java.security.AccessController Java Examples

The following examples show how to use java.security.AccessController. 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: Container.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the position of the mouse pointer in this <code>Container</code>'s
 * coordinate space if the <code>Container</code> is under the mouse pointer,
 * otherwise returns <code>null</code>.
 * This method is similar to {@link Component#getMousePosition()} with the exception
 * that it can take the <code>Container</code>'s children into account.
 * If <code>allowChildren</code> is <code>false</code>, this method will return
 * a non-null value only if the mouse pointer is above the <code>Container</code>
 * directly, not above the part obscured by children.
 * If <code>allowChildren</code> is <code>true</code>, this method returns
 * a non-null value if the mouse pointer is above <code>Container</code> or any
 * of its descendants.
 *
 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
 * @param     allowChildren true if children should be taken into account
 * @see       Component#getMousePosition
 * @return    mouse coordinates relative to this <code>Component</code>, or null
 * @since     1.5
 */
public Point getMousePosition(boolean allowChildren) throws HeadlessException {
    if (GraphicsEnvironment.isHeadless()) {
        throw new HeadlessException();
    }
    PointerInfo pi = java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<PointerInfo>() {
            public PointerInfo run() {
                return MouseInfo.getPointerInfo();
            }
        }
    );
    synchronized (getTreeLock()) {
        Component inTheSameWindow = findUnderMouseInWindow(pi);
        if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) {
            return  pointRelativeToComponent(pi.getLocation());
        }
        return null;
    }
}
 
Example #2
Source File: SecuritySupport.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
public static InputStream getResourceAsStream(final ClassLoader cl,
        final String name)
{
    return (InputStream)
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            InputStream ris;
            if (cl == null) {
                ris = Object.class.getResourceAsStream("/"+name);
            } else {
                ris = cl.getResourceAsStream(name);
            }
            return ris;
        }
    });
}
 
Example #3
Source File: Options.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convenience function for getting system properties in a safe way
 *
 * @param name of integer property
 * @param defValue the default value if unset
 * @return integer property if set or default value
 */
public static int getIntProperty(final String name, final int defValue) {
    checkPropertyName(name);
    return AccessController.doPrivileged(
            new PrivilegedAction<Integer>() {
                @Override
                public Integer run() {
                    try {
                        return Integer.getInteger(name, defValue);
                    } catch (final SecurityException e) {
                        // if no permission to read, assume the default value
                        return defValue;
                    }
                }
            }, READ_PROPERTY_ACC_CTXT);
}
 
Example #4
Source File: ArrayNotificationBuffer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isInstanceOf(final MBeanServer mbs,
                                    final ObjectName name,
                                    final String className) {
    PrivilegedExceptionAction<Boolean> act =
        new PrivilegedExceptionAction<Boolean>() {
            public Boolean run() throws InstanceNotFoundException {
                return mbs.isInstanceOf(name, className);
            }
        };
    try {
        return AccessController.doPrivileged(act);
    } catch (Exception e) {
        logger.fine("isInstanceOf", "failed: " + e);
        logger.debug("isInstanceOf", e);
        return false;
    }
}
 
Example #5
Source File: SecuritySupport.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static <U> U doPrivilegedIOWithReturn(Callable<U> function) throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<U>() {
            @Override
            public U run() throws Exception {
                return function.call();
            }
        }, null);
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new IOException("Unexpected error during I/O operation. " + t.getMessage(), t);
    }
}
 
Example #6
Source File: CreatedFontTracker.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void init() {
    if (t == null) {
        // Add a shutdown hook to remove the temp file.
        AccessController.doPrivileged(
                (PrivilegedAction<Void>) () -> {
                    /* The thread must be a member of a thread group
                     * which will not get GCed before VM exit.
                     * Make its parent the top-level thread group.
                     */
                    ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
                    t = new Thread(rootTG, TempFileDeletionHook::runHooks);
                    t.setContextClassLoader(null);
                    Runtime.getRuntime().addShutdownHook(t);
                    return null;
                });
    }
}
 
Example #7
Source File: Container.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the position of the mouse pointer in this <code>Container</code>'s
 * coordinate space if the <code>Container</code> is under the mouse pointer,
 * otherwise returns <code>null</code>.
 * This method is similar to {@link Component#getMousePosition()} with the exception
 * that it can take the <code>Container</code>'s children into account.
 * If <code>allowChildren</code> is <code>false</code>, this method will return
 * a non-null value only if the mouse pointer is above the <code>Container</code>
 * directly, not above the part obscured by children.
 * If <code>allowChildren</code> is <code>true</code>, this method returns
 * a non-null value if the mouse pointer is above <code>Container</code> or any
 * of its descendants.
 *
 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
 * @param     allowChildren true if children should be taken into account
 * @see       Component#getMousePosition
 * @return    mouse coordinates relative to this <code>Component</code>, or null
 * @since     1.5
 */
public Point getMousePosition(boolean allowChildren) throws HeadlessException {
    if (GraphicsEnvironment.isHeadless()) {
        throw new HeadlessException();
    }
    PointerInfo pi = java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<PointerInfo>() {
            public PointerInfo run() {
                return MouseInfo.getPointerInfo();
            }
        }
    );
    synchronized (getTreeLock()) {
        Component inTheSameWindow = findUnderMouseInWindow(pi);
        if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) {
            return  pointRelativeToComponent(pi.getLocation());
        }
        return null;
    }
}
 
