java.security.PrivilegedAction Java Examples

The following examples show how to use java.security.PrivilegedAction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppContext.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for AppContext.  This method is <i>not</i> public,
 * nor should it ever be used as such.  The proper way to construct
 * an AppContext is through the use of SunToolkit.createNewAppContext.
 * A ThreadGroup is created for the new AppContext, a Thread is
 * created within that ThreadGroup, and that Thread calls
 * SunToolkit.createNewAppContext before calling anything else.
 * That creates both the new AppContext and its EventQueue.
 *
 * @param   threadGroup     The ThreadGroup for the new AppContext
 * @see     sun.awt.SunToolkit
 * @since   1.2
 */
AppContext(ThreadGroup threadGroup) {
    numAppContexts.incrementAndGet();

    this.threadGroup = threadGroup;
    threadGroup2appContext.put(threadGroup, this);

    this.contextClassLoader =
         AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });

    // Initialize push/pop lock and its condition to be used by all the
    // EventQueues within this AppContext
    Lock eventQueuePushPopLock = new ReentrantLock();
    put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
    Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
    put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
 
Example #2
Source File: Finalizer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void forkSecondaryFinalizer(final Runnable proc) {
    AccessController.doPrivileged(
        new PrivilegedAction<Void>() {
            public Void run() {
                ThreadGroup tg = Thread.currentThread().getThreadGroup();
                for (ThreadGroup tgn = tg;
                     tgn != null;
                     tg = tgn, tgn = tg.getParent());
                Thread sft = new Thread(tg, proc, "Secondary finalizer");

                if (TenantGlobals.isDataIsolationEnabled() && TenantContainer.current() != null) {
                    SharedSecrets.getTenantAccess()
                            .registerServiceThread(TenantContainer.current(), sft);
                }

                sft.start();
                try {
                    sft.join();
                } catch (InterruptedException x) {
                    Thread.currentThread().interrupt();
                }
                return null;
            }});
}
 
Example #3
Source File: RTFReader.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/** Looks up a named character set. A character set is a 256-entry
 *  array of characters, mapping unsigned byte values to their Unicode
 *  equivalents. The character set is loaded if necessary.
 *
 *  @returns the character set
 */
public static Object
getCharacterSet(final String name)
    throws IOException
{
    char[] set = characterSets.get(name);
    if (set == null) {
        InputStream charsetStream = AccessController.doPrivileged(
                new PrivilegedAction<InputStream>() {
                    public InputStream run() {
                        return RTFReader.class.getResourceAsStream("charsets/" + name + ".txt");
                    }
                });
        set = readCharset(charsetStream);
        defineCharacterSet(name, set);
    }
    return set;
}
 
Example #4
Source File: PreserveCombinerTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[]args) throws Exception {
    final DomainCombiner dc = new DomainCombiner() {
        @Override
        public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
            return currentDomains; // basically a no-op
        }
    };

    // Get an instance of the saved ACC
    AccessControlContext saved = AccessController.getContext();
    // Simulate the stack ACC with a DomainCombiner attached
    AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);

    // Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
    // whether the DomainCombiner from the stack ACC is preserved
    boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
        @Override
        public Boolean run() {
            return dc == AccessController.getContext().getDomainCombiner();
        }
    }, stack, saved);

    if (!ret) {
        System.exit(1);
    }
}
 
Example #5
Source File: AppContext.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void stopEventDispatchThreads() {
    for (AppContext appContext: getAppContexts()) {
        if (appContext.isDisposed()) {
            continue;
        }
        Runnable r = new PostShutdownEventRunnable(appContext);
        // For security reasons EventQueue.postEvent should only be called
        // on a thread that belongs to the corresponding thread group.
        if (appContext != AppContext.getAppContext()) {
            // Create a thread that belongs to the thread group associated
            // with the AppContext and invokes EventQueue.postEvent.
            PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r);
            Thread thread = AccessController.doPrivileged(action);
            thread.start();
        } else {
            r.run();
        }
    }
}
 
Example #6
Source File: PageContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public Object findAttribute(final String name) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(
                new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer
                            .getMessage("jsp.error.attribute.null_name"));
                }

                return doFindAttribute(name);
            }
        });
    } else {
        if (name == null) {
            throw new NullPointerException(Localizer
                    .getMessage("jsp.error.attribute.null_name"));
        }

        return doFindAttribute(name);
    }
}
 
Example #7
Source File: ApplicationContextAwareProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
	AccessControlContext acc = null;

	if (System.getSecurityManager() != null &&
			(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
					bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
					bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
		acc = this.applicationContext.getBeanFactory().getAccessControlContext();
	}

	if (acc != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareInterfaces(bean);
				return null;
			}
		}, acc);
	}
	else {
		invokeAwareInterfaces(bean);
	}

	return bean;
}
 
