Java Code Examples for java.security.AccessController

The following examples show how to use java.security.AccessController. These examples are extracted from open source projects. 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 Project: jdk8u60   Source File: Subject.java    License: 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 2
Source Project: jdk8u60   Source File: Util.java    License: 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 3
Source Project: jdk8u60   Source File: CreatedFontTracker.java    License: 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 4
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 5
Source Project: jdk8u60   Source File: ClassLoader.java    License: 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 6
Source Project: jdk1.8-source-analysis   Source File: SecuritySupport.java    License: 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 7
Source Project: TencentKona-8   Source File: Launcher.java    License: 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 8
@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 9
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 10
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 11
Source Project: jdk8u60   Source File: SocketAdaptor.java    License: 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 12
Source Project: anomaly-detection   Source File: ModelManager.java    License: 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 13
Source Project: jdk8u60   Source File: AppContext.java    License: 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 14
Source Project: jdk8u60   Source File: Container.java    License: 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 15
Source Project: TencentKona-8   Source File: Container.java    License: 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 16
Source Project: TencentKona-8   Source File: Options.java    License: 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 17
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 Project: Tomcat8-Source-Read   Source File: PageContextImpl.java    License: 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 19
Source Project: jdk8u60   Source File: XRCompositeManager.java    License: 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 20
Source Project: jdk8u60   Source File: LoginContext.java    License: 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 21
Source Project: TencentKona-8   Source File: LocaleData.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static ResourceBundle getBundle(final String baseName, final Locale locale) {
    return AccessController.doPrivileged(new PrivilegedAction<ResourceBundle>() {
        @Override
        public ResourceBundle run() {
            return ResourceBundle
                    .getBundle(baseName, locale, LocaleDataResourceBundleControl.INSTANCE);
        }
    });
}
 
Example 22
private File[] getInstalledExtensions() throws IOException {
    return AccessController.doPrivileged(
        new PrivilegedAction<File[]>() {
            public File[] run() {
                 try {
                     return getExtFiles(getExtDirs());
                 } catch(IOException e) {
                     debug("Cannot get list of installed extensions");
                     debugException(e);
                    return new File[0];
                 }
             }
        });
}
 
Example 23
Source Project: smallrye-config   Source File: SecuritySupport.java    License: Apache License 2.0 5 votes vote down vote up
static void setAccessible(AccessibleObject object, boolean flag) {
    if (System.getSecurityManager() == null) {
        object.setAccessible(flag);
    } else {
        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

            try {
                object.setAccessible(flag);
            } catch (SecurityException ex) {
                ConfigLogging.log.failedToSetAccessible(ex, object.toString());
            }
            return null;
        });
    }
}
 
Example 24
Source Project: kogito-runtimes   Source File: SafeMVELEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object executeExpression(final Object compiledExpression, final VariableResolverFactory factory) {
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            return MVEL.executeExpression(compiledExpression, factory);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example 25
Source Project: TencentKona-8   Source File: Container.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void stopListeningForOtherDrags() {
    //System.out.println("Removing AWTEventListener");
    java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Object>() {
            public Object run() {
                nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this);
                return null;
            }
        }
    );
}
 
Example 26
Source Project: jdk8u60   Source File: AppletClassLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ThreadGroup getThreadGroup() {
  synchronized (threadGroupSynchronizer) {
    if (threadGroup == null || threadGroup.isDestroyed()) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                threadGroup = new AppletThreadGroup(base + "-threadGroup");
                // threadGroup.setDaemon(true);
                // threadGroup is now destroyed by AppContext.dispose()

                // Create the new AppContext from within a Thread belonging
                // to the newly created ThreadGroup, and wait for the
                // creation to complete before returning from this method.
                AppContextCreator creatorThread = new AppContextCreator(threadGroup);

                // Since this thread will later be used to launch the
                // applet's AWT-event dispatch thread and we want the applet
                // code executing the AWT callbacks to use their own class
                // loader rather than the system class loader, explicitly
                // set the context class loader to the AppletClassLoader.
                creatorThread.setContextClassLoader(AppletClassLoader.this);

                creatorThread.start();
                try {
                    synchronized(creatorThread.syncObject) {
                        while (!creatorThread.created) {
                            creatorThread.syncObject.wait();
                        }
                    }
                } catch (InterruptedException e) { }
                appContext = creatorThread.appContext;
                return null;
            }
        });
    }
    return threadGroup;
  }
}
 
Example 27
Source Project: openjdk-jdk8u   Source File: Subject.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean contains(Object o) {
    final Iterator<E> e = iterator();
    while (e.hasNext()) {
        E next;
        if (which != Subject.PRIV_CREDENTIAL_SET) {
            next = e.next();
        } else {

            // For private credentials:
            // If the caller does not have read permission for
            // for o.getClass(), we throw a SecurityException.
            // Otherwise we check the private cred set to see whether
            // it contains the Object

            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                sm.checkPermission(new PrivateCredentialPermission
                                        (o.getClass().getName(),
                                        subject.getPrincipals()));
            }
            next = java.security.AccessController.doPrivileged
                (new java.security.PrivilegedAction<E>() {
                public E run() {
                    return e.next();
                }
            });
        }

        if (next == null) {
            if (o == null) {
                return true;
            }
        } else if (next.equals(o)) {
            return true;
        }
    }
    return false;
}
 
Example 28
long getLastModified(final File f) {
    return ((Long)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new Long(f.lastModified());
                }
            })).longValue();
}
 
Example 29
Source Project: JDKSourceCode1.8   Source File: Package.java    License: MIT License 5 votes vote down vote up
private static Package defineSystemPackage(final String iname,
                                           final String fn)
{
    return AccessController.doPrivileged(new PrivilegedAction<Package>() {
        public Package run() {
            String name = iname;
            // Get the cached code source url for the file name
            URL url = urls.get(fn);
            if (url == null) {
                // URL not found, so create one
                File file = new File(fn);
                try {
                    url = ParseUtil.fileToEncodedURL(file);
                } catch (MalformedURLException e) {
                }
                if (url != null) {
                    urls.put(fn, url);
                    // If loading a JAR file, then also cache the manifest
                    if (file.isFile()) {
                        mans.put(fn, loadManifest(fn));
                    }
                }
            }
            // Convert to "."-separated package name
            name = name.substring(0, name.length() - 1).replace('/', '.');
            Package pkg;
            Manifest man = mans.get(fn);
            if (man != null) {
                pkg = new Package(name, man, url, null);
            } else {
                pkg = new Package(name, null, null, null,
                                  null, null, null, null, null);
            }
            pkgs.put(name, pkg);
            return pkg;
        }
    });
}
 
Example 30
public AccessControlContext
    delegatedContext(AccessControlContext authenticatedACC,
                     Subject delegatedSubject,
                     boolean removeCallerContext)
        throws SecurityException {

    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }

    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for(Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action =
        new PrivilegedAction<Void>() {
            public Void run() {
                for (Permission sdp : permissions) {
                    AccessController.checkPermission(sdp);
                }
                return null;
            }
        };
    AccessController.doPrivileged(action, authenticatedACC);

    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}