Search in sources :

Example 71 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hackpad by dropbox.

the class PolicySecurityController method callWithDomain.

@Override
public Object callWithDomain(final Object securityDomain, final Context cx, Callable callable, Scriptable scope, Scriptable thisObj, Object[] args) {
    // Run in doPrivileged as we might be checked for "getClassLoader" 
    // runtime permission
    final ClassLoader classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction<Object>() {

        public Object run() {
            return cx.getApplicationClassLoader();
        }
    });
    final CodeSource codeSource = (CodeSource) securityDomain;
    Map<ClassLoader, SoftReference<SecureCaller>> classLoaderMap;
    synchronized (callers) {
        classLoaderMap = callers.get(codeSource);
        if (classLoaderMap == null) {
            classLoaderMap = new WeakHashMap<ClassLoader, SoftReference<SecureCaller>>();
            callers.put(codeSource, classLoaderMap);
        }
    }
    SecureCaller caller;
    synchronized (classLoaderMap) {
        SoftReference<SecureCaller> ref = classLoaderMap.get(classLoader);
        if (ref != null) {
            caller = ref.get();
        } else {
            caller = null;
        }
        if (caller == null) {
            try {
                // Run in doPrivileged as we'll be checked for 
                // "createClassLoader" runtime permission
                caller = (SecureCaller) AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {

                    public Object run() throws Exception {
                        Loader loader = new Loader(classLoader, codeSource);
                        Class<?> c = loader.defineClass(SecureCaller.class.getName() + "Impl", secureCallerImplBytecode);
                        return c.newInstance();
                    }
                });
                classLoaderMap.put(classLoader, new SoftReference<SecureCaller>(caller));
            } catch (PrivilegedActionException ex) {
                throw new UndeclaredThrowableException(ex.getCause());
            }
        }
    }
    return caller.call(callable, cx, scope, thisObj, args);
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) SecureClassLoader(java.security.SecureClassLoader) CodeSource(java.security.CodeSource) PrivilegedActionException(java.security.PrivilegedActionException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SoftReference(java.lang.ref.SoftReference) PrivilegedAction(java.security.PrivilegedAction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SecureClassLoader(java.security.SecureClassLoader)

Example 72 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hackpad by dropbox.

the class SecureCaller method callSecurely.

/**
     * Call the specified callable using a protection domain belonging to the 
     * specified code source. 
     */
static Object callSecurely(final CodeSource codeSource, Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
    final Thread thread = Thread.currentThread();
    // Run in doPrivileged as we might be checked for "getClassLoader" 
    // runtime permission
    final ClassLoader classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction<Object>() {

        public Object run() {
            return thread.getContextClassLoader();
        }
    });
    Map<ClassLoader, SoftReference<SecureCaller>> classLoaderMap;
    synchronized (callers) {
        classLoaderMap = callers.get(codeSource);
        if (classLoaderMap == null) {
            classLoaderMap = new WeakHashMap<ClassLoader, SoftReference<SecureCaller>>();
            callers.put(codeSource, classLoaderMap);
        }
    }
    SecureCaller caller;
    synchronized (classLoaderMap) {
        SoftReference<SecureCaller> ref = classLoaderMap.get(classLoader);
        if (ref != null) {
            caller = ref.get();
        } else {
            caller = null;
        }
        if (caller == null) {
            try {
                // Run in doPrivileged as we'll be checked for 
                // "createClassLoader" runtime permission
                caller = (SecureCaller) AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {

                    public Object run() throws Exception {
                        ClassLoader effectiveClassLoader;
                        Class<?> thisClass = getClass();
                        if (classLoader.loadClass(thisClass.getName()) != thisClass) {
                            effectiveClassLoader = thisClass.getClassLoader();
                        } else {
                            effectiveClassLoader = classLoader;
                        }
                        SecureClassLoaderImpl secCl = new SecureClassLoaderImpl(effectiveClassLoader);
                        Class<?> c = secCl.defineAndLinkClass(SecureCaller.class.getName() + "Impl", secureCallerImplBytecode, codeSource);
                        return c.newInstance();
                    }
                });
                classLoaderMap.put(classLoader, new SoftReference<SecureCaller>(caller));
            } catch (PrivilegedActionException ex) {
                throw new UndeclaredThrowableException(ex.getCause());
            }
        }
    }
    return caller.call(callable, cx, scope, thisObj, args);
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SoftReference(java.lang.ref.SoftReference) PrivilegedAction(java.security.PrivilegedAction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SecureClassLoader(java.security.SecureClassLoader)

Example 73 with PrivilegedActionException

use of java.security.PrivilegedActionException in project grails-core by grails.

the class OptimizedAutowireCapableBeanFactory method autowireBeanInAutowireByName.

protected void autowireBeanInAutowireByName(final Object existingBean, Map<String, PropertyDescriptor> autowireableBeanProps) {
    for (Map.Entry<String, PropertyDescriptor> entry : autowireableBeanProps.entrySet()) {
        final PropertyDescriptor pd = entry.getValue();
        final Method writeMethod = pd.getWriteMethod();
        final String beanName = entry.getKey();
        final Object value = getBean(beanName);
        try {
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {

                        public Object run() throws Exception {
                            writeMethod.invoke(existingBean, value);
                            return null;
                        }
                    }, getAccessControlContext());
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(existingBean, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(existingBean, beanName, null, value);
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
            }
            throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(existingBean, beanName, null, value);
            throw new MethodInvocationException(pce, ex);
        }
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) PropertyDescriptor(java.beans.PropertyDescriptor) PrivilegedActionException(java.security.PrivilegedActionException) Method(java.lang.reflect.Method) PrivilegedActionException(java.security.PrivilegedActionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 74 with PrivilegedActionException

use of java.security.PrivilegedActionException in project jersey by jersey.

the class WadlGeneratorJAXBGrammarGenerator method buildModelAndSchemas.

/**
     * Build the JAXB model and generate the schemas based on tha data
     *
     * @param extraFiles additional files.
     * @return class to {@link QName} resolver.
     */
private Resolver buildModelAndSchemas(final Map<String, ApplicationDescription.ExternalGrammar> extraFiles) {
    // Lets get all candidate classes so we can create the JAX-B context
    // include any @XmlSeeAlso references.
    final Set<Class> classSet = new HashSet<>(seeAlsoClasses);
    for (final TypeCallbackPair pair : nameCallbacks) {
        final GenericType genericType = pair.genericType;
        final Class<?> clazz = genericType.getRawType();
        if (clazz.getAnnotation(XmlRootElement.class) != null) {
            classSet.add(clazz);
        } else if (SPECIAL_GENERIC_TYPES.contains(clazz)) {
            final Type type = genericType.getType();
            if (type instanceof ParameterizedType) {
                final Type parameterType = ((ParameterizedType) type).getActualTypeArguments()[0];
                if (parameterType instanceof Class) {
                    classSet.add((Class) parameterType);
                }
            }
        }
    }
    // Create a JAX-B context, and use this to generate us a bunch of
    // schema objects
    JAXBIntrospector introspector = null;
    try {
        final JAXBContext context = JAXBContext.newInstance(classSet.toArray(new Class[classSet.size()]));
        final List<StreamResult> results = new ArrayList<>();
        context.generateSchema(new SchemaOutputResolver() {

            int counter = 0;

            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName) {
                final StreamResult result = new StreamResult(new CharArrayWriter());
                result.setSystemId("xsd" + (counter++) + ".xsd");
                results.add(result);
                return result;
            }
        });
        for (final StreamResult result : results) {
            final CharArrayWriter writer = (CharArrayWriter) result.getWriter();
            final byte[] contents = writer.toString().getBytes("UTF8");
            extraFiles.put(result.getSystemId(), new ApplicationDescription.ExternalGrammar(// I don't think there is a specific media type for XML Schema
            MediaType.APPLICATION_XML_TYPE, contents));
        }
        // Create an introspector
        //
        introspector = context.createJAXBIntrospector();
    } catch (final JAXBException e) {
        LOGGER.log(Level.SEVERE, "Failed to generate the schema for the JAX-B elements", e);
    } catch (final IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to generate the schema for the JAX-B elements due to an IO error", e);
    }
    if (introspector != null) {
        final JAXBIntrospector copy = introspector;
        return new Resolver() {

            public QName resolve(final Class type) {
                Object parameterClassInstance = null;
                try {
                    final Constructor<?> defaultConstructor = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {

                        @SuppressWarnings("unchecked")
                        @Override
                        public Constructor<?> run() throws NoSuchMethodException {
                            final Constructor<?> constructor = type.getDeclaredConstructor();
                            constructor.setAccessible(true);
                            return constructor;
                        }
                    });
                    parameterClassInstance = defaultConstructor.newInstance();
                } catch (final InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                    LOGGER.log(Level.FINE, null, ex);
                } catch (final PrivilegedActionException ex) {
                    LOGGER.log(Level.FINE, null, ex.getCause());
                }
                if (parameterClassInstance == null) {
                    return null;
                }
                try {
                    return copy.getElementName(parameterClassInstance);
                } catch (final NullPointerException e) {
                    // annotation is passed as a parameter of #getElementName method.
                    return null;
                }
            }
        };
    } else {
        // No resolver created
        return null;
    }
}
Also used : ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) CharArrayWriter(java.io.CharArrayWriter) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) ParameterizedType(java.lang.reflect.ParameterizedType) SchemaOutputResolver(javax.xml.bind.SchemaOutputResolver) HashSet(java.util.HashSet) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) GenericType(javax.ws.rs.core.GenericType) StreamResult(javax.xml.transform.stream.StreamResult) SchemaOutputResolver(javax.xml.bind.SchemaOutputResolver) PrivilegedActionException(java.security.PrivilegedActionException) Constructor(java.lang.reflect.Constructor) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) ApplicationDescription(org.glassfish.jersey.server.wadl.internal.ApplicationDescription) InvocationTargetException(java.lang.reflect.InvocationTargetException) JAXBIntrospector(javax.xml.bind.JAXBIntrospector) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type)

