Java Code Examples for java.security.AccessController#doPrivileged()

The following examples show how to use java.security.AccessController#doPrivileged() . 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: Options.java    From jdk8u60 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 boolean property
 * @param defValue default value of boolean property
 * @return true if set to true, default value if unset or set to false
 */
public static boolean getBooleanProperty(final String name, final Boolean defValue) {
    checkPropertyName(name);
    return AccessController.doPrivileged(
            new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    try {
                        final String property = System.getProperty(name);
                        if (property == null && defValue != null) {
                            return defValue;
                        }
                        return property != null && !"false".equalsIgnoreCase(property);
                    } catch (final SecurityException e) {
                        // if no permission to read, assume false
                        return false;
                    }
                }
            }, READ_PROPERTY_ACC_CTXT);
}
 
Example 2
Source File: Launcher.java    From java-n-IDE-for-Android with Apache License 2.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 (AppClassLoader)
        AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            URL[] urls =
                (s == null) ? new URL[0] : pathToURLs(path);
            return new AppClassLoader(urls, extcl);
        }
    });
}
 
Example 3
Source File: Window.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
private void setWarningString() {
    warningString = null;
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            sm.checkPermission(SecurityConstants.AWT.TOPLEVEL_WINDOW_PERMISSION);
        } catch (SecurityException se) {
            // make sure the privileged action is only
            // for getting the property! We don't want the
            // above checkPermission call to always succeed!
            warningString = AccessController.doPrivileged(
                  new GetPropertyAction("awt.appletWarning",
                                        "Java Applet Window"));
        }
    }
}
 
Example 4
Source File: JSSecurityManager.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/** Load properties from a file.
    This method tries to load properties from the filename give into
    the passed properties object.
    If the file cannot be found or something else goes wrong,
    the method silently fails.
    @param properties The properties bundle to store the values of the
    properties file.
    @param filename The filename of the properties file to load. This
    filename is interpreted as relative to the subdirectory "lib" in
    the JRE directory.
 */
static void loadProperties(final Properties properties,
                           final String filename) {
    if(hasSecurityManager()) {
        try {
            // invoke the privileged action using 1.2 security
            PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
                    public Void run() {
                        loadPropertiesImpl(properties, filename);
                        return null;
                    }
                };
            AccessController.doPrivileged(action);
            if(Printer.debug)Printer.debug("Loaded properties with JDK 1.2 security");
        } catch (Exception e) {
            if(Printer.debug)Printer.debug("Exception loading properties with JDK 1.2 security");
            // try without using JDK 1.2 security
            loadPropertiesImpl(properties, filename);
        }
    } else {
        // not JDK 1.2 security, assume we already have permission
        loadPropertiesImpl(properties, filename);
    }
}
 
Example 5
Source File: StandardManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void load() throws ClassNotFoundException, IOException {
    if (SecurityUtil.isPackageProtectionEnabled()){
        try{
            AccessController.doPrivileged( new PrivilegedDoLoad() );
        } catch (PrivilegedActionException ex){
            Exception exception = ex.getException();
            if (exception instanceof ClassNotFoundException) {
                throw (ClassNotFoundException)exception;
            } else if (exception instanceof IOException) {
                throw (IOException)exception;
            }
            if (log.isDebugEnabled()) {
                log.debug("Unreported exception in load() ", exception);
            }
        }
    } else {
        doLoad();
    }
}
 
Example 6
Source File: ArrayNotificationBuffer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void addNotificationListener(final ObjectName name,
                                     final NotificationListener listener,
                                     final NotificationFilter filter,
                                     final Object handback)
        throws Exception {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws InstanceNotFoundException {
                mBeanServer.addNotificationListener(name,
                                                    listener,
                                                    filter,
                                                    handback);
                return null;
            }
        });
    } catch (Exception e) {
        throw extractException(e);
    }
}
 
