KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > security > SecurityUtil


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;
24
25 import java.lang.*;
26 import java.security.*;
27 import java.lang.reflect.*;
28 import java.io.File JavaDoc;
29 import java.util.Set JavaDoc;
30 import java.util.HashSet JavaDoc;
31
32 import javax.security.auth.Subject JavaDoc;
33 import javax.security.jacc.*;
34
35 import com.sun.enterprise.deployment.Application;
36 import com.sun.enterprise.SecurityManager;
37 import com.sun.enterprise.security.application.EJBSecurityManager;
38 import com.sun.enterprise.server.pluggable.PluggableFeatureFactoryImpl;
39 import com.sun.enterprise.server.pluggable.SecuritySupport;
40 import com.sun.ejb.Container;
41 import com.sun.ejb.Invocation;
42 import com.sun.enterprise.security.util.IASSecurityException;
43 import com.sun.logging.LogDomains;
44 import com.sun.enterprise.util.LocalStringManagerImpl;
45 import com.sun.logging.*;
46 import java.util.logging.*;
47 import com.sun.web.security.WebSecurityManagerFactory;
48 /**
49   * This utility class encloses all the calls to a ejb method
50   * in a specified subject
51   * @author Harpreet Singh
52   * @author Shing Wai Chan
53   */

54 public class SecurityUtil{
55
56     private static LocalStringManagerImpl localStrings =
57     new LocalStringManagerImpl(SecurityUtil.class);
58     private static Logger _logger =
59         LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
60     public static String JavaDoc VENDOR_PRESENT =
61     "com.sun.enterprise.security.provider.jaccvendorpresent";
62     private static boolean vendorPresent = Boolean.getBoolean(VENDOR_PRESENT);
63     // The repository is defined in PolicyFileMgr.
64
// It is repeated here since JACC provider is not reference directly.
65
public static String JavaDoc repository = System.getProperty("com.sun.enterprise.jaccprovider.property.repository");
66     // private static LocalStringManagerImpl localStrings =
67
// new LocalStringManagerImpl(SecurityUtil.class);
68

69     /** This method is called from the generated code to execute the
70      * method. This is a translation of method.invoke that the
71      * generated code needs to do, to invoke a particular ejb
72      * method. The method is invoked under a security Subject. This
73      * method is called from the generated code.
74      * @param Method beanClassMethod, the bean class method to be invoked
75      * @param Invocation inv, the current invocation object
76      * @param Object o, the object on which this method needs to be invoked,
77      * @param Object[] oa, the parameters to the methods,
78      * @param Container c, the container from which the appropriate subject is
79      * queried from.
80      */

81     public static Object JavaDoc runMethod(Method beanClassMethod, Invocation inv, Object JavaDoc o, Object JavaDoc[] oa, Container c)
82     throws Throwable JavaDoc {
83
84         final Method meth = beanClassMethod;
85         final Object JavaDoc obj = o;
86         final Object JavaDoc[] objArr = oa;
87         Object JavaDoc ret;
88         EJBSecurityManager mgr = (EJBSecurityManager) c.getSecurityManager();
89         if (mgr == null) {
90         throw new SecurityException JavaDoc("SecurityManager not set");
91         }
92
93             // Optimization. Skip doAsPrivileged call if this is a local
94
// invocation and the target ejb uses caller identity or the
95
// System Security Manager is disabled.
96
// Still need to execute it within the target bean's policy context.
97
// see CR 6331550
98
if((inv.isLocal && mgr.getUsesCallerIdentity()) ||
99            System.getSecurityManager() == null) {
100                 ret = mgr.runMethod(meth, obj, objArr);
101             } else {
102                 try {
103                     PrivilegedExceptionAction pea =
104                         new PrivilegedExceptionAction(){
105                             public java.lang.Object JavaDoc run() throws Exception JavaDoc {
106                                 return meth.invoke(obj, objArr);
107                             }
108                         };
109
110                     ret = mgr.doAsPrivileged(pea);
111                 } catch(PrivilegedActionException pae) {
112                     Throwable JavaDoc cause = pae.getCause();
113                     if( cause instanceof InvocationTargetException ) {
114                         cause = ((InvocationTargetException) cause).getCause();
115                     }
116                     throw cause;
117                 }
118             }
119         return ret;
120     }
121     /**
122      * This method is similiar to the runMethod, except it keeps the
123      * semantics same as the one in reflection. On failure, if the
124      * exception is caused due to reflection, it returns the
125      * InvocationTargetException. This method is called from the
126      * containers for ejbTimeout, WebService and MDBs.
127      * @param Method beanClassMethod, the bean class method to be invoked
128      * @param Invocation inv, the current invocation
129      * @param Object o, the object on which this method is to be
130      * invoked in this case the ejb,
131      * @param Object[] oa, the parameters for the method,
132      * @param Container c, the container instance,
133      * @param SecurityManager sm, security manager for this container,
134      * can be a null value, where in the container will be queried to
135      * find its security manager.
136      * @return Object, the result of the execution of the method.
137      */

138     public static Object JavaDoc invoke(Method beanClassMethod, Invocation inv, Object JavaDoc o, Object JavaDoc[] oa, Container c,
139                            SecurityManager JavaDoc mgr) throws Throwable JavaDoc {
140     
141     final Method meth = beanClassMethod;
142     final Object JavaDoc obj = o;
143     final Object JavaDoc[] objArr = oa;
144     Object JavaDoc ret = null;
145         EJBSecurityManager ejbSecMgr = null;
146
147     if(mgr == null) {
148         if (c != null) {
149         ejbSecMgr = (EJBSecurityManager) c.getSecurityManager();
150         }
151         if (ejbSecMgr == null) {
152         throw new SecurityException JavaDoc("SecurityManager not set");
153         }
154     } else {
155             ejbSecMgr = (EJBSecurityManager) mgr;
156         }
157
158         // Optimization. Skip doAsPrivileged call if this is a local
159
// invocation and the target ejb uses caller identity or the
160
// System Security Manager is disabled.
161
// Still need to execute it within the target bean's policy context.
162
// see CR 6331550
163
if((inv.isLocal && ejbSecMgr.getUsesCallerIdentity()) ||
164        System.getSecurityManager() == null) {
165             ret = ejbSecMgr.runMethod(meth, obj, objArr);
166         } else {
167
168             PrivilegedExceptionAction pea =
169                 new PrivilegedExceptionAction(){
170                     public java.lang.Object JavaDoc run() throws Exception JavaDoc {
171                         return meth.invoke(obj, objArr);
172                     }
173                 };
174  
175             try {
176                 ret = ejbSecMgr.doAsPrivileged(pea);
177             } catch(PrivilegedActionException pae) {
178                 Throwable JavaDoc cause = pae.getCause();
179                 throw cause;
180             }
181         }
182     return ret;
183     }
184
185      /** This method obtains the policy configuration object
186      * corresponding to the name, and causes the corresponding policy
187      * statements to be put in service. This method also informs the
188      * policy module to refresh its in service policy contexts.
189      * Note that policy statements have already been
190      * added to the pc, this method works to put them in Service.
191      * @param String name - the module id which serves to identify
192      * the corresponding policy context. The name shall not be null.
193      * If the underlying PolicyModule is the RI PolicyModule,
194      * A SecurityRoleMapper must have been bound to the policy context
195      * before this method is called or the embedded call to pc.commit will
196      * throw an exception.
197      */

198     public static void generatePolicyFile(String JavaDoc name) throws IASSecurityException {
199
200     assert name != null;
201
202     if (name == null) {
203         throw new IASSecurityException("Invalid Module Name");
204     }
205
206     try {
207
208         boolean inService =
209         PolicyConfigurationFactory.getPolicyConfigurationFactory().
210         inService(name);
211
212         if (!inService) {
213
214         // find the PolicyConfig using remove=false to ensure policy stmts
215
// are retained.
216

217         // Note that it is presumed that the pc exists, and that
218
// it is populated with the desired policy statements.
219
// If this is not true, the call to commit will not
220
// result in the correct policy statements being made
221
// available to the policy module.
222

223
224                 PolicyConfigurationFactory pcf =
225                     PolicyConfigurationFactory.getPolicyConfigurationFactory();
226                 PolicyConfiguration pc =
227             pcf.getPolicyConfiguration(name, false);
228                 
229         pc.commit();
230
231         if (_logger.isLoggable(Level.FINE)){
232             _logger.fine("JACC: committed policy for context: "+name);
233         }
234         }
235      
236         Policy.getPolicy().refresh();
237
238     } catch(java.lang.ClassNotFoundException JavaDoc cnfe){
239         String JavaDoc msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
240         throw new IASSecurityException(msg);
241     } catch(javax.security.jacc.PolicyContextException JavaDoc pce){
242         throw new IASSecurityException(pce.toString());
243     }
244     }
245
246     /**
247      * Inform the policy module to take the named policy context out of service.
248      * The policy context is transitioned to the deleted state. In our provider
249      * implementation, the corresponding policy file is deleted, as the presence
250      * of a policy file in the repository is how we persistently remember which
251      * policy contexts are in service.
252      * @param String name - the module id which serves to identify
253      * the corresponding policy context. The name shall not be null.
254      */

255     public static void removePolicy(String JavaDoc name) throws IASSecurityException {
256
257     assert name != null;
258
259     if (name == null) {
260         throw new IASSecurityException("Invalid Module Name");
261     }
262
263     try {
264
265         boolean wasInService =
266         PolicyConfigurationFactory.getPolicyConfigurationFactory().
267         inService(name);
268         
269         // find the PolicyConfig and delete it.
270

271         PolicyConfiguration pc =
272         PolicyConfigurationFactory.getPolicyConfigurationFactory().
273         getPolicyConfiguration(name, false);
274
275         pc.delete();
276             // remove from the cache...
277
WebSecurityManagerFactory.getInstance().removeWebSecurityManager(name);
278
279         // Only do refresh policy if the deleted context was in service
280

281         if (wasInService) {
282         Policy.getPolicy().refresh();
283         }
284
285     } catch(java.lang.ClassNotFoundException JavaDoc cnfe){
286         String JavaDoc msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
287         throw new IASSecurityException(msg);
288     } catch(javax.security.jacc.PolicyContextException JavaDoc pce){
289         throw new IASSecurityException(pce.toString());
290     }
291     }
292     /** This method obtains the policy configuration object
293     * corresponding to the name, and links it, for roleMapping purposes
294     * to another. If the pc is already InService when this method is called,
295     * this method does nothing.
296     * @param String name - the module id which serves to identify
297     * the corresponding policy context. The name shall not be null.
298     * @param String linkName - the module id of the module being linked
299     * to this context. This value may be null, in which case, no link is done,
300     * but the inService state of the named PC is returned.
301     * @param boolean lastInService - the inService state returned by the previous
302     * call to this method. The value of this argument is only significant when linkName
303     * is not null.
304     * @return boolean if linkName is null, returns the inService state of the
305     * PC identified in the name argument. Otherwise returns the value
306     * passed to lastInService.
307     */

308     public static boolean linkPolicyFile(String JavaDoc name, String JavaDoc linkName, boolean lastInService)
309     throws IASSecurityException {
310         
311         boolean rvalue = lastInService;
312         
313         assert name != null;
314         
315         if (name == null) {
316             throw new IASSecurityException("Invalid Module Name");
317         }
318         try {
319             PolicyConfigurationFactory pcf = PolicyConfigurationFactory.getPolicyConfigurationFactory();
320             boolean inService = pcf.inService(name);
321             
322             if (linkName == null) {
323                 rvalue = inService;
324             } else if (inService == lastInService) {
325                 
326                 // only do the link if the named PC is not inService.
327
if (!inService) {
328                     
329                     // find the PolicyConfigs using remove=false to ensure policy stmts
330
// are retained.
331

332                     PolicyConfiguration pc =
333                         pcf.getPolicyConfiguration(name, false);
334                     PolicyConfiguration linkPc =
335                         pcf.getPolicyConfiguration(linkName, false);
336                     pc.linkConfiguration(linkPc);
337                 }
338             } else {
339                 throw new IASSecurityException("Inconsistent Module State");
340             }
341             
342         } catch(java.lang.ClassNotFoundException JavaDoc cnfe){
343             String JavaDoc msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
344             throw new IASSecurityException(msg);
345         } catch(javax.security.jacc.PolicyContextException JavaDoc pce){
346             throw new IASSecurityException(pce.toString());
347         }
348         return rvalue;
349     }
350
351
352     /**
353      * This method provides a single place to get SecuritySupport for security.
354      */

355     public static SecuritySupport getSecuritySupport() {
356         return PluggableFeatureFactoryImpl.getFactory().getSecuritySupport();
357     }
358 }
359
Popular Tags