Example #8
Source File: PageContextImpl.java    From Tomcat8-Source-Read with MIT License 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 #9
Source File: Launcher.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static ClassLoader getAppClassLoader(final ClassLoader extcl)
    throws IOException
{
    final String s = System.getProperty("java.class.path");
    final File[] path = (s == null) ? new File[0] : getClassPath(s);

    // Note: on bugid 4256530
    // Prior implementations of this doPrivileged() block supplied
    // a rather restrictive ACC via a call to the private method
    // AppClassLoader.getContext(). This proved overly restrictive
    // when loading  classes. Specifically it prevent
    // accessClassInPackage.sun.* grants from being honored.
    //
    return AccessController.doPrivileged(
        new PrivilegedAction<AppClassLoader>() {
            public AppClassLoader run() {
            URL[] urls =
                (s == null) ? new URL[0] : pathToURLs(path);
            return new AppClassLoader(urls, extcl);
        }
    });
}
 
Example #10
Source File: XRCompositeManager.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private XRCompositeManager(XRSurfaceData surface) {
    con = new XRBackendNative();

    String gradProp =
        AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return System.getProperty("sun.java2d.xrgradcache");
            }
        });

    enableGradCache = gradProp == null ||
                      !(gradProp.equalsIgnoreCase("false") ||
                      gradProp.equalsIgnoreCase("f"));

    XRPaints.register(this);

    initResources(surface);

    maskBuffer = new MaskTileManager(this, surface.getXid());
    textRenderer = new XRTextRenderer(this);
    maskImage = new XRMaskImage(this, surface.getXid());
}
 
Example #11
Source File: ClassLoader.java    From jdk8u60 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 #12
Source File: RMIIIOPServerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
    if (callerACC == null) {
        throw new SecurityException("AccessControlContext cannot be null");
    }
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<RMIConnection>() {
                public RMIConnection run() throws IOException {
                    return superDoNewClient(credentials);
                }
        }, callerACC);
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
}
 
Example #13
Source File: HttpURLConnection.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
                        final String host,
                        final InetAddress addr,
                        final int port,
                        final String protocol,
                        final String prompt,
                        final String scheme,
                        final URL url,
                        final RequestorType authType) {
    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<PasswordAuthentication>() {
            public PasswordAuthentication run() {
                if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                    logger.finest("Requesting Authentication: host =" + host + " url = " + url);
                }
                PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
                    host, addr, port, protocol,
                    prompt, scheme, url, authType);
                if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                    logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
                }
                return pass;
            }
        });
}
 
Example #14
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 #15
Source File: SocketAdaptor.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public OutputStream getOutputStream() throws IOException {
    if (!sc.isOpen())
        throw new SocketException("Socket is closed");
    if (!sc.isConnected())
        throw new SocketException("Socket is not connected");
    if (!sc.isOutputOpen())
        throw new SocketException("Socket output is shutdown");
    OutputStream os = null;
    try {
        os = AccessController.doPrivileged(
            new PrivilegedExceptionAction<OutputStream>() {
                public OutputStream run() throws IOException {
                    return Channels.newOutputStream(sc);
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        throw (IOException)e.getException();
    }
    return os;
}
 
Example #16
Source File: ModelManager.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
private void processRcfCheckpoint(
    Optional<String> rcfCheckpoint,
    String modelId,
    String detectorId,
    double[] point,
    ActionListener<RcfResult> listener
) {
    Optional<ModelState<RandomCutForest>> model = rcfCheckpoint
        .map(checkpoint -> AccessController.doPrivileged((PrivilegedAction<RandomCutForest>) () -> rcfSerde.fromJson(checkpoint)))
        .filter(rcf -> isHostingAllowed(detectorId, rcf))
        .map(rcf -> new ModelState<>(rcf, modelId, detectorId, ModelType.RCF.getName(), clock.instant()));
    if (model.isPresent()) {
        forests.put(modelId, model.get());
        getRcfResult(model.get(), point, listener);
    } else {
        throw new ResourceNotFoundException(detectorId, CommonErrorMessages.NO_CHECKPOINT_ERR_MSG + modelId);
    }
}
 
Example #17
Source File: CreatedFontTracker.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void init() {
    if (t == null) {
        // Add a shutdown hook to remove the temp file.
        AccessController.doPrivileged(
                (PrivilegedAction<Void>) () -> {
                    /* The thread must be a member of a thread group
                     * which will not get GCed before VM exit.
                     * Make its parent the top-level thread group.
                     */
                    ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
                    t = new Thread(rootTG, TempFileDeletionHook::runHooks);
                    t.setContextClassLoader(null);
                    Runtime.getRuntime().addShutdownHook(t);
                    return null;
                });
    }
}
 
Example #18
Source File: Util.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void initDBBRConstructor() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                try {
                    Class<?> cl = Class.forName("java.nio.DirectByteBufferR");
                    Constructor<?> ctor = cl.getDeclaredConstructor(
                        new Class<?>[] { int.class,
                                         long.class,
                                         FileDescriptor.class,
                                         Runnable.class });
                    ctor.setAccessible(true);
                    directByteBufferRConstructor = ctor;
                } catch (ClassNotFoundException |
                         NoSuchMethodException |
                         IllegalArgumentException |
                         ClassCastException x) {
                    throw new InternalError(x);
                }
                return null;
            }});
}
 
