Java Code Examples for java.security.PrivilegedActionException#getCause()

The following examples show how to use java.security.PrivilegedActionException#getCause() . 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: DefaultInstanceManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected Class<?> loadClassMaybePrivileged(final String className,
        final ClassLoader classLoader) throws ClassNotFoundException {
    Class<?> clazz;
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {

                @Override
                public Class<?> run() throws Exception {
                    return loadClass(className, classLoader);
                }
            });
        } catch (PrivilegedActionException e) {
            Throwable t = e.getCause();
            if (t instanceof ClassNotFoundException) {
                throw (ClassNotFoundException) t;
            }
            throw new RuntimeException(t);
        }
    } else {
        clazz = loadClass(className, classLoader);
    }
    checkAccess(clazz);
    return clazz;
}
 
Example 2
Source File: RMIIIOPServerImpl.java    From hottub 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 3
Source File: RMIIIOPServerImpl.java    From dragonwell8_jdk 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 4
Source File: ConcurrentLinkedDeque8.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @return Instance of Unsafe class.
 */
static Unsafe unsafe() {
    try {
        return Unsafe.getUnsafe();
    }
    catch (SecurityException ignored) {
        try {
            return AccessController.doPrivileged
                (new PrivilegedExceptionAction<Unsafe>() {
                    @Override public Unsafe run() throws Exception {
                        Field f = Unsafe.class.getDeclaredField("theUnsafe");

                        f.setAccessible(true);

                        return (Unsafe) f.get(null);
                    }
                });
        }
        catch (PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics.", e.getCause());
        }
    }
}
 
Example 5
Source File: ShutdownHook.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private WriteableUserPath makeDumpOnExitPath(PlatformRecording recording) {
    try {
        String name = Utils.makeFilename(recording.getRecording());
        AccessControlContext acc = recording.getNoDestinationDumpOnExitAccessControlContext();
        return AccessController.doPrivileged(new PrivilegedExceptionAction<WriteableUserPath>() {
            @Override
            public WriteableUserPath run() throws Exception {
                return new WriteableUserPath(recording.getDumpOnExitDirectory().toPath().resolve(name));
            }
        }, acc);
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof SecurityException) {
            Logger.log(LogTag.JFR, LogLevel.WARN, "Not allowed to create dump path for recording " + recording.getId() + " on exit.");
        }
        if (t instanceof IOException) {
            Logger.log(LogTag.JFR, LogLevel.WARN, "Could not dump " + recording.getId() + " on exit.");
        }
        return null;
    }
}
 