Example 7
Source File: RMIConnectionImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private ClassLoader getClassLoaderFor(final ObjectName name)
    throws InstanceNotFoundException {
    try {
        return (ClassLoader)
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<Object>() {
                    public Object run() throws InstanceNotFoundException {
                        return mbeanServer.getClassLoaderFor(name);
                    }
                },
                withPermissions(new MBeanPermission("*", "getClassLoaderFor"))
        );
    } catch (PrivilegedActionException pe) {
        throw (InstanceNotFoundException) extractException(pe);
    }
}
 
Example 8
Source File: SunNativeProvider.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public SunNativeProvider() {
    /* We are the Sun NativeGSS provider */
    super(NAME, 1.8d, INFO);

    if (MECH_MAP != null) {
        AccessController.doPrivileged(new PutAllAction(this, MECH_MAP));
    }
}
 
Example 9
Source File: PlatformDependent.java    From getty with Apache License 2.0 5 votes vote down vote up
/**
 * Return the {@link ClassLoader} for the given {@link Class}.
 */
public static ClassLoader getClassLoader(final Class<?> clazz) {
    if (System.getSecurityManager() == null) {
        return clazz.getClassLoader();
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            @Override
            public ClassLoader run() {
                return clazz.getClassLoader();
            }
        });
    }
}
 
Example 10
Source File: Context.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that the given package can be accessed from no permissions context.
 *
 * @param sm current security manager instance
 * @param fullName fully qualified package name
 * @throw SecurityException if not accessible
 */
private static void checkPackageAccess(final SecurityManager sm, final String fullName) {
    Objects.requireNonNull(sm);
    final int index = fullName.lastIndexOf('.');
    if (index != -1) {
        final String pkgName = fullName.substring(0, index);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                sm.checkPackageAccess(pkgName);
                return null;
            }
        }, NO_PERMISSIONS_ACC_CTXT);
    }
}
 
Example 11
Source File: ProviderImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static JAXBContext getEPRJaxbContext() {
    // EPRs have package and private fields, so we need privilege escalation.
    // this access only fixed, known set of classes, so doing that
    // shouldn't introduce security vulnerability.
    return AccessController.doPrivileged(new PrivilegedAction<JAXBContext>() {
        public JAXBContext run() {
            try {
                return JAXBContext.newInstance(MemberSubmissionEndpointReference.class, W3CEndpointReference.class);
            } catch (JAXBException e) {
                throw new WebServiceException("Error creating JAXBContext for W3CEndpointReference. ", e);
            }
        }
    });
}
 
Example 12
Source File: GetORBPropertiesFileAction.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private String getSystemProperty(final String name) {
    // This will not throw a SecurityException because this
    // class was loaded from rt.jar using the bootstrap classloader.
    String propValue = (String) AccessController.doPrivileged(
        new PrivilegedAction() {
            public java.lang.Object run() {
                return System.getProperty(name);
            }
        }
    );

    return propValue;
}
 
Example 13
Source File: EncapsInputStreamFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static TypeCodeInputStream newTypeCodeInputStream(
        final org.omg.CORBA.ORB orb, final ByteBuffer byteBuffer,
        final int size, final boolean littleEndian,
        final GIOPVersion version) {
    return AccessController
            .doPrivileged(new PrivilegedAction<TypeCodeInputStream>() {
                @Override
                public TypeCodeInputStream run() {
                    return new TypeCodeInputStream(orb, byteBuffer, size,
                            littleEndian, version);
                }
            });
}
 
Example 14
Source File: AnyImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * returns an output stream that an Any value can be marshaled into.
 *
 * @result          the OutputStream to marshal value of Any into
 */
public org.omg.CORBA.portable.OutputStream create_output_stream()
{
    //debug.log ("create_output_stream");
    final ORB finalorb = this.orb;
    return AccessController.doPrivileged(new PrivilegedAction<AnyOutputStream>() {
        @Override
        public AnyOutputStream run() {
            return new AnyOutputStream(finalorb);
        }
    });
}
 
