final void checkPackageAccess(Class<?> cls, ProtectionDomain pd) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (ReflectUtil.isNonPublicProxyClass(cls)) { for (Class<?> intf: cls.getInterfaces()) { checkPackageAccess(intf, pd); } return; } final String name = cls.getName(); final int i = name.lastIndexOf('.'); if (i != -1) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { sm.checkPackageAccess(name.substring(0, i)); return null; } }, new AccessControlContext(new ProtectionDomain[] {pd})); } } domains.add(pd); }
void nativeQueueSurfaceDataRunnable(AppContext appContext, final Component c, final Runnable r) { synchronized(this) { if (runnableList == null) { runnableList = new LinkedList<Runnable>(); } runnableList.add(new Runnable() { public void run() { AccessControlContext stack = AccessController.getContext(); AccessControlContext acc = AWTAccessor.getComponentAccessor().getAccessControlContext(c); javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() { public Void run() { r.run(); return null; } }, stack, acc); } }); } scheduleProcessingRunnable(appContext); }
public CachedFile(File tempFile) { this.tempFile = tempFile; final Permissions filePermissions = new Permissions(); final FilePermission crudPermission = new FilePermission(tempFile.getAbsolutePath(), "read,write,delete"); filePermissions.add(crudPermission); debug("filePermissions Added FilePermission for 'read', 'write', 'delete' on " + tempFile.getAbsolutePath()); filePermissionContext = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, filePermissions)}); final Permissions openPermissions = new Permissions(); openPermissions.add(crudPermission); debug("openPermissions Added FilePermission for 'read', 'write', 'delete' on " + tempFile.getAbsolutePath()); openPermissions.add(new FilePermission("<<ALL FILES>>", "execute")); debug("openPermissions Added FilePermission for 'execute' on <<ALL FILES>>"); openPermissions.add(new AWTPermission("showWindowWithoutWarningBanner")); debug("openPermissions Added AWTPermission for 'showWindowWithoutWarningBanner'"); openPermissionContext = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, openPermissions)}); setAsSynced(); }
/** * Retrieves the ServiceCreds for the specified server principal from * the Subject in the specified AccessControlContext. If not found, and if * useSubjectCredsOnly is false, then obtain from a LoginContext. * * NOTE: This method is also used by JSSE Kerberos Cipher Suites */ public static ServiceCreds getServiceCreds(GSSCaller caller, String serverPrincipal, AccessControlContext acc) throws LoginException { Subject accSubj = Subject.getSubject(acc); ServiceCreds sc = null; if (accSubj != null) { sc = ServiceCreds.getInstance(accSubj, serverPrincipal); } if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) { Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID); sc = ServiceCreds.getInstance(subject, serverPrincipal); } return sc; }
public void actionPerformed(final ActionEvent e) { final Object src = e.getSource(); final PrivilegedAction<Void> action = new PrivilegedAction<Void>() { public Void run() { actionPerformedImpl(e); return null; } }; final AccessControlContext stack = AccessController.getContext(); final AccessControlContext srcAcc = AWTAccessor.getComponentAccessor().getAccessControlContext((Component)src); final AccessControlContext eventAcc = AWTAccessor.getAWTEventAccessor().getAccessControlContext(e); if (srcAcc == null) { javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc); } else { javaSecurityAccess.doIntersectionPrivilege( new PrivilegedAction<Void>() { public Void run() { javaSecurityAccess.doIntersectionPrivilege(action, eventAcc); return null; } }, stack, srcAcc); } }
/** * 清理来自URLClassLoader.acc.ProtectionDomain[]中,来自上一个ModuleClassLoader的ProtectionDomain * 这样写好蛋疼,而且还有不兼容的风险,从JDK6+都必须要这样清理,但我找不出更好的办法。 * 在重置沙箱时,遇到MgrModule模块无法正确卸载类的情况,主要的原因是在于URLClassLoader.acc.ProtectionDomain[]中包含了上一个ModuleClassLoader的引用 * 所以必须要在这里清理掉,否则随着重置次数的增加,类会越累积越多 */ private void cleanProtectionDomainWhichCameFromModuleClassLoader() { // got ProtectionDomain[] from URLClassLoader's acc final AccessControlContext acc = unCaughtGetClassDeclaredJavaFieldValue(URLClassLoader.class, "acc", this); final ProtectionDomain[] protectionDomainArray = unCaughtInvokeMethod( unCaughtGetClassDeclaredJavaMethod(AccessControlContext.class, "getContext"), acc ); // remove ProtectionDomain which loader is ModuleClassLoader final Set<ProtectionDomain> cleanProtectionDomainSet = new LinkedHashSet<ProtectionDomain>(); if (ArrayUtils.isNotEmpty(protectionDomainArray)) { for (final ProtectionDomain protectionDomain : protectionDomainArray) { if (protectionDomain.getClassLoader() == null || !StringUtils.equals(ModuleClassLoader.class.getName(), protectionDomain.getClassLoader().getClass().getName())) { cleanProtectionDomainSet.add(protectionDomain); } } } // rewrite acc final AccessControlContext newAcc = new AccessControlContext(cleanProtectionDomainSet.toArray(new ProtectionDomain[]{})); unCaughtSetClassDeclaredJavaFieldValue(URLClassLoader.class, "acc", this, newAcc); }
private ClassLoader getClassLoader(final ObjectName name) { if(clr == null){ return null; } // Restrict to getClassLoader permission only Permissions permissions = new Permissions(); permissions.add(new MBeanPermission("*", null, name, "getClassLoader")); ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions); ProtectionDomain[] domains = {protectionDomain}; AccessControlContext ctx = new AccessControlContext(domains); ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return clr.getClassLoader(name); } }, ctx); return loader; }
@Override public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException { AccessControlContext acc = null; if (System.getSecurityManager() != null && (bean instanceof DisruptorEventPublisherAware )) { acc = getAccessControlContext(); } if (acc != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { invokeAwareInterfaces(bean); return null; } }, acc); } else { invokeAwareInterfaces(bean); } return bean; }
/** * create a context that can read any directories (recursively) * mentioned in the class path. In the case of a jar, it has to * be the directory containing the jar, not just the jar, as jar * files might refer to other jar files. */ private static AccessControlContext getContext(File[] cp) throws MalformedURLException { PathPermissions perms = new PathPermissions(cp); ProtectionDomain domain = new ProtectionDomain(new CodeSource(perms.getCodeBase(), (java.security.cert.Certificate[]) null), perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); return acc; }
@Override public void run() { // Don't need to synchronize, as it only runs in one thread. for (Map.Entry<HandshakeCompletedListener,AccessControlContext> entry : targets) { final HandshakeCompletedListener l = entry.getKey(); AccessControlContext acc = entry.getValue(); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { l.handshakeCompleted(event); return null; } }, acc); } }
Object invoke() throws Exception { AccessControlContext acc = this.acc; if ((acc == null) && (System.getSecurityManager() != null)) { throw new SecurityException("AccessControlContext is not set"); } try { return AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return invokeInternal(); } }, acc ); } catch (PrivilegedActionException exception) { throw exception.getException(); } }
/** * create a context that can read any directories (recursively) * mentioned in the class path. In the case of a jar, it has to * be the directory containing the jar, not just the jar, as jar * files might refer to other jar files. */ private static AccessControlContext getContext(File[] cp) throws java.net.MalformedURLException { PathPermissions perms = new PathPermissions(cp); ProtectionDomain domain = new ProtectionDomain(new CodeSource(perms.getCodeBase(), (java.security.cert.Certificate[]) null), perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); return acc; }
/** * Verify that the given AccessControlContext has permission to * accept this connection. */ void checkAcceptPermission(SecurityManager sm, AccessControlContext acc) { /* * Note: no need to synchronize on cache-related fields, since this * method only gets called from the ConnectionHandler's thread. */ if (sm != cacheSecurityManager) { okContext = null; authCache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>(); cacheSecurityManager = sm; } if (acc.equals(okContext) || authCache.containsKey(acc)) { return; } InetAddress addr = socket.getInetAddress(); String host = (addr != null) ? addr.getHostAddress() : "*"; sm.checkAccept(host, socket.getPort()); authCache.put(acc, new SoftReference<AccessControlContext>(acc)); okContext = acc; }
/** * Retrieves the ticket corresponding to the client/server principal * pair from the Subject in the specified AccessControlContext. * If the ticket can not be found in the Subject, and if * useSubjectCredsOnly is false, then obtain ticket from * a LoginContext. */ static KerberosTicket getTicket(GSSCaller caller, String clientPrincipal, String serverPrincipal, AccessControlContext acc) throws LoginException { // Try to get ticket from acc's Subject Subject accSubj = Subject.getSubject(acc); KerberosTicket ticket = SubjectComber.find(accSubj, serverPrincipal, clientPrincipal, KerberosTicket.class); // Try to get ticket from Subject obtained from GSSUtil if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) { Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID); ticket = SubjectComber.find(subject, serverPrincipal, clientPrincipal, KerberosTicket.class); } return ticket; }
public static void main(String[] args) throws Exception { ProtectionDomain domain = new ProtectionDomain(null, null); AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { // this initialize ProxyLazyValues UIManager.getLookAndFeel(); return null; } }, new AccessControlContext(new ProtectionDomain[]{domain})); weakRef = new WeakReference<ProtectionDomain>(domain); domain = null; Util.generateOOME(); if (weakRef.get() != null) { throw new RuntimeException("Memory leak found!"); } System.out.println("Test passed"); }
@Test public void joinGroupMulticastTest() throws Exception { InetAddress group = InetAddress.getByName("229.227.226.221"); try (MulticastSocket s = new MulticastSocket(0)) { int port = s.getLocalPort(); String addr = "localhost:" + port; AccessControlContext acc = getAccessControlContext( new SocketPermission(addr, "listen,resolve"), new SocketPermission("229.227.226.221", "connect,accept")); // Positive AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { s.joinGroup(group); s.leaveGroup(group); return null; }, acc); // Negative try { AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { s.joinGroup(group); s.leaveGroup(group); fail("Expected SecurityException"); return null; }, RESTRICTED_ACC); } catch (SecurityException expected) { } } }
ProviderImpl(Class<S> service, Class<? extends S> type, Method factoryMethod, AccessControlContext acc) { this.service = service; this.type = type; this.factoryMethod = factoryMethod; this.ctor = null; this.acc = acc; }
/** * Return the current user, including any doAs in the current stack. * @return the current user * @throws IOException if login fails */ @InterfaceAudience.Public @InterfaceStability.Evolving public synchronized static UserGroupInformation getCurrentUser() throws IOException { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null || subject.getPrincipals(User.class).isEmpty()) { return getLoginUser(); } else { return new UserGroupInformation(subject); } }
@Override public Object compile(String scriptName, String scriptSource, Map<String, String> params) { // classloader created here final SecurityManager sm = System.getSecurityManager(); SpecialPermission.check(); return AccessController.doPrivileged(new PrivilegedAction<Expression>() { @Override public Expression run() { try { // snapshot our context here, we check on behalf of the expression AccessControlContext engineContext = AccessController.getContext(); ClassLoader loader = getClass().getClassLoader(); if (sm != null) { loader = new ClassLoader(loader) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { engineContext.checkPermission(new ClassPermission(name)); } catch (SecurityException e) { throw new ClassNotFoundException(name, e); } return super.loadClass(name, resolve); } }; } // NOTE: validation is delayed to allow runtime vars, and we don't have access to per index stuff here return JavascriptCompiler.compile(scriptSource, JavascriptCompiler.DEFAULT_FUNCTIONS, loader); } catch (ParseException e) { throw convertToScriptException("compile error", scriptSource, scriptSource, e); } } }); }
Callback(ObjectInputValidation obj, int priority, Callback next, AccessControlContext acc) { this.obj = obj; this.priority = priority; this.next = next; this.acc = acc; }
static Krb5AcceptCredential getInstance(final GSSCaller caller, Krb5NameElement name) throws GSSException { final String serverPrinc = (name == null? null: name.getKrb5PrincipalName().getName()); final AccessControlContext acc = AccessController.getContext(); ServiceCreds creds = null; try { creds = AccessController.doPrivileged( new PrivilegedExceptionAction<ServiceCreds>() { public ServiceCreds run() throws Exception { return Krb5Util.getServiceCreds( caller == GSSCaller.CALLER_UNKNOWN ? GSSCaller.CALLER_ACCEPT: caller, serverPrinc, acc); }}); } catch (PrivilegedActionException e) { GSSException ge = new GSSException(GSSException.NO_CRED, -1, "Attempt to obtain new ACCEPT credentials failed!"); ge.initCause(e.getException()); throw ge; } if (creds == null) throw new GSSException(GSSException.NO_CRED, -1, "Failed to find any Kerberos credentails"); if (name == null) { String fullName = creds.getName(); if (fullName != null) { name = Krb5NameElement.getInstance(fullName, Krb5MechFactory.NT_GSS_KRB5_PRINCIPAL); } } return new Krb5AcceptCredential(name, creds); }
/** * Version for InnocuousForkJoinWorkerThread. */ ForkJoinWorkerThread(ForkJoinPool pool, ClassLoader ccl, ThreadGroup threadGroup, AccessControlContext acc) { super(threadGroup, null, "aForkJoinWorkerThread"); super.setContextClassLoader(ccl); ThreadLocalRandom.setInheritedAccessControlContext(this, acc); ThreadLocalRandom.eraseThreadLocals(this); // clear before registering this.pool = pool; this.workQueue = pool.registerWorker(this); }
/** * Registration method. * * @param classes * @param serviceProperties * @return the ServiceRegistration */ ServiceRegistration registerService(Class<?>[] classes, final Dictionary serviceProperties) { Assert.notEmpty(classes, "at least one class has to be specified for exporting " + "(if autoExport is enabled then maybe the object doesn't implement any interface)"); // create an array of classnames (used for registering the service) final String[] names = ClassUtils.toStringArray(classes); // sort the names in alphabetical order (eases debugging) Arrays.sort(names); log.info("Publishing service under classes [" + ObjectUtils.nullSafeToString(names) + "]"); ServiceFactory serviceFactory = new PublishingServiceFactory(resolver, classes, (ExportContextClassLoaderEnum.SERVICE_PROVIDER .equals(contextClassLoader)), classLoader, aopClassLoader, bundleContext); if (isBeanBundleScoped()) serviceFactory = new OsgiBundleScope.BundleScopeServiceFactory(serviceFactory); if (System.getSecurityManager() != null) { AccessControlContext acc = SecurityUtils.getAccFrom(beanFactory); final ServiceFactory serviceFactoryFinal = serviceFactory; return AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() { public ServiceRegistration run() { return bundleContext.registerService(names, serviceFactoryFinal, serviceProperties); } }, acc); } else { return bundleContext.registerService(names, serviceFactory, serviceProperties); } }
private AccessControlContext getDelegatedAcc(Subject delegatedSubject, boolean removeCallerContext) { if (removeCallerContext) { return JMXSubjectDomainCombiner.getDomainCombinerContext(delegatedSubject); } else { return JMXSubjectDomainCombiner.getContext(delegatedSubject); } }
static void checkMBeanPermission( final MBeanServer mbs, final ObjectName name, final String actions) throws InstanceNotFoundException, SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { AccessControlContext acc = AccessController.getContext(); ObjectInstance oi; try { oi = AccessController.doPrivileged( new PrivilegedExceptionAction<ObjectInstance>() { public ObjectInstance run() throws InstanceNotFoundException { return mbs.getObjectInstance(name); } }); } catch (PrivilegedActionException e) { throw (InstanceNotFoundException) extractException(e); } String classname = oi.getClassName(); MBeanPermission perm = new MBeanPermission( classname, null, name, actions); sm.checkPermission(perm, acc); } }
private String getValueForFile(File file, String key, boolean haveTriedAndWarnedInOtherDir) { ValueReaderFromFile valueReaderFromFile = new ValueReaderFromFile(file, key, haveTriedAndWarnedInOtherDir); final Permissions permissions = new Permissions(); permissions.add(new FilePermission(file.getAbsolutePath(), "read")); final AccessControlContext context = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, permissions)}); AccessController.doPrivileged(valueReaderFromFile, context); return valueReaderFromFile.getPropertyValue(); }
URLClassLoader(URL[] urls, AccessControlContext acc) { super(); // this is to make the stack depth consistent with 1.1 SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkCreateClassLoader(); } this.acc = acc; this.ucp = new URLClassPath(urls, acc); }
private static AccessControlContext getAccessControlContext(Permission... ps) { Permissions perms = new Permissions(); for (Permission p : ps) { perms.add(p); } /* *Create an AccessControlContext that consist a single protection domain * with only the permissions calculated above */ ProtectionDomain pd = new ProtectionDomain(null, perms); return new AccessControlContext(new ProtectionDomain[]{pd}); }
public ClientKeyExchange createServerExchange( ProtocolVersion protocolVersion, ProtocolVersion clientVersion, SecureRandom rand, byte[] encodedTicket, byte[] encrypted, AccessControlContext acc, Object serviceCreds) throws IOException { return new ExchangerImpl(protocolVersion, clientVersion, rand, encodedTicket, encrypted, acc, serviceCreds); }
/** * Creates an access control context limited to only the specified permissions. * @param permissions the permissions for the newly created access control context. * @return a new access control context limited to only the specified permissions. */ public static AccessControlContext createAccessControlContext(final Permission... permissions) { final Permissions perms = new Permissions(); for(final Permission permission: permissions) { perms.add(permission); } return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) }); }
JarLoader(URL url, URLStreamHandler jarHandler, HashMap<String, Loader> loaderMap, AccessControlContext acc) throws IOException { super(new URL("jar", "", -1, url + "!/", jarHandler)); csu = url; handler = jarHandler; lmap = loaderMap; this.acc = acc; ensureOpen(); }
/** * Extract the appropriate property value from the event and * pass it to the action associated with * this {@code EventHandler}. * * @param proxy the proxy object * @param method the method in the listener interface * @return the result of applying the action to the target * * @see EventHandler */ public Object invoke(final Object proxy, final Method method, final Object[] arguments) { AccessControlContext acc = this.acc; if ((acc == null) && (System.getSecurityManager() != null)) { throw new SecurityException("AccessControlContext is not set"); } return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return invokeInternal(proxy, method, arguments); } }, acc); }
URLClassLoader(URL[] urls, ClassLoader parent, AccessControlContext acc) { super(parent); // this is to make the stack depth consistent with 1.1 SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkCreateClassLoader(); } this.acc = acc; ucp = new URLClassPath(urls, acc); }
public static void main(String[] args) throws Exception { /* * If we delay setting the security manager until after the service * configuration file has been installed, then this test still * functions properly, but the -Djava.security.debug output is * lacking, so to ease debugging, we'll set it early-- at the cost * of having to specify the policy even when running standalone. */ TestLibrary.suggestSecurityManager(null); ServiceConfiguration.installServiceConfigurationFile(); /* * Execute use of RMIClassLoader within an AccessControlContext * that has a protection domain with no permissions, to make sure * that RMIClassLoader can still properly initialize itself. */ CodeSource codesource = new CodeSource(null, (Certificate[]) null); Permissions perms = null; ProtectionDomain pd = new ProtectionDomain(codesource, perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { pd }); java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction() { public Object run() throws Exception { TestProvider.exerciseTestProvider( TestProvider2.loadClassReturn, TestProvider2.loadProxyClassReturn, TestProvider2.getClassLoaderReturn, TestProvider2.getClassAnnotationReturn, TestProvider2.invocations); return null; } }, acc); }
/** * Extract the appropriate property value from the event and * pass it to the action associated with * this <code>EventHandler</code>. * * @param proxy the proxy object * @param method the method in the listener interface * @return the result of applying the action to the target * * @see EventHandler */ public Object invoke(final Object proxy, final Method method, final Object[] arguments) { AccessControlContext acc = this.acc; if ((acc == null) && (System.getSecurityManager() != null)) { throw new SecurityException("AccessControlContext is not set"); } return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return invokeInternal(proxy, method, arguments); } }, acc); }
@Override public Object run() { Utils.writeFile(filename); AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); return Subject.doAs(subject, nextAction); }
@Override public Object run() { Utils.readFile(filename); AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); ReadPropertyAction readProperty = new ReadPropertyAction(); if (anotherSubject != null) { return Subject.doAs(anotherSubject, readProperty); } else { return Subject.doAs(subject, readProperty); } }
public void run() { final ScheduledFuture<?> sf; final AccessControlContext ac; synchronized (Monitor.this) { sf = Monitor.this.schedulerFuture; ac = Monitor.this.acc; } PrivilegedAction<Void> action = new PrivilegedAction<Void>() { public Void run() { if (Monitor.this.isActive()) { final int an[] = alreadyNotifieds; int index = 0; for (ObservedObject o : Monitor.this.observedObjects) { if (Monitor.this.isActive()) { Monitor.this.monitor(o, index++, an); } } } return null; } }; if (ac == null) { throw new SecurityException("AccessControlContext cannot be null"); } AccessController.doPrivileged(action, ac); synchronized (Monitor.this) { if (Monitor.this.isActive() && Monitor.this.schedulerFuture == sf) { Monitor.this.monitorFuture = null; Monitor.this.schedulerFuture = scheduler.schedule(Monitor.this.schedulerTask, Monitor.this.getGranularityPeriod(), TimeUnit.MILLISECONDS); } } }