Example #8
Source File: Control.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private String combineSafe(Set<String> values) {
    if (context == null) {
        // VM events requires no access control context
        return combine(values);
    }
    return AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override
        public String run() {
            try {
                combine(Collections.unmodifiableSet(values));
            } catch (Throwable t) {
                // Prevent malicious user to propagate exception callback in the wrong context
                Logger.log(LogTag.JFR_SETTING, LogLevel.WARN, "Exception occured when combining " + values + " for " + getClass());
            }
            return null;
        }
    }, context);
}
 
Example #9
Source File: ClassLoader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private 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);
}
 
Example #10
Source File: ProcessImpl.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Open a file for writing. If {@code append} is {@code true} then the file
 * is opened for atomic append directly and a FileOutputStream constructed
 * with the resulting handle. This is because a FileOutputStream created
 * to append to a file does not open the file in a manner that guarantees
 * that writes by the child process will be atomic.
 */
private static FileOutputStream newFileOutputStream(File f, boolean append)
    throws IOException
{
    if (append) {
        String path = f.getPath();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null)
            sm.checkWrite(path);
        long handle = openForAtomicAppend(path);
        final FileDescriptor fd = new FileDescriptor();
        fdAccess.setHandle(fd, handle);
        return AccessController.doPrivileged(
            new PrivilegedAction<FileOutputStream>() {
                public FileOutputStream run() {
                    return new FileOutputStream(fd);
                }
            }
        );
    } else {
        return new FileOutputStream(f);
    }
}
 
Example #11
Source File: JRELocaleProviderAdapter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Getter methods for java.util.spi.* providers
 */
@Override
public CurrencyNameProvider getCurrencyNameProvider() {
    if (currencyNameProvider == null) {
        CurrencyNameProvider provider = AccessController.doPrivileged(
            (PrivilegedAction<CurrencyNameProvider>) () ->
                new CurrencyNameProviderImpl(
                    getAdapterType(),
                    getLanguageTagSet("CurrencyNames")));

        synchronized (this) {
            if (currencyNameProvider == null) {
                currencyNameProvider = provider;
            }
        }
    }
    return currencyNameProvider;
}
 
Example #12
Source File: ObjectStreamClass.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the value contained by this EntryFuture, blocking if
 * necessary until a value is set.
 */
synchronized Object get() {
    boolean interrupted = false;
    while (entry == unset) {
        try {
            wait();
        } catch (InterruptedException ex) {
            interrupted = true;
        }
    }
    if (interrupted) {
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
                public Void run() {
                    Thread.currentThread().interrupt();
                    return null;
                }
            }
        );
    }
    return entry;
}
 
Example #13
Source File: DefaultMBeanServerInterceptor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
 
Example #14
Source File: LimitedDoPrivilegedWithThread.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) {
    //parent thread without any permission
    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                Thread ct = new Thread(
                        new ChildThread(PROPERTYPERM, FILEPERM));
                ct.start();
                try {
                    ct.join();
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    ie.printStackTrace();
                    throw new RuntimeException("Unexpected InterruptedException");
                }
                return null;
            }, ACC);
}
 
Example #15
Source File: CLDRLocaleProviderAdapter.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public TimeZoneNameProvider getTimeZoneNameProvider() {
    if (timeZoneNameProvider == null) {
        TimeZoneNameProvider provider = AccessController.doPrivileged(
            (PrivilegedAction<TimeZoneNameProvider>) () ->
                new CLDRTimeZoneNameProviderImpl(
                    getAdapterType(),
                    getLanguageTagSet("TimeZoneNames")));

        synchronized (this) {
            if (timeZoneNameProvider == null) {
                timeZoneNameProvider = provider;
            }
        }
    }
    return timeZoneNameProvider;
}
 
Example #16
Source File: TestJHSSecurity.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private MRClientProtocol getMRClientProtocol(Token token,
    final InetSocketAddress hsAddress, String user, final Configuration conf) {
  UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
  ugi.addToken(ConverterUtils.convertFromYarn(token, hsAddress));

  final YarnRPC rpc = YarnRPC.create(conf);
  MRClientProtocol hsWithDT = ugi
      .doAs(new PrivilegedAction<MRClientProtocol>() {

        @Override
        public MRClientProtocol run() {
          return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class,
              hsAddress, conf);
        }
      });
  return hsWithDT;
}
 
Example #17
Source File: MarshalledObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new <code>MarshalledObjectInputStream</code> that
 * reads its objects from <code>objIn</code> and annotations
 * from <code>locIn</code>.  If <code>locIn</code> is
 * <code>null</code>, then all annotations will be
 * <code>null</code>.
 */
MarshalledObjectInputStream(InputStream objIn, InputStream locIn,
            ObjectInputFilter filter)
    throws IOException
{
    super(objIn);
    this.locIn = (locIn == null ? null : new ObjectInputStream(locIn));
    if (filter != null) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this, filter);
                if (MarshalledObjectInputStream.this.locIn != null) {
                    ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this.locIn, filter);
                }
                return null;
            }
        });
    }
}
 
Example #18
Source File: SSLSocketImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
}
 
Example #19
Source File: DefaultMBeanServerInterceptor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
 