Example 15
Source File: MappedMXBeanType.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
CompositeDataMXBeanType(Class<?> c) throws OpenDataException {
    this.javaClass = c;
    this.mappedTypeClass = COMPOSITE_DATA_CLASS;

    // check if a static from method exists
    try {
        fromMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
                public Method run() throws NoSuchMethodException {
                    return javaClass.getMethod("from", COMPOSITE_DATA_CLASS);
                }
            });
    } catch (PrivilegedActionException e) {
        // ignore NoSuchMethodException since we allow classes
        // that has no from method to be embeded in another class.
    }

    if (COMPOSITE_DATA_CLASS.isAssignableFrom(c)) {
        // c implements CompositeData - set openType to null
        // defer generating the CompositeType
        // until the object is constructed
        this.isCompositeData = true;
        this.openType = null;
    } else {
        this.isCompositeData = false;

        // Make a CompositeData containing all the getters
        final Method[] methods =
            AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
                public Method[] run() {
                    return javaClass.getMethods();
                }
            });
        final List<String> names = new ArrayList<>();
        final List<OpenType<?>> types = new ArrayList<>();

        /* Select public methods that look like "T getX()" or "boolean
           isX()", where T is not void and X is not the empty
           string.  Exclude "Class getClass()" inherited from Object.  */
        for (int i = 0; i < methods.length; i++) {
            final Method method = methods[i];
            final String name = method.getName();
            final Type type = method.getGenericReturnType();
            final String rest;
            if (name.startsWith("get")) {
                rest = name.substring(3);
            } else if (name.startsWith("is") &&
                       type instanceof Class &&
                       ((Class) type) == boolean.class) {
                rest = name.substring(2);
            } else {
                // ignore non-getter methods
                continue;
            }

            if (rest.equals("") ||
                method.getParameterTypes().length > 0 ||
                type == void.class ||
                rest.equals("Class")) {

                // ignore non-getter methods
                continue;
            }
            names.add(decapitalize(rest));
            types.add(toOpenType(type));
        }

        final String[] nameArray = names.toArray(new String[0]);
        openType = new CompositeType(c.getName(),
                                     c.getName(),
                                     nameArray, // field names
                                     nameArray, // field descriptions
                                     types.toArray(new OpenType<?>[0]));
    }
}
 
Example 16
Source File: Policy.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Returns the installed Policy object, skipping the security check.
 *
 * @return the installed Policy.
 *
 */
static Policy getPolicyNoCheck() {
    if (policy == null) {

        synchronized(Policy.class) {

            if (policy == null) {
                String policy_class = null;
                policy_class = AccessController.doPrivileged
                    (new PrivilegedAction<String>() {
                    public String run() {
                        return java.security.Security.getProperty
                            ("auth.policy.provider");
                    }
                });
                if (policy_class == null) {
                    policy_class = AUTH_POLICY;
                }

                try {
                    final String finalClass = policy_class;

                    Policy untrustedImpl = AccessController.doPrivileged(
                            new PrivilegedExceptionAction<Policy>() {
                                public Policy run() throws ClassNotFoundException,
                                        InstantiationException,
                                        IllegalAccessException {
                                    Class<? extends Policy> implClass = Class.forName(
                                            finalClass, false,
                                            Thread.currentThread().getContextClassLoader()
                                    ).asSubclass(Policy.class);
                                    return implClass.newInstance();
                                }
                            });
                    AccessController.doPrivileged(
                            new PrivilegedExceptionAction<Void>() {
                                public Void run() {
                                    setPolicy(untrustedImpl);
                                    isCustomPolicy = !finalClass.equals(AUTH_POLICY);
                                    return null;
                                }
                            }, Objects.requireNonNull(untrustedImpl.acc)
                    );
                } catch (Exception e) {
                    throw new SecurityException
                            (sun.security.util.ResourcesMgr.getString
                            ("unable.to.instantiate.Subject.based.policy"));
                }
            }
        }
    }
    return policy;
}
 
