1 package org.hibernate.secure; 3 4 import java.lang.reflect.UndeclaredThrowableException ; 5 import java.security.AccessController ; 6 import java.security.CodeSource ; 7 import java.security.Policy ; 8 import java.security.Principal ; 9 import java.security.PrivilegedActionException ; 10 import java.security.PrivilegedExceptionAction ; 11 import java.security.ProtectionDomain ; 12 import java.util.Set ; 13 14 import javax.security.auth.Subject ; 15 import javax.security.jacc.EJBMethodPermission ; 16 import javax.security.jacc.PolicyContext ; 17 import javax.security.jacc.PolicyContextException ; 18 19 24 public class JACCPermissions { 25 26 public static void checkPermission(Class clazz, EJBMethodPermission methodPerm) 27 throws SecurityException { 28 CodeSource ejbCS = clazz.getProtectionDomain().getCodeSource(); 29 30 try { 31 Policy policy = Policy.getPolicy(); 32 Subject caller = getContextSubject(); 34 35 Principal [] principals = null; 36 if ( caller != null ) { 37 Set principalsSet = caller.getPrincipals(); 39 principals = new Principal [ principalsSet.size() ]; 40 principalsSet.toArray( principals ); 41 } 42 43 ProtectionDomain pd = new ProtectionDomain ( ejbCS, null, null, principals ); 44 if ( policy.implies( pd, methodPerm ) == false ) { 45 String msg = "Denied: " + methodPerm + ", caller=" + caller; 46 SecurityException e = new SecurityException ( msg ); 47 throw e; 48 } 49 } 50 catch (PolicyContextException e) { 51 throw new RuntimeException ( e ); 52 } 53 } 54 55 interface PolicyContextActions { 56 57 static final String SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container"; 58 PolicyContextActions PRIVILEGED = new PolicyContextActions() { 59 private final PrivilegedExceptionAction exAction = new PrivilegedExceptionAction () { 60 public Object run() throws Exception { 61 return (Subject ) PolicyContext.getContext( SUBJECT_CONTEXT_KEY ); 62 } 63 }; 64 65 public Subject getContextSubject() throws PolicyContextException { 66 try { 67 return (Subject ) AccessController.doPrivileged( exAction ); 68 } 69 catch (PrivilegedActionException e) { 70 Exception ex = e.getException(); 71 if ( ex instanceof PolicyContextException ) { 72 throw (PolicyContextException ) ex; 73 } 74 else throw new UndeclaredThrowableException ( ex ); 75 } 76 } 77 }; 78 79 PolicyContextActions NON_PRIVILEGED = new PolicyContextActions() { 80 public Subject getContextSubject() throws PolicyContextException { 81 return (Subject ) PolicyContext.getContext( SUBJECT_CONTEXT_KEY ); 82 } 83 }; 84 85 Subject getContextSubject() throws PolicyContextException ; 86 } 87 88 static Subject getContextSubject() throws PolicyContextException { 89 if ( System.getSecurityManager() == null ) { 90 return PolicyContextActions.NON_PRIVILEGED.getContextSubject(); 91 } 92 else { 93 return PolicyContextActions.PRIVILEGED.getContextSubject(); 94 } 95 } 96 97 } 98 | Popular Tags |