Example #19
Source File: LoginContext.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void handle(final Callback[] callbacks)
        throws java.io.IOException, UnsupportedCallbackException {
    try {
        java.security.AccessController.doPrivileged
            (new java.security.PrivilegedExceptionAction<Void>() {
            public Void run() throws java.io.IOException,
                                UnsupportedCallbackException {
                ch.handle(callbacks);
                return null;
            }
        }, acc);
    } catch (java.security.PrivilegedActionException pae) {
        if (pae.getException() instanceof java.io.IOException) {
            throw (java.io.IOException)pae.getException();
        } else {
            throw (UnsupportedCallbackException)pae.getException();
        }
    }
}
 
Example #20
Source File: Subject.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static AccessControlContext createContext(final Subject subject,
                                    final AccessControlContext acc) {


    return java.security.AccessController.doPrivileged
        (new java.security.PrivilegedAction<AccessControlContext>() {
        public AccessControlContext run() {
            if (subject == null)
                return new AccessControlContext(acc, null);
            else
                return new AccessControlContext
                                    (acc,
                                    new SubjectDomainCombiner(subject));
        }
    });
}
 
Example #21
Source File: TransferableProxy.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void annotateClass(final Class<?> cl) throws IOException {
    ClassLoader classLoader =
        (ClassLoader)AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return cl.getClassLoader();
            }
        });

    Set<String> s = new HashSet<String>(1);
    s.add(cl.getName());

    map.put(s, classLoader);
}
 
Example #22
Source File: JLayer.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private void removeAWTEventListener() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            Toolkit.getDefaultToolkit().
                    removeAWTEventListener(LayerEventController.this);
            return null;
        }
    });
}
 
Example #23
Source File: WrappedSocket.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the local address to which the socket is bound.
 */
public InetAddress getLocalAddress() {
    return  AccessController.doPrivileged(
                    new PrivilegedAction<InetAddress>() {
                        @Override
                        public InetAddress run() {
                            return socket.getLocalAddress();

                        }
                    });
}
 
Example #24
Source File: SimpleStandard.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the "monitorRole" identity.
 */
private void checkSubject() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals("monitorRole"))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
Example #25
Source File: SocketPermissionTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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) { }
    }

}
 
Example #26
Source File: OpenType.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private static boolean overridesGetClassName(final Class<?> c) {
    return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            try {
                return (c.getMethod("getClassName").getDeclaringClass() !=
                        OpenType.class);
            } catch (Exception e) {
                return true;  // fail safe
            }
        }
    });
}
 
Example #27
Source File: ExecutableInputMethodManager.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private Preferences getUserRoot() {
    return AccessController.doPrivileged(new PrivilegedAction<Preferences>() {
        public Preferences run() {
            return Preferences.userRoot();
        }
    });
}
 
Example #28
Source File: SecuritySupport.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
static ClassLoader getContextClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException ex) {
            }
            return cl;
        }
    });
}
 
Example #29
Source File: LimitedDoPrivilegedWithThread.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    //Verified that child thread has permission p1,
    runTest(null, P1, false, 1);
    //Verified that child thread inherits parent thread's access control context
    AccessControlContext childAcc = AccessController.getContext();
    runTest(childAcc, P1, true, 2);
    //Verified that we can give permision p2 to limit the "privilege" of the
    //class calling doprivileged action, stack walk will continue
    runTest(null, P2, true, 3);

}
 
Example #30
Source File: SecuritySupport.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static ClassLoader getSystemClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (SecurityException ex) {
            }
            return cl;
        }
    });
}