/** * Load class. * * @param className the class name * @return loaded class * @throws ClassNotFoundException for any error */ protected Class loadClass(final String className) throws ClassNotFoundException { try { return (Class)AccessController.doPrivileged(new PrivilegedExceptionAction(){ public Object run() throws Exception{ ClassLoader cl = Thread.currentThread().getContextClassLoader(); return Class.forName(className, true, cl); } }); } catch (PrivilegedActionException pae) { throw new RuntimeException("cannot load the class: " + className, pae.getException()); } }
/** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call * to Unsafe.getUnsafe when integrating into a jdk. * * @return a sun.misc.Unsafe */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) { } try { return java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); } }); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } }
/** * Perform an action with permission checking enabled. If permission checking is already enabled, the action is * simply run. * * @param action the action to perform * @param context the access control context to use * @param <T> the action return type * @return the return value of the action * @throws PrivilegedActionException if the action threw an exception */ public static <T> T doChecked(PrivilegedExceptionAction<T> action, AccessControlContext context) throws PrivilegedActionException { final Context ctx = CTX.get(); if (ctx.checking) { try { return action.run(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new PrivilegedActionException(e); } } ctx.checking = true; try { return AccessController.doPrivileged(action, context); } finally { ctx.checking = false; } }
@Override public final PrivilegedActionException privilegedActionFailed(final Exception e) { final PrivilegedActionException result = new PrivilegedActionException(e); final StackTraceElement[] st = result.getStackTrace(); result.setStackTrace(Arrays.copyOfRange(st, 1, st.length)); return result; } private static final String readOnlyPermissionCollection = "COM00300: Permission collection is read-only";
public static InetAddress[] allAddressesByName(final String hostname) throws UnknownHostException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress[]>() { @Override public InetAddress[] run() throws UnknownHostException { return InetAddress.getAllByName(hostname); } }); } catch (PrivilegedActionException e) { throw (UnknownHostException) e.getCause(); } }
static <T> Constructor<T> getConstructor(Class<T> javaClass, Class<?>... parameterTypes) throws NoSuchMethodException { if (System.getSecurityManager() != null) { try { return AccessController.doPrivileged(GetConstructorAction.of(javaClass, parameterTypes)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchMethodException) { throw (NoSuchMethodException) e.getCause(); } throw new WeldException(e.getCause()); } } else { return javaClass.getConstructor(parameterTypes); } }
private static Class<AsyncHttpClient> getClass(final String asyncImplClassName) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<AsyncHttpClient>>() { @SuppressWarnings("unchecked") public Class<AsyncHttpClient> run() throws ClassNotFoundException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) try { return (Class<AsyncHttpClient>) cl.loadClass(asyncImplClassName); } catch (ClassNotFoundException e) { AsyncHttpClientFactory.logger.info("Couldn't find class : " + asyncImplClassName + " in thread context classpath " + "checking system class path next", e); } cl = ClassLoader.getSystemClassLoader(); return (Class<AsyncHttpClient>) cl.loadClass(asyncImplClassName); } }); } catch (PrivilegedActionException e) { throw new AsyncHttpClientImplException("Class : " + asyncImplClassName + " couldn't be found in " + " the classpath due to : " + e.getMessage(), e); } } }
private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject) throws IOException, ServletException { try { Subject.doAs( subject, new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { doFilterInternal(request, response, chain); 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); } } }
final Subject subject = new Subject(); final LoginContext lc; try { lc = new LoginContext("KDC", subject, (c) -> { throw new FastUnsupportedCallbackException(c[0]); }, configuration); lc.login(); log.tracef("Logging in using LoginContext and subject [%s] succeed", subject); Set<KerberosTicket> kerberosTickets = doPrivileged((PrivilegedAction<Set<KerberosTicket>>) () -> subject.getPrivateCredentials(KerberosTicket.class)); if (kerberosTickets.size() > 1) { throw log.tooManyKerberosTicketsFound(); return Subject.doAs(subject, (PrivilegedExceptionAction<GSSKerberosCredential>) () -> { Set<KerberosPrincipal> principals = subject.getPrincipals(KerberosPrincipal.class); if (principals.size() < 1) { if (e.getCause() instanceof GeneralSecurityException) { throw (GeneralSecurityException) e.getCause(); throw new GeneralSecurityException(e.getCause());
CallbackHandler callbackHandler = getUsernamePasswordHandler( authPolicy.getUserName(), authPolicy.getPassword()); LoginContext lc = new LoginContext(contextName, null, callbackHandler, loginConfig); lc.login(); subject = lc.getSubject(); return Subject.doAs(subject, new CreateServiceTicketAction(context, token)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof GSSException) { throw (GSSException) e.getCause();
String principal = config.getProperty(PRINCIPAL); if (principal == null || principal.trim().length() == 0) { throw new ServletException("Principal not defined in configuration"); throw new ServletException("Keytab not defined in configuration"); throw new ServletException("Keytab does not exist: " + keytab); new KerberosAuthenticator.DruidKerberosConfiguration(keytab, spnegoPrincipal); final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration); try { loginContext.login(); gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() throw ex.getException();
public Class<?> loadBeanClass(final String className) { try { return (Class<?>) AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return Class.forName(className, true, getClassLoader(this.getClass())); } }); } catch (PrivilegedActionException pae) { throw new WeldException(BeanMessage.CANNOT_LOAD_CLASS, className, pae.getException()); } }
public static <T> T doAs(String principal, final Callable<T> callable) throws Exception { LoginContext loginContext = null; try { Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(KerberosTestUtils.getClientPrincipal())); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal)); loginContext.login(); subject = loginContext.getSubject(); return Subject.doAs(subject, new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } finally { if (loginContext != null) { loginContext.logout(); } } }
private static <T> T doAs(Subject subject, GssSupplier<T> action) throws GSSException { try { return Subject.doAs(subject, (PrivilegedExceptionAction<T>) action::get); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); throwIfInstanceOf(t, GSSException.class); throwIfUnchecked(t); throw new RuntimeException(t); } }
@Override public boolean login() throws LoginException { if (!options.containsKey(REALM_PROPERTY)) { logger.warn(REALM_PROPERTY + " is not set"); throw new LoginException("cannot authenticate through the delegating realm"); } context = new LoginContext((String) options.get(REALM_PROPERTY), this.subject, this.callbackHandler); context.login(); try { return Subject.doAs(context.getSubject(), (PrivilegedExceptionAction<Boolean>) this::doLogin); } catch (PrivilegedActionException pExcp) { logger.error("error with delegated authentication", pExcp); throw new LoginException(pExcp.getMessage()); } }
private static Connection createConnection(String jdbcUrl, String userName, String password) throws Exception { if (jdbcUrl.contains(";auth=kerberos")) { String client = System.getProperty("java.security.auth.login.config.client", "KerberosClient"); LoginContext lc = new LoginContext(client, callbacks -> { for (Callback cb : callbacks) { if (cb instanceof NameCallback) ((NameCallback) cb).setName(userName); if (cb instanceof PasswordCallback) ((PasswordCallback) cb).setPassword(password.toCharArray()); } }); lc.login(); Subject subject = lc.getSubject(); try { return Subject.doAs(subject, (PrivilegedExceptionAction<Connection>) () -> DriverManager.getConnection(jdbcUrl, userName, password)); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { return DriverManager.getConnection(jdbcUrl, userName, password); } }
@Override public Object invoke( Object proxy, final Method method, final Object[] args ) throws Throwable { try { return Subject.doAs( loginContext.getSubject(), new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { Object result = method.invoke( delegate, args ); if ( result != null ) { for ( Class<?> iface : result.getClass().getInterfaces() ) { if ( interfacesToDelegate.contains( iface ) ) { result = forObject( result, loginContext, interfacesToDelegate ); break; } } } return result; } } ); } catch ( PrivilegedActionException e ) { if ( e.getCause() instanceof InvocationTargetException ) { throw ( (InvocationTargetException) e.getCause() ).getCause(); } throw e; } } }
GSSName gssName = manager.createName(servicePrincipalName + "@" + serviceHostname, GSSName.NT_HOSTBASED_SERVICE); GSSCredential cred = manager.createCredential(gssName, GSSContext.INDEFINITE_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY); subject.getPrivateCredentials().add(cred); } catch (GSSException ex) { LOG.warn("Cannot add private credential to subject; clients authentication may fail", ex); return Subject.doAs(subject, (PrivilegedExceptionAction<SaslServer>) () -> Sasl.createSaslServer(saslMechanism, servicePrincipalName, serviceHostname, configs, saslServerCallbackHandler)); } catch (PrivilegedActionException e) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause());
final String serverName = request.getServerName(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException());
@Override public Object run() throws Exception { try { return Subject.doAsPrivileged( login.getSubject(), action, null); } catch (PrivilegedActionException e) { throw e.getException(); } } });