KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > codehaus > loom > xmlpolicy > builder > PolicyBuilder


1 /*
2  * Copyright (C) The Spice Group. All rights reserved.
3  *
4  * This software is published under the terms of the Spice
5  * Software License version 1.1, a copy of which has been included
6  * with this distribution in the LICENSE.txt file.
7  */

8 package org.codehaus.loom.xmlpolicy.builder;
9
10 import java.io.InputStream JavaDoc;
11 import java.lang.reflect.Constructor JavaDoc;
12 import java.net.MalformedURLException JavaDoc;
13 import java.net.URL JavaDoc;
14 import java.security.CodeSource JavaDoc;
15 import java.security.KeyStore JavaDoc;
16 import java.security.KeyStoreException JavaDoc;
17 import java.security.Permission JavaDoc;
18 import java.security.Policy JavaDoc;
19 import java.security.UnresolvedPermission JavaDoc;
20 import java.security.cert.Certificate JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.PropertyPermission JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27
28 import org.codehaus.loom.xmlpolicy.metadata.GrantMetaData;
29 import org.codehaus.loom.xmlpolicy.metadata.KeyStoreMetaData;
30 import org.codehaus.loom.xmlpolicy.metadata.PermissionMetaData;
31 import org.codehaus.loom.xmlpolicy.metadata.PolicyMetaData;
32
33 /**
34  * A Utility class that builds a Policy object from a specified
35  * PolicyMetaData.
36  *
37  * @author Peter Donald
38  * @version $Revision: 1.1 $ $Date: 2004/04/19 22:20:25 $
39  */