Example 17
Source File: Subject.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Get the {@code Subject} associated with the provided
 * {@code AccessControlContext}.
 *
 * <p> The {@code AccessControlContext} may contain many
 * Subjects (from nested {@code doAs} calls).
 * In this situation, the most recent {@code Subject} associated
 * with the {@code AccessControlContext} is returned.
 *
 * <p>
 *
 * @param  acc the {@code AccessControlContext} from which to retrieve
 *          the {@code Subject}.
 *
 * @return  the {@code Subject} associated with the provided
 *          {@code AccessControlContext}, or {@code null}
 *          if no {@code Subject} is associated
 *          with the provided {@code AccessControlContext}.
 *
 * @exception SecurityException if the caller does not have permission
 *          to get the {@code Subject}. <p>
 *
 * @exception NullPointerException if the provided
 *          {@code AccessControlContext} is {@code null}.
 */
public static Subject getSubject(final AccessControlContext acc) {

    java.lang.SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION);
    }

    if (acc == null) {
        throw new NullPointerException(ResourcesMgr.getString
            ("invalid.null.AccessControlContext.provided"));
    }

    // return the Subject from the DomainCombiner of the provided context
    return AccessController.doPrivileged
        (new java.security.PrivilegedAction<Subject>() {
        public Subject run() {
            DomainCombiner dc = acc.getDomainCombiner();
            if (!(dc instanceof SubjectDomainCombiner))
                return null;
            SubjectDomainCombiner sdc = (SubjectDomainCombiner)dc;
            return sdc.getSubject();
        }
    });
}
 
Example 18
Source File: SecurityActions.java    From smallrye-fault-tolerance with Apache License 2.0 3 votes vote down vote up
/**
 * Get method of a given name from beanClass or one of its super-classes or interfaces.
 * The method should have the same parameter types as a method it is intended to be a fallback for (let's call it the
 * original method). The original method can be defined in a superclass and have parameter types provided with generics.
 *
 * @param beanClass the class of the bean that we search for the method for
 * @param declaringClass the class that defines the method that we search for a counterpart for
 * @param name name of the method
 * @param parameterTypes parameters of the method
 * @return the method in search
 * @throws PrivilegedActionException
 */
static Method getDeclaredMethod(Class<?> beanClass, Class<?> declaringClass, String name, Type[] parameterTypes)
        throws PrivilegedActionException {
    if (System.getSecurityManager() == null) {
        return doGetMethod(beanClass, declaringClass, name, parameterTypes);
    }
    return AccessController.doPrivileged(
            (PrivilegedExceptionAction<Method>) () -> doGetMethod(beanClass, declaringClass, name, parameterTypes));
}
 
Example 19
Source File: ParserDelegator.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Fetch a resource relative to the ParserDelegator classfile.
 * If this is called on 1.2 the loading will occur under the
 * protection of a doPrivileged call to allow the ParserDelegator
 * to function when used in an applet.
 *
 * @param name the name of the resource, relative to the
 *  ParserDelegator class.
 * @returns a stream representing the resource
 */
static InputStream getResourceAsStream(final String name) {
    return AccessController.doPrivileged(
            new PrivilegedAction<InputStream>() {
                public InputStream run() {
                    return ParserDelegator.class.getResourceAsStream(name);
                }
            });
}
 
Example 20
Source File: HTMLEditorKit.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Fetch a resource relative to the HTMLEditorKit classfile.
 * If this is called on 1.2 the loading will occur under the
 * protection of a doPrivileged call to allow the HTMLEditorKit
 * to function when used in an applet.
 *
 * @param name the name of the resource, relative to the
 *  HTMLEditorKit class
 * @return a stream representing the resource
 */
static InputStream getResourceAsStream(final String name) {
    return AccessController.doPrivileged(
            new PrivilegedAction<InputStream>() {
                public InputStream run() {
                    return HTMLEditorKit.class.getResourceAsStream(name);
                }
            });
}