KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > security > store > IdentityManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.security.store;
24
25 import com.sun.enterprise.util.SystemPropertyConstants;
26
27 import java.io.BufferedReader JavaDoc;
28 import java.io.InputStreamReader JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.File JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.io.OutputStreamWriter JavaDoc;
34 import java.io.PrintWriter JavaDoc;
35 import java.io.BufferedWriter JavaDoc;
36 import java.util.Hashtable JavaDoc;
37 import java.util.HashMap JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Properties JavaDoc;
42 import java.security.cert.CertificateException JavaDoc;
43 import java.security.KeyStoreException JavaDoc;
44 import java.security.NoSuchAlgorithmException JavaDoc;
45 import java.security.UnrecoverableKeyException JavaDoc;
46
47 public class IdentityManager {
48
49     public static final String JavaDoc PROPMPT_FOR_IDENTITY_SYSTEM_PROPERTY = "com.sun.aas.promptForIdentity";
50     private static final String JavaDoc USER_ALIAS="admin-user";
51     private static final String JavaDoc PASSWORD_ALIAS="admin-password";
52     private static final String JavaDoc MASTER_PASSWORD_ALIAS="master-password";
53     private static final String JavaDoc IDENTITY_STORE_FILE_NAME=".identity";
54
55     private static String JavaDoc _user=null;
56     private static String JavaDoc _password=null;
57     private static String JavaDoc _masterPassword=null;
58     private static Hashtable JavaDoc _htIdentity=new Hashtable JavaDoc();
59     private static boolean bDebug=false;
60     private static boolean _keystorePropertyWasSet = true;
61     private static boolean _truststorePropertyWasSet = true;
62     private static boolean _nssDbPasswordPropertyWasSet = true;
63
64     // make private so it can't be instantiated
65
private IdentityManager() {}
66
67     /**
68      * getIdentityArray - This method is used when the identity information
69      * needs to be passed to another process
70      */

71     public static String JavaDoc[] getIdentityArray() {
72         ArrayList JavaDoc ar=new ArrayList JavaDoc();
73         // add in standard values
74
ar.add(getUser());
75         ar.add(getPassword());
76         ar.add(getMasterPassword());
77         
78         // add in other identity info
79
Iterator JavaDoc it=_htIdentity.keySet().iterator();
80         String JavaDoc key=null;
81         while(it.hasNext()) {
82             key=(String JavaDoc)it.next();
83             ar.add(key + "=" + (String JavaDoc)_htIdentity.get(key));
84         }
85         
86         String JavaDoc[] identity=new String JavaDoc[ar.size()];
87         identity=(String JavaDoc[])ar.toArray(identity);
88
89         return identity;
90     }
91
92    
93     /**
94     * populateFromInputStream - This method uses the stdin to populate the variables
95     * of this class in the order user, password, masterpassword
96     */

97     public static void populateFromInputStream() throws IOException JavaDoc {
98         populateFromInputStream(System.in);
99     }
100
101
102     /**
103     * populateFromInputStream - This method uses the passed in InputStream to populate the variables
104     * of this class in the order user, password, masterpassword
105     */

106     public static void populateFromInputStream(InputStream JavaDoc in) throws IOException JavaDoc {
107
108         // if not input stream or read identity is not enables (usually processLauncher.xml)
109
// then retirn. Wanted to make sure we could turn of the prompting if java command ran from
110
// comman line
111
if (bDebug) System.out.println("IM seeing if need to read in security properties from stdin");
112         if (in == null || System.getProperty(PROPMPT_FOR_IDENTITY_SYSTEM_PROPERTY) == null) {
113             return;
114         }
115
116         BufferedReader JavaDoc br=null;
117         try {
118             // read in each line and populate structure in the order user, password, masterpassword
119
if (bDebug) System.out.println("IM attempting to read from inputstream");
120             br=new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
121             String JavaDoc sxLine=null;
122             int cnt=0, ipos=0;
123             // help for users who are not running the command through the exposed asadmin command
124
System.out.println("Enter Admin User:");
125             while ((sxLine=br.readLine()) != null) {
126                 if (bDebug) System.out.println("IM Number read - Reading Line:" + cnt + " - " + sxLine);
127                 
128                 // get input lines from process if any
129
switch (cnt) {
130                     case 0:
131                         setUser(sxLine);
132                         // print next prompt
133
System.out.println("Enter Admin Password:");
134                         break;
135                     case 1:
136                         setPassword(sxLine);
137                         // print next prompt
138
System.out.println("Enter Master Password:");
139                         break;
140                     case 2:
141                         setMasterPassword(sxLine);
142                         System.out.println("Enter Other Password Information (or ctrl-D or ctrl-Z):");
143                         break;
144                     default:
145                         // see if tokenized string separated by and "="
146
putTokenizedString(sxLine) ;
147                         System.out.println("Enter Other Password Information (or ctrl-D or ctrl-Z):");
148                 }
149                 // increment cound for next input field
150
cnt++;
151
152             }
153         } catch (IOException JavaDoc e) {
154             throw e;
155         }
156     }
157
158     
159     /**
160      * writeToOutputStream - This method is used to writeout the contents of this class
161      * to the outputstream
162      */

163     public static void writeToOutputStream(OutputStream JavaDoc out) {
164         // return if no output
165
if (out == null) return;
166         
167         PrintWriter JavaDoc writer=null;
168         // open the output stream
169
writer = new PrintWriter JavaDoc(new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(out)));
170         if (bDebug) System.out.println("Writing to OutputStream: " + getFormatedContents());
171         // get input lines from process if any
172
writer.println(getUser());
173         writer.println(getPassword());
174         writer.println(getMasterPassword());
175
176         // add in other identity items
177
Iterator JavaDoc it=_htIdentity.keySet().iterator();
178         String JavaDoc key=null;
179         while(it.hasNext()) {
180             key=(String JavaDoc)it.next();
181             writer.println(key + "=" + (String JavaDoc)_htIdentity.get(key));
182         }
183         writer.flush();
184         writer.close();
185     }
186     
187     
188     /**
189      * This method is used instead of the toString method for static instances
190      */