Example 6
Source File: SamlHTTPMetadataResolver.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private static HttpClient createHttpClient(Settings settings, Path configPath) throws Exception {
    try {
        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        return AccessController.doPrivileged(new PrivilegedExceptionAction<HttpClient>() {
            @Override
            public HttpClient run() throws Exception {
                return createHttpClient0(settings, configPath);
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example 7
Source File: SecuritySupport.java    From openjdk-jdk8u 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 8
Source File: ReflectionHelper.java    From cqrs-eventsourcing-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Creates class instance by calling the default constructor.
 */
public static <T> T instantiate(final Class<T> clazz) {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {
            @Override
            public T run() throws Exception {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                return constructor.newInstance();
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof NoSuchMethodException) {
            throw new RuntimeException(clazz + " must have a default constructor");
        }
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: RequestDispatcherImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void include(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    if(System.getSecurityManager() != null) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    setupIncludeImpl(request, response);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            if(e.getCause() instanceof ServletException) {
                throw (ServletException)e.getCause();
            } else if(e.getCause() instanceof IOException) {
                throw (IOException)e.getCause();
            } else if(e.getCause() instanceof RuntimeException) {
                throw (RuntimeException)e.getCause();
            } else {
                throw new RuntimeException(e.getCause());
            }
        }
    } else {
        setupIncludeImpl(request, response);
    }
}
 
Example 10
Source File: SecurityActions.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
static TheUnsafe getSunMiscUnsafeAnonymously() throws ClassNotFoundException
{
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<TheUnsafe>() { public TheUnsafe run() throws
                    ClassNotFoundException, NoSuchFieldException, SecurityException,
                    IllegalArgumentException, IllegalAccessException {
                Class<?> unsafe = Class.forName("sun.misc.Unsafe");
                Field theUnsafe = unsafe.getDeclaredField("theUnsafe");
                theUnsafe.setAccessible(true);
                TheUnsafe usf = stack.new TheUnsafe(unsafe, theUnsafe.get(null));
                theUnsafe.setAccessible(false);
                disableWarning(usf);
                return usf;
            }
        });
    }
    catch (PrivilegedActionException e) {
        if (e.getCause() instanceof ClassNotFoundException)
            throw (ClassNotFoundException) e.getCause();
        if (e.getCause() instanceof NoSuchFieldException)
            throw new ClassNotFoundException("No such instance.", e.getCause());
        if (e.getCause() instanceof IllegalAccessException
                || e.getCause() instanceof IllegalAccessException
                || e.getCause() instanceof SecurityException)
            throw new ClassNotFoundException("Security denied access.", e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 11
Source File: SocketUtils.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static InetAddress addressByName(final String hostname) throws UnknownHostException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress>() {
            @Override
            public InetAddress run() throws UnknownHostException {
                return InetAddress.getByName(hostname);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (UnknownHostException) e.getCause();
    }
}
 
Example 12
Source File: ClassLoader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static synchronized void initSystemClassLoader() {
    if (!sclSet) {
        if (scl != null)
            throw new IllegalStateException("recursive invocation");
        sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
        if (l != null) {
            Throwable oops = null;
            scl = l.getClassLoader();
            try {
                scl = AccessController.doPrivileged(
                    new SystemClassLoaderAction(scl));
            } catch (PrivilegedActionException pae) {
                oops = pae.getCause();
                if (oops instanceof InvocationTargetException) {
                    oops = oops.getCause();
                }
            }
            if (oops != null) {
                if (oops instanceof Error) {
                    throw (Error) oops;
                } else {
                    // wrap the exception
                    throw new Error(oops);
                }
            }
        }
        sclSet = true;
    }
}
 
Example 13
Source File: CalendarSystem.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a {@link Properties} loaded from lib/calendars.properties.
 *
 * @return a {@link Properties} loaded from lib/calendars.properties
 * @throws IOException if an error occurred when reading from the input stream
 * @throws IllegalArgumentException if the input stream contains any malformed
 *                                  Unicode escape sequences
 */
public static Properties getCalendarProperties() throws IOException {
    Properties calendarProps = null;
    try {
        String homeDir = AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("java.home"));
        final String fname = homeDir + File.separator + "lib" + File.separator
                             + "calendars.properties";
        calendarProps = AccessController.doPrivileged(new PrivilegedExceptionAction<Properties>() {
            @Override
            public Properties run() throws IOException {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(fname)) {
                    props.load(fis);
                }
                return props;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) cause;
        }
        // Should not happen
        throw new InternalError(cause);
    }
    return calendarProps;
}
 
Example 14
Source File: URLBlobContainer.java    From crate with Apache License 2.0 5 votes vote down vote up
@SuppressForbidden(reason = "We call connect in doPrivileged and provide SocketPermission")
private static InputStream getInputStream(URL url) throws IOException {
    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<InputStream>) url::openStream);
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
 
Example 15
Source File: SocketUtils.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress)
        throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws IOException {
                return socketChannel.connect(remoteAddress);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
 
Example 16
Source File: AbstractJWTFilter.java    From knox with Apache License 2.0 5 votes vote down vote up
protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
  Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
  AuditContext context = auditService.getContext();
  if (context != null) {
    context.setUsername( principal.getName() );
    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
    if (sourceUri != null) {
      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
    }
  }

  try {
    Subject.doAs(
      subject,
      new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          chain.doFilter(request, response);
          return null;
        }
      }
      );
  }
  catch (PrivilegedActionException e) {
    Throwable t = e.getCause();
    if (t instanceof IOException) {
      throw (IOException) t;
    }
    else if (t instanceof ServletException) {
      throw (ServletException) t;
    }
    else {
      throw new ServletException(t);
    }
  }
}
 
Example 17
Source File: CalendarSystem.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a {@link Properties} loaded from lib/calendars.properties.
 *
 * @return a {@link Properties} loaded from lib/calendars.properties
 * @throws IOException if an error occurred when reading from the input stream
 * @throws IllegalArgumentException if the input stream contains any malformed
 *                                  Unicode escape sequences
 */
public static Properties getCalendarProperties() throws IOException {
    Properties calendarProps = null;
    try {
        String homeDir = AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("java.home"));
        final String fname = homeDir + File.separator + "lib" + File.separator
                             + "calendars.properties";
        calendarProps = AccessController.doPrivileged(new PrivilegedExceptionAction<Properties>() {
            @Override
            public Properties run() throws IOException {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(fname)) {
                    props.load(fis);
                }
                return props;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) cause;
        }
        // Should not happen
        throw new InternalError(cause);
    }
    return calendarProps;
}
 