40 public class PolicyBuilder
41 {
42     /**
43      * Build a policy for a specified meta data.
44      *
45      * @param policy the policy metadata
46      * @return the Policy object
47      * @throws Exception if unable to create Policy object
48      */

49     public Policy JavaDoc buildPolicy( final PolicyMetaData policy,
50                                final PolicyResolver resolver )
51         throws Exception JavaDoc
52     {
53         if( null == policy )
54         {
55             throw new NullPointerException JavaDoc( "policy" );
56         }
57         if( null == resolver )
58         {
59             throw new NullPointerException JavaDoc( "resolver" );
60         }
61
62         final Map JavaDoc keyStores =
63             createKeyStores( policy.getKeyStores(), resolver );
64         final Map JavaDoc grants = new HashMap JavaDoc();
65         processGrants( policy.getGrants(), keyStores, grants, resolver );
66
67         final CodeSource JavaDoc codeSource = createDefaultCodeSource();
68         final Permission JavaDoc[] permissions = getDefaultPermissions();
69         grants.put( codeSource, permissions );
70
71         return resolver.createPolicy( grants );
72     }
73
74     /**
75      * Porcess all the grants and build up a grant map.
76      *
77      * @param metaDatas the metadata
78      * @param keyStores the configured keystores
79      * @param grants the grant map
80      * @param resolver the resolver to use to resolve locations etc
81      * @throws Exception if unable to create grant map
82      */

83     private void processGrants( final GrantMetaData[] metaDatas,
84                                 final Map JavaDoc keyStores,
85                                 final Map JavaDoc grants,
86                                 final PolicyResolver resolver )
87         throws Exception JavaDoc
88     {
89         for( int i = 0; i < metaDatas.length; i++ )
90         {
91             processGrant( metaDatas[ i ], keyStores, grants, resolver );
92         }
93     }
94
95     /**
96      * Porcess a grants and add to the grant map.
97      *
98      * @param metaData the metadata
99      * @param keyStores the configured keystores
100      * @param grants the grant map
101      * @param resolver the resolver to use to resolve locations etc
102      * @throws Exception if unable to create grant map
103      */

104     private void processGrant( final GrantMetaData metaData,
105                                final Map JavaDoc keyStores,
106                                final Map JavaDoc grants,
107                                final PolicyResolver resolver )
108         throws Exception JavaDoc
109     {
110         final URL JavaDoc url =
111             resolver.resolveLocation( metaData.getCodebase() );
112
113         final Certificate JavaDoc[] signers =
114             getSigners( metaData.getSignedBy(),
115                         metaData.getKeyStore(),
116                         keyStores );
117         final CodeSource JavaDoc codeSource = new CodeSource JavaDoc( url, signers );
118
119         final Permission JavaDoc[] permissions =
120             createPermissions( metaData.getPermissions(),
121                                keyStores );
122         grants.put( codeSource, permissions );
123     }
124
125     /**
126      * Create all permissions for specified metadata.
127      *
128      * @param metaDatas the metadata
129      * @param keyStores the keystores to use when loading signers
130      * @return the created permissions
131      * @throws Exception if unabel to create permissions
132      */

133     private Permission JavaDoc[] createPermissions( final PermissionMetaData[] metaDatas,
134                                             final Map JavaDoc keyStores )
135         throws Exception JavaDoc
136     {
137         final List JavaDoc set = new ArrayList JavaDoc();
138
139         for( int i = 0; i < metaDatas.length; i++ )
140         {
141             final Permission JavaDoc permission =
142                 createPermission( metaDatas[ i ], keyStores );
143             set.add( permission );
144         }
145
146         return (Permission JavaDoc[])set.toArray( new Permission JavaDoc[ set.size() ] );
147     }
148
149     /**
150      * Create a permission for metadata.
151      *
152      * @param metaData the permission metadata
153      * @param keyStores the keystore to use (if needed)
154      * @return the created permission
155      * @throws Exception if unable to create permission
156      */

157     private Permission JavaDoc createPermission( final PermissionMetaData metaData,
158                                          final Map JavaDoc keyStores )
159         throws Exception JavaDoc
160     {
161         final String JavaDoc type = metaData.getClassname();
162         final String JavaDoc actions = metaData.getAction();
163         final String JavaDoc signedBy = metaData.getSignedBy();
164         final String JavaDoc keyStoreName = metaData.getKeyStore();
165         final String JavaDoc target = metaData.getTarget();
166
167         final Certificate JavaDoc[] signers =
168             getSigners( signedBy, keyStoreName, keyStores );
169         return createPermission( type, target, actions, signers );
170     }
171
172     /**
173      * Create a mpa of keystores from specified metadata.
174      *
175      * @param metaDatas the metadata
176      * @return the keystore map
177      * @throws Exception if unable to create all keystores
178      */

179     private Map JavaDoc createKeyStores( final KeyStoreMetaData[] metaDatas,
180                                  final PolicyResolver resolver )
181         throws Exception JavaDoc
182     {
183         final Map JavaDoc keyStores = new HashMap JavaDoc();
184
185         for( int i = 0; i < metaDatas.length; i++ )
186         {
187             final KeyStoreMetaData metaData = metaDatas[ i ];
188             final String JavaDoc name = metaData.getName();
189
190             try
191             {
192                 final URL JavaDoc url =
193                     resolver.resolveLocation( metaData.getLocation() );
194                 final KeyStore JavaDoc keyStore =
195                     createKeyStore( metaData.getType(), url );
196
197                 keyStores.put( name, keyStore );
198             }
199             catch( final Exception JavaDoc e )
200             {
201                 final String JavaDoc message =
202                     "Error creating keystore " + name + ". Due to " + e;
203                 throw new Exception JavaDoc( message );
204             }
205         }
206
207         return keyStores;
208     }
209
210     /**
211      * Create a permission of specified class and
212      * with specified target, action and signers.
213      *
214      * @param type the classname of Permission object
215      * @param target the target of permission
216      * @param actions the actions allowed on permission (if any)
217      * @param signers the signers (if any)
218      * @return the created Permission object
219      * @throws Exception if unable to create permission
220      */

221     private final Permission JavaDoc createPermission( final String JavaDoc type,
222                                                final String JavaDoc target,
223                                                final String JavaDoc actions,
224                                                final Certificate JavaDoc[] signers )
225         throws Exception JavaDoc
226     {
227         if( null != signers )
228         {
229             return new UnresolvedPermission JavaDoc( type, target, actions, signers );
230         }
231
232         try
233         {
234             final Class JavaDoc clazz = Class.forName( type );
235
236             Class JavaDoc paramClasses[] = null;
237             Object JavaDoc params[] = null;
238
239             if( null == actions && null == target )
240             {
241                 paramClasses = new Class JavaDoc[ 0 ];
242                 params = new Object JavaDoc[ 0 ];
243             }
244             else if( null == actions )
245             {
246                 paramClasses = new Class JavaDoc[ 1 ];
247                 paramClasses[ 0 ] = String JavaDoc.class;
248                 params = new Object JavaDoc[ 1 ];
249                 params[ 0 ] = target;
250             }
251             else
252             {
253                 paramClasses = new Class JavaDoc[ 2 ];
254                 paramClasses[ 0 ] = String JavaDoc.class;
255                 paramClasses[ 1 ] = String JavaDoc.class;
256                 params = new Object JavaDoc[ 2 ];
257                 params[ 0 ] = target;
258                 params[ 1 ] = actions;
259             }
260
261             final Constructor JavaDoc constructor = clazz.getConstructor( paramClasses );
262             return (Permission JavaDoc)constructor.newInstance( params );
263         }
264         catch( final ClassNotFoundException JavaDoc cnfe )
265         {
266             return new UnresolvedPermission JavaDoc( type, target, actions, signers );
267         }
268     }
269
270     /**
271      * Create a keystore of specified type and loading from specified url.
272      *
273      * @param type the type of key store
274      * @param url the location of key store data
275      * @return the create and configured keystore
276      * @throws Exception if unable to create or load keystore
277      */

278     protected KeyStore JavaDoc createKeyStore( final String JavaDoc type,
279                                        final URL JavaDoc url )
280         throws Exception JavaDoc
281     {
282         final KeyStore JavaDoc keyStore = KeyStore.getInstance( type );
283         final InputStream JavaDoc ins = url.openStream();
284         keyStore.load( ins, null );
285         return keyStore;
286     }
287
288     /**
289      * Retrieve Certificates for specified signers
290      * as loaded from keyStore.
291      *
292      * @param signedBy the signers
293      * @param keyStoreName the name of keystore
294      * @param keyStores the list of keystores to lookup
295      * @return the certificates
296      * @throws Exception if unable to get signers
297      */

298     private Certificate JavaDoc[] getSigners( final String JavaDoc signedBy,
299                                       final String JavaDoc keyStoreName,
300                                       final Map JavaDoc keyStores )
301         throws Exception JavaDoc
302     {
303         if( null == signedBy )
304         {
305             return null;
306         }
307         else
308         {
309             final KeyStore JavaDoc keyStore = getKeyStore( keyStoreName, keyStores );
310             return getCertificates( signedBy, keyStore );
311         }
312     }
313
314     /**
315      * Retrieve the set of Ceritificates for all signers.
316      *
317      * @param signedBy the comma separated list of signers
318      * @param keyStore the keystore to look for signers certificates in
319      * @return the certificate set
320      * @throws Exception if unabel to create certificates
321      */

322     private Certificate JavaDoc[] getCertificates( final String JavaDoc signedBy,
323                                            final KeyStore JavaDoc keyStore )
324         throws Exception JavaDoc
325     {
326         final List JavaDoc certificateSet = new ArrayList JavaDoc();
327
328         final StringTokenizer JavaDoc st = new StringTokenizer JavaDoc( signedBy, "," );
329         while( st.hasMoreTokens() )
330         {
331             final String JavaDoc alias = st.nextToken().trim();
332             Certificate JavaDoc certificate = null;
333
334             try
335             {
336                 certificate = keyStore.getCertificate( alias );
337             }
338             catch( final KeyStoreException JavaDoc kse )
339             {
340                 final String JavaDoc message =
341                     "Unable to get certificate for alias " +
342                     alias + " due to " + kse;
343                 throw new Exception JavaDoc( message );
344             }
345
346             if( null == certificate )
347             {
348                 final String JavaDoc message =
349                     "Missing certificate for alias " + alias;
350                 throw new Exception JavaDoc( message );
351             }
352
353             if( !certificateSet.contains( certificate ) )
354             {
355                 certificateSet.add( certificate );
356             }
357         }
358
359         return (Certificate JavaDoc[])certificateSet.toArray( new Certificate JavaDoc[ certificateSet.size() ] );
360     }
361
362     /**
363      * Retrieve keystore with specified name from map.
364      * If missing throw an exception.
365      *
366      * @param keyStoreName the name of key store
367      * @param keyStores the map of stores
368      * @return the keystore
369      * @throws Exception thrown if unable to locate keystore
370      */

371     private KeyStore JavaDoc getKeyStore( final String JavaDoc keyStoreName, final Map JavaDoc keyStores ) throws Exception JavaDoc
372     {
373         final KeyStore JavaDoc keyStore = (KeyStore JavaDoc)keyStores.get( keyStoreName );
374         if( null == keyStore )
375         {
376             final String JavaDoc message = "Missing keystore named: " + keyStoreName;
377             throw new Exception JavaDoc( message );
378         }
379         else
380         {
381             return keyStore;
382         }
383     }
384
385     /**
386      * A utility method to get a default codesource
387      * that covers all files on fielsystem
388      *
389      * @return the code source
390      */

391     private CodeSource JavaDoc createDefaultCodeSource()
392     {
393         //Create a URL that covers whole file system.
394
final URL JavaDoc url;
395         try
396         {
397             url = new URL JavaDoc( "file:/-" );
398         }
399         catch( final MalformedURLException JavaDoc mue )
400         {
401             //will never happen
402
throw new IllegalStateException JavaDoc( mue.getMessage() );
403         }
404         final CodeSource JavaDoc codeSource = new CodeSource JavaDoc( url, null );
405         return codeSource;
406     }
407
408     /**
409      * A utility method to get all the default permissions.
410      */

411     private Permission JavaDoc[] getDefaultPermissions()
412     {
413         final ArrayList JavaDoc list = new ArrayList JavaDoc();
414         //these properties straight out ot ${java.home}/lib/security/java.policy
415
list.add( new PropertyPermission JavaDoc( "os.name", "read" ) );
416         list.add( new PropertyPermission JavaDoc( "os.arch", "read" ) );
417         list.add( new PropertyPermission JavaDoc( "os.version", "read" ) );
418         list.add( new PropertyPermission JavaDoc( "file.separator", "read" ) );
419         list.add( new PropertyPermission JavaDoc( "path.separator", "read" ) );
420         list.add( new PropertyPermission JavaDoc( "line.separator", "read" ) );
421
422         list.add( new PropertyPermission JavaDoc( "java.version", "read" ) );
423         list.add( new PropertyPermission JavaDoc( "java.vendor", "read" ) );
424         list.add( new PropertyPermission JavaDoc( "java.vendor.url", "read" ) );
425
426         list.add( new PropertyPermission JavaDoc( "java.class.version", "read" ) );
427         list.add( new PropertyPermission JavaDoc( "java.vm.version", "read" ) );
428         list.add( new PropertyPermission JavaDoc( "java.vm.vendor", "read" ) );
429         list.add( new PropertyPermission JavaDoc( "java.vm.name", "read" ) );
430
431         list.add( new PropertyPermission JavaDoc( "java.specification.version", "read" ) );
432         list.add( new PropertyPermission JavaDoc( "java.specification.vendor", "read" ) );
433         list.add( new PropertyPermission JavaDoc( "java.specification.name", "read" ) );
434         list.add( new PropertyPermission JavaDoc( "java.vm.specification.version", "read" ) );
435         list.add( new PropertyPermission JavaDoc( "java.vm.specification.vendor", "read" ) );
436         list.add( new PropertyPermission JavaDoc( "java.vm.specification.name", "read" ) );
437
438         return (Permission JavaDoc[])list.toArray( new Permission JavaDoc[ list.size() ] );
439     }
440 }
441
Popular Tags