191     public static String JavaDoc getFormatedContents() {
192         StringBuffer JavaDoc sb=new StringBuffer JavaDoc("IdentityManager Data: User:" + getUser());
193         //Only display password information if compiling with debug enabled; otherwise, this
194
//is a security violation.
195
if (bDebug) {
196             sb.append(", ");
197             sb.append("Password:" + getPassword() + ", ");
198             sb.append("MasterPassword:" + getMasterPassword() + ", ");
199             Iterator JavaDoc it=_htIdentity.keySet().iterator();
200             String JavaDoc key=null;
201             while(it.hasNext()) {
202                 key=(String JavaDoc)it.next();
203                 sb.append(key + ":" + (String JavaDoc)_htIdentity.get(key) + ", ");
204             }
205         }
206         return sb.toString();
207     }
208     
209     
210     //
211
// public access and mutators for convienence
212
public static void setUser(String JavaDoc userx) {
213         _user=userx;
214     }
215     public static String JavaDoc getUser() {
216         return _user;
217     }
218
219     public static void setPassword(String JavaDoc passwordx) {
220         _password=passwordx;
221     }
222     
223     public static String JavaDoc getPassword() {
224         return _password;
225     }
226
227     public static void setMasterPassword(String JavaDoc masterPasswordx) {
228         _masterPassword=masterPasswordx;
229         //We set the keystore and truststore password properties (used for JSSE)
230
//to the master password value if they are not already set. This is necessary
231
//for PE only and not for SE/EE since NSS is used.
232
//The xxxWasSet booleans keep track of whether the system property was initially set
233
//(e.g. in domain.xml). When false, this indicates that we have set the property and
234
//that we should continue to set it if the master password is changed. This is necessary
235
//since the master password can be changed (e.g. asadmin change-master-password) and
236
//setMasterPassword called multiple times.
237
if (System.getProperty(SystemPropertyConstants.KEYSTORE_PROPERTY) != null) {
238             if (!_keystorePropertyWasSet ||
239                 System.getProperty(SystemPropertyConstants.KEYSTORE_PASSWORD_PROPERTY) == null)
240             {
241                 System.setProperty(SystemPropertyConstants.KEYSTORE_PASSWORD_PROPERTY,
242                     getMasterPassword());
243                 _keystorePropertyWasSet = false;
244             }
245         }
246         if (System.getProperty(SystemPropertyConstants.TRUSTSTORE_PROPERTY) != null) {
247             if (!_truststorePropertyWasSet ||
248                 System.getProperty(SystemPropertyConstants.TRUSTSTORE_PASSWORD_PROPERTY) == null)
249             {
250                 System.setProperty(SystemPropertyConstants.TRUSTSTORE_PASSWORD_PROPERTY,
251                     getMasterPassword());
252                 _truststorePropertyWasSet = false;
253             }
254         }
255         if (System.getProperty(SystemPropertyConstants.NSS_DB_PROPERTY) != null) {
256             if (!_nssDbPasswordPropertyWasSet ||
257                 System.getProperty(SystemPropertyConstants.NSS_DB_PASSWORD_PROPERTY) == null)
258             {
259                 System.setProperty(SystemPropertyConstants.NSS_DB_PASSWORD_PROPERTY,
260                     getMasterPassword());
261                 _nssDbPasswordPropertyWasSet = false;
262             }
263         }
264     }
265
266     
267     public static String JavaDoc getMasterPassword() {
268         return _masterPassword;
269     }
270     
271     
272     public static void putTokenizedString(String JavaDoc sxToken) {
273         // put value in mapped file for use by nssutils and unknown numbers of input
274
// see if tokenized string separated by and "="
275
int ipos=sxToken.indexOf("=");
276         if (ipos > 0) {
277             // break into key value pair and put into map
278
put(sxToken.substring(0, ipos), sxToken.substring(ipos + 1));
279         }
280     }
281     
282     
283     public static void put(String JavaDoc key, String JavaDoc value) {
284         // put value in mapped file for use by nssutils and unknown numbers of input
285
_htIdentity.put(key, value);
286     }
287
288     public static String JavaDoc get(String JavaDoc key) {
289         return (String JavaDoc)_htIdentity.get(key);
290     }
291
292     public static void addToMap(HashMap JavaDoc map)
293     {
294         Iterator JavaDoc it = map.keySet().iterator();
295         String JavaDoc key = null;
296         while(it.hasNext()) {
297             key = (String JavaDoc)it.next();
298             put(key, (String JavaDoc)map.get(key));
299         }
300     }
301     
302     public static Map JavaDoc getMap() {
303         // create a deep copy of the map so it can't be
304
// side effected by a thirdparty util
305
HashMap JavaDoc hm=new HashMap JavaDoc();
306         Iterator JavaDoc it=_htIdentity.keySet().iterator();
307         String JavaDoc key=null;
308         while(it.hasNext()) {
309             key=(String JavaDoc)it.next();
310             hm.put(new String JavaDoc(key), new String JavaDoc((String JavaDoc)_htIdentity.get(key)));
311         }
312         return hm;
313     }
314     
315     
316     
317     
318     
319     
320     //
321
// these methods write out the identitymanager so it cab be read in later
322