Example 75 with PrivilegedActionException

use of java.security.PrivilegedActionException in project netty by netty.

the class PrivilegedSocketOperationsBenchmark method testWithSMWithNullCheck.

@Benchmark
public ServerSocketChannel testWithSMWithNullCheck(final SecurityManagerInstalled sm) throws IOException {
    if (System.getSecurityManager() != null) {
        try {
            final ServerSocketChannel ssc = AccessController.doPrivileged(new PrivilegedExceptionAction<ServerSocketChannel>() {

                @Override
                public ServerSocketChannel run() throws Exception {
                    final ServerSocketChannel ssc = ServerSocketChannel.open();
                    ssc.socket().bind(null);
                    ssc.configureBlocking(false);
                    ssc.accept();
                    return ssc;
                }
            });
            ssc.close();
            return ssc;
        } catch (final PrivilegedActionException e) {
            throw (IOException) e.getCause();
        }
    } else {
        // this should never happen during benchmarking, but we write the correct code here
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(null);
        ssc.configureBlocking(false);
        ssc.accept();
        ssc.close();
        return ssc;
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) PrivilegedActionException(java.security.PrivilegedActionException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Aggregations

PrivilegedActionException (java.security.PrivilegedActionException)135 IOException (java.io.IOException)58 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)56 Subject (javax.security.auth.Subject)23 LoginContext (javax.security.auth.login.LoginContext)14 LoginException (javax.security.auth.login.LoginException)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)11 Method (java.lang.reflect.Method)11 URISyntaxException (java.net.URISyntaxException)11 HashSet (java.util.HashSet)11 ServletException (javax.servlet.ServletException)11 AccessControlContext (java.security.AccessControlContext)10 Principal (java.security.Principal)9 GSSException (org.ietf.jgss.GSSException)9 Field (java.lang.reflect.Field)8 SolrServerException (org.apache.solr.client.solrj.SolrServerException)7 GSSManager (org.ietf.jgss.GSSManager)7 MalformedURLException (java.net.MalformedURLException)6 ArrayList (java.util.ArrayList)6 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)6