Search in sources :

Example 76 with PrivilegedActionException

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

the class PrivilegedSocketOperationsBenchmark method testWithoutSMWithNullCheck.

@Benchmark
public ServerSocketChannel testWithoutSMWithNullCheck(final SecurityManagerEmpty sm) throws IOException {
    if (System.getSecurityManager() != null) {
        // this should never happen during benchmarking, but we write the correct code here
        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 {
        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)

Example 77 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hadoop by apache.

the class KerberosAuthenticationHandler method init.

/**
   * Initializes the authentication handler instance.
   * <p>
   * It creates a Kerberos context using the principal and keytab specified in
   * the configuration.
   * <p>
   * This method is invoked by the {@link AuthenticationFilter#init} method.
   *
   * @param config configuration properties to initialize the handler.
   *
   * @throws ServletException thrown if the handler could not be initialized.
   */
@Override
public void init(Properties config) throws ServletException {
    try {
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }
        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }
        for (String spnegoPrincipal : spnegoPrincipals) {
            LOG.info("Login using keytab {}, for principal {}", keytab, spnegoPrincipal);
            final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                LOG.warn("Failed to login as [{}]", spnegoPrincipal, le);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
            KerberosName kerbName = new KerberosName(spnegoPrincipal);
            if (kerbName.getHostName() != null && kerbName.getServiceName() != null && kerbName.getServiceName().equals("HTTP")) {
                boolean added = serverPrincipalMap.put(kerbName.getHostName(), spnegoPrincipal);
                LOG.info("Map server: {} to principal: [{}], added = {}", kerbName.getHostName(), spnegoPrincipal, added);
            } else {
                LOG.warn("HTTP principal: [{}] is invalid for SPNEGO!", spnegoPrincipal);
            }
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}
Also used : AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) KerberosName(org.apache.hadoop.security.authentication.util.KerberosName) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) LoginException(javax.security.auth.login.LoginException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException) ServletException(javax.servlet.ServletException) LoginContext(javax.security.auth.login.LoginContext) LoginException(javax.security.auth.login.LoginException) File(java.io.File)

Example 78 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hadoop by apache.

the class KerberosAuthenticationHandler method authenticate.

/**
   * It enforces the the Kerberos SPNEGO authentication sequence returning an
   * {@link AuthenticationToken} only after the Kerberos SPNEGO sequence has
   * completed successfully.
   *
   * @param request the HTTP client request.
   * @param response the HTTP client response.
   *
   * @return an authentication token if the Kerberos SPNEGO sequence is complete
   * and valid, <code>null</code> if it is in progress (in this case the handler
   * handles the response to the client).
   *
   * @throws IOException thrown if an IO error occurred.
   * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
   */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);
    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting for url: {}", request.getRequestURL());
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        final String serverName = InetAddress.getByName(request.getServerName()).getCanonicalHostName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                private Set<String> serverPrincipals = serverPrincipalMap.get(serverName);

                @Override
                public AuthenticationToken run() throws Exception {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("SPNEGO with server principals: {} for {}", serverPrincipals.toString(), serverName);
                    }
                    AuthenticationToken token = null;
                    Exception lastException = null;
                    for (String serverPrincipal : serverPrincipals) {
                        try {
                            token = runWithPrincipal(serverPrincipal, clientToken, base64, response);
                        } catch (Exception ex) {
                            lastException = ex;
                            LOG.trace("Auth {} failed with {}", serverPrincipal, ex);
                        } finally {
                            if (token != null) {
                                LOG.trace("Auth {} successfully", serverPrincipal);
                                break;
                            }
                        }
                    }
                    if (token != null) {
                        return token;
                    } else {
                        throw new AuthenticationException(lastException);
                    }
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Set(java.util.Set) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException)

Example 79 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hadoop by apache.

the class KerberosTestUtils method doAs.

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();
        }
    }
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) PrivilegedActionException(java.security.PrivilegedActionException) Subject(javax.security.auth.Subject) PrivilegedActionException(java.security.PrivilegedActionException) LoginContext(javax.security.auth.login.LoginContext) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 80 with PrivilegedActionException

use of java.security.PrivilegedActionException in project hadoop by apache.

the class KerberosAuthenticator method doSpnegoSequence.

/**
   * Implements the SPNEGO authentication sequence interaction using the current default principal
   * in the Kerberos cache (normally set via kinit).
   *
   * @param token the authentication token being used for the user.
   *
   * @throws IOException if an IO error occurred.
   * @throws AuthenticationException if an authentication error occurred.
   */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null || (!KerberosUtil.hasKerberosKeyTab(subject) && !KerberosUtil.hasKerberosTicket(subject))) {
            LOG.debug("No subject in context, logging in");
            subject = new Subject();
            LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
            login.login();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Using subject: " + subject);
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", KerberosAuthenticator.this.url.getHost());
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);
                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;
                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }
                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        if (ex.getException() instanceof IOException) {
            throw (IOException) ex.getException();
        } else {
            throw new AuthenticationException(ex.getException());
        }
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}
Also used : GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) Oid(org.ietf.jgss.Oid) IOException(java.io.IOException) Subject(javax.security.auth.Subject) LoginException(javax.security.auth.login.LoginException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) LoginContext(javax.security.auth.login.LoginContext) AccessControlContext(java.security.AccessControlContext) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) LoginException(javax.security.auth.login.LoginException)

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