Example #20
Source File: EventQueue.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
final void initDispatchThread() {
    pushPopLock.lock();
    try {
        if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) {
            dispatchThread = AccessController.doPrivileged(
                new PrivilegedAction<EventDispatchThread>() {
                    public EventDispatchThread run() {
                        EventDispatchThread t =
                            new EventDispatchThread(threadGroup,
                                                    name,
                                                    EventQueue.this);
                        t.setContextClassLoader(classLoader);
                        t.setPriority(Thread.NORM_PRIORITY + 1);
                        t.setDaemon(false);
                        AWTAutoShutdown.getInstance().notifyThreadBusy(t);
                        return t;
                    }
                }
            );
            dispatchThread.start();
        }
    } finally {
        pushPopLock.unlock();
    }
}
 
Example #21
Source File: RepaintManager.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Validate all of the components that have been marked invalid.
 * @see #addInvalidComponent
 */
public void validateInvalidComponents() {
    final java.util.List<Component> ic;
    synchronized(this) {
        if (invalidComponents == null) {
            return;
        }
        ic = invalidComponents;
        invalidComponents = null;
    }
    int n = ic.size();
    for(int i = 0; i < n; i++) {
        final Component c = ic.get(i);
        AccessControlContext stack = AccessController.getContext();
        AccessControlContext acc =
            AWTAccessor.getComponentAccessor().getAccessControlContext(c);
        javaSecurityAccess.doIntersectionPrivilege(
            new PrivilegedAction<Void>() {
                public Void run() {
                    c.validate();
                    return null;
                }
            }, stack, acc);
    }
}
 
Example #22
Source File: ResourceLeakDetectorFactory.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
DefaultResourceLeakDetectorFactory() {
    String customLeakDetector;
    try {
        customLeakDetector = AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return SystemPropertyUtil.get("io.netty.customResourceLeakDetector");
            }
        });
    } catch (Throwable cause) {
        logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause);
        customLeakDetector = null;
    }
    if (customLeakDetector == null) {
        obsoleteCustomClassConstructor = customClassConstructor = null;
    } else {
        obsoleteCustomClassConstructor = obsoleteCustomClassConstructor(customLeakDetector);
        customClassConstructor = customClassConstructor(customLeakDetector);
    }
}
 
Example #23
Source File: LimitedDoPrivilegedWithThread.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(AccessControlContext acc, Permission perm,
        boolean expectACE, int id) {

    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                try {
                    AccessController.getContext().checkPermission(P1);
                } catch (AccessControlException ace) {
                    catchACE = true;
                }
                if (catchACE ^ expectACE) {
                    throw new RuntimeException("test" + id + " failed");
                }
                return null;
            }, acc, perm);
}
 
Example #24
Source File: RepaintManager.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #25
Source File: SecurityActions.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
static ServletRequestContext requireCurrentServletRequestContext() {
    if (System.getSecurityManager() == null) {
        return ServletRequestContext.requireCurrent();
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<ServletRequestContext>() {
            @Override
            public ServletRequestContext run() {
                return ServletRequestContext.requireCurrent();
            }
        });
    }
}
 
Example #26
Source File: SecurityUtilities.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Retrieves a system property within a privileged block. Use it only when
 * the property is used from within Rhino code and is not passed out of it.
 * @param name the name of the system property
 * @return the value of the system property
 */
public static String getSystemProperty(final String name)
{
    return AccessController.doPrivileged(
        new PrivilegedAction<String>()
        {
            public String run()
            {
                return System.getProperty(name);
            }
        });
}
 
Example #27
Source File: Win32FontManager.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String[] getDefaultPlatformFont() {
    String[] info = new String[2];
    info[0] = "Arial";
    info[1] = "c:\\windows\\fonts";
    final String[] dirs = getPlatformFontDirs(true);
    if (dirs.length > 1) {
        String dir = (String)
            AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        for (int i=0; i<dirs.length; i++) {
                            String path =
                                dirs[i] + File.separator + "arial.ttf";
                            File file = new File(path);
                            if (file.exists()) {
                                return dirs[i];
                            }
                        }
                        return null;
                    }
                });
        if (dir != null) {
            info[1] = dir;
        }
    } else {
        info[1] = dirs[0];
    }
    info[1] = info[1] + File.separator + "arial.ttf";
    return info;
}
 
Example #28
Source File: JMXConnectorFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static ClassLoader wrap(final ClassLoader parent) {
    return parent != null ? AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new ClassLoader(parent) {
                @Override
                protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                    ReflectUtil.checkPackageAccess(name);
                    return super.loadClass(name, resolve);
                }
            };
        }
    }) : null;
}
 
Example #29
Source File: Response.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public String generateCookieString(final Cookie cookie) {
    // Web application code can receive a IllegalArgumentException
    // from the generateHeader() invocation
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run(){
                return getContext().getCookieProcessor().generateHeader(cookie);
            }
        });
    } else {
        return getContext().getCookieProcessor().generateHeader(cookie);
    }
}
 
Example #30
Source File: SecuritySupport.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static long getLastModified(final File f) {
    return ((Long) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new Long(f.lastModified());
        }
    })).longValue();
}