323     /**
324      * createIdentityStore - This method takes the IdentityManager singleton and
325      * writes its information into a keystore for later retrieval. This method is used for temportary
326      * storage of Identity information for use by task such as restart. The extra token information
327      * is read in through the appropriate manager because its variable nature was problematic to store.
328      */

329      public static void createIdentityStore()
330         throws KeyStoreException JavaDoc, CertificateException JavaDoc, NoSuchAlgorithmException JavaDoc, IOException JavaDoc
331      {
332
333         // create temporary keystore for start to read from
334
Properties JavaDoc aliasPasswordProps=new Properties JavaDoc();
335         aliasPasswordProps.setProperty(USER_ALIAS, getUser());
336         aliasPasswordProps.setProperty(PASSWORD_ALIAS, getPassword());
337         aliasPasswordProps.setProperty(MASTER_PASSWORD_ALIAS, getMasterPassword());
338         
339         File JavaDoc instanceRoot = new File JavaDoc(System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY), IDENTITY_STORE_FILE_NAME);
340
341         // get the password for the keystore
342
PasswordAdapter p = new PasswordAdapter(instanceRoot.getAbsolutePath(),
343            getMasterPasswordPassword());
344
345         // loop through properties and set passwords for aliases
346
Iterator JavaDoc iter=aliasPasswordProps.keySet().iterator();
347         String JavaDoc alias=null, pass=null;
348         while(iter.hasNext()) {
349             alias=(String JavaDoc)iter.next();
350             pass=aliasPasswordProps.getProperty(alias);
351             p.setPasswordForAlias(alias, pass.getBytes());
352         }
353     }
354      
355      
356     /**
357      * readIdentityManagerFile - This method us used to populate the IdentityManager singleton and
358      * reas its information from a keystore that was previously created. This method is used to retrieve
359      * temportarily storaged Identity information for use by task such as restart. The extra token information
360      * is read in through the appropriate manager because its variable nature was problematic to store.
361      */

362     public static void readIdentityStore()
363         throws KeyStoreException JavaDoc, CertificateException JavaDoc, NoSuchAlgorithmException JavaDoc, IOException JavaDoc, UnrecoverableKeyException JavaDoc
364     {
365         
366         
367         File JavaDoc instanceRoot = new File JavaDoc(System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY), IDENTITY_STORE_FILE_NAME);
368         
369         System.out.println("****** READING IDENTITY FROM ====>" + instanceRoot.getAbsolutePath());
370         
371         if (instanceRoot.exists()) {
372             PasswordAdapter p = new PasswordAdapter(instanceRoot.getAbsolutePath(),
373                 getMasterPasswordPassword());
374
375             setUser(p.getPasswordForAlias(USER_ALIAS));
376             setPassword(p.getPasswordForAlias(PASSWORD_ALIAS));
377             setMasterPassword(p.getPasswordForAlias(MASTER_PASSWORD_ALIAS));
378         }
379     }
380      
381     
382     
383     public static void deleteIdentityStore() {
384         File JavaDoc instanceRoot = new File JavaDoc(System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY), IDENTITY_STORE_FILE_NAME);
385         instanceRoot.delete();
386     }
387     
388     
389     
390     /**
391      *
392      * @return The password protecting the master password keywtore
393      */

394     private static char[] getMasterPasswordPassword()
395     {
396         //FIXTHIS: Need a better password which varies across machines but is not the ip address.
397
return MASTER_PASSWORD_ALIAS.toCharArray();
398     }
399    
400      
401 }
402
Popular Tags