Example 18
Source File: SecurityActions.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Set a single Field value
 *
 * @param target The object to set it on
 * @param fieldName The field name
 * @param value The new value
 */
public static void setFieldValue(final Class<?> source, final Object target, final String fieldName,
        final Object value) throws NoSuchFieldException {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                Field field = source.getDeclaredField(fieldName);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                field.set(target, value);
                return null;
            }
        });
    } // Unwrap
    catch (final PrivilegedActionException pae) {
        final Throwable t = pae.getCause();
        // Rethrow
        if (t instanceof NoSuchFieldException) {
            throw (NoSuchFieldException) t;
        } else {
            // No other checked Exception thrown by Class.getConstructor
            try {
                throw (RuntimeException) t;
            } // Just in case we've really messed up
            catch (final ClassCastException cce) {
                throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
            }
        }
    }
}
 
Example 19
Source File: PulsarSaslClient.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public PulsarSaslClient(String serverHostname, String serverType, Subject subject) throws SaslException {
    checkArgument(subject != null, "Cannot create SASL client with NULL JAAS subject");
    checkArgument(!Strings.isNullOrEmpty(serverHostname), "Cannot create SASL client with NUll server name");
    if (!serverType.equals(SaslConstants.SASL_BROKER_PROTOCOL) && !serverType
                                                                       .equals(SaslConstants.SASL_PROXY_PROTOCOL)) {
        log.warn("The server type {} is not recommended", serverType);
    }

    String serverPrincipal = serverType.toLowerCase() + "/" + serverHostname;
    this.clientSubject = subject;
    if (clientSubject.getPrincipals().isEmpty()) {
        throw new SaslException("Cannot create SASL client with empty JAAS subject principal");
    }
    // GSSAPI/Kerberos
    final Object[] principals = clientSubject.getPrincipals().toArray();
    final Principal clientPrincipal = (Principal) principals[0];

    final KerberosName clientKerberosName = new KerberosName(clientPrincipal.getName());
    KerberosName serviceKerberosName = new KerberosName(serverPrincipal + "@" + clientKerberosName.getRealm());
    final String serviceName = serviceKerberosName.getServiceName();
    final String serviceHostname = serviceKerberosName.getHostName();
    final String clientPrincipalName = clientKerberosName.toString();
    log.info("Using JAAS/SASL/GSSAPI auth to connect to server Principal {},",
        serverPrincipal);

    try {
        this.saslClient = Subject.doAs(clientSubject, new PrivilegedExceptionAction<SaslClient>() {
            @Override
            public SaslClient run() throws SaslException {
                String[] mechs = {"GSSAPI"};
                return Sasl.createSaslClient(mechs, clientPrincipalName, serviceName, serviceHostname, null,
                    new ClientCallbackHandler());
            }
        });
    } catch (PrivilegedActionException err) {
        log.error("GSSAPI client error", err.getCause());
        throw new SaslException("error while booting GSSAPI client", err.getCause());
    }

    if (saslClient == null) {
        throw new SaslException("Cannot create JVM SASL Client");
    }

}
 
Example 20
Source File: SecureCaller.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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);
}