Example usage for javax.security.auth.kerberos KerberosPrincipal KerberosPrincipal

List of usage examples for javax.security.auth.kerberos KerberosPrincipal KerberosPrincipal

Introduction

In this page you can find the example usage for javax.security.auth.kerberos KerberosPrincipal KerberosPrincipal.

Prototype

public KerberosPrincipal(String name) 

Source Link

Document

Constructs a KerberosPrincipal from the provided string input.

Usage

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java

@Test
public void testPingWithCaseSensitiveUser() throws Exception {
    // USER1 is present in the list of users who are allowed to connect to sentry web ui.
    String userPrinciple = "user1/" + SentryServiceIntegrationBase.SERVER_HOST;
    String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM;
    Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)),
            new HashSet<Object>(), new HashSet<Object>());
    File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user1.keytab");
    SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple);
    LoginContext userLoginContext = new LoginContext("", userSubject, null,
            KerberosConfiguration.createClientConfig(userKerberosName, userKeytab));
    userLoginContext.login();/* w w w  .  j a va  2  s. c  o m*/
    Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":"
                    + SentryServiceIntegrationBase.webServerPort + "/ping");
            try {
                new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url,
                        new AuthenticatedURL.Token());
                fail("Login with user1 should fail");
            } catch (AuthenticationException e) {
                String expectedError = "status code: 403";
                if (!exceptionContainsMessage(e, expectedError)) {
                    LOG.error("UnexpectedError: " + e.getMessage(), e);
                    fail("UnexpectedError: " + e.getMessage());
                }
            }
            return null;
        }
    });
}

From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithKerberos.java

@Test
public void testPingWithUnauthorizedUser() throws Exception {
    // create an unauthorized User with Kerberos
    String userPrinciple = "user/" + SERVER_HOST;
    String userKerberosName = userPrinciple + "@" + REALM;
    Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)),
            new HashSet<Object>(), new HashSet<Object>());
    File userKeytab = new File(kdcWorkDir, "user.keytab");
    kdc.createPrincipal(userKeytab, userPrinciple);
    LoginContext userLoginContext = new LoginContext("", userSubject, null,
            KerberosConfiguration.createClientConfig(userKerberosName, userKeytab));
    userLoginContext.login();/*ww  w.  jav a  2  s  . co  m*/
    Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/ping");
            try {
                new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url,
                        new AuthenticatedURL.Token());
                fail("Here should fail.");
            } catch (AuthenticationException e) {
                String expectedError = "status code: 403";
                if (!e.getMessage().contains(expectedError)) {
                    LOG.error("UnexpectedError: " + e.getMessage(), e);
                    fail("UnexpectedError: " + e.getMessage());
                }
            }
            return null;
        }
    });
}

From source file:org.apache.sentry.service.thrift.SentryServiceIntegrationBase.java

public static void setupConf() throws Exception {
    if (kerberos) {
        setupKdc();/*from   w  w w . ja  v a 2  s . c o  m*/
        kdc = getKdc();
        kdcWorkDir = getWorkDir();
        serverKeytab = new File(kdcWorkDir, "server.keytab");
        clientKeytab = new File(kdcWorkDir, "client.keytab");
        kdc.createPrincipal(serverKeytab, SERVER_PRINCIPAL);
        kdc.createPrincipal(clientKeytab, CLIENT_PRINCIPAL);
        conf.set(ServerConfig.PRINCIPAL, getServerKerberosName());
        conf.set(ServerConfig.KEY_TAB, serverKeytab.getPath());
        conf.set(ServerConfig.ALLOW_CONNECT, CLIENT_KERBEROS_SHORT_NAME);
        conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_PRINCIPAL, getServerKerberosName());
        conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_KEYTAB, serverKeytab.getPath());

        conf.set(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "false");
        clientSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(CLIENT_KERBEROS_NAME)),
                new HashSet<Object>(), new HashSet<Object>());
        clientLoginContext = new LoginContext("", clientSubject, null,
                KerberosConfiguration.createClientConfig(CLIENT_KERBEROS_NAME, clientKeytab));
        clientLoginContext.login();
        clientSubject = clientLoginContext.getSubject();
    } else {
        LOGGER.info("Stopped KDC");
        conf.set(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_NONE);
    }
    if (haEnabled) {
        zkServer = getZKServer();
        conf.set(ServerConfig.SENTRY_HA_ENABLED, "true");
        conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_QUORUM, zkServer.getConnectString());
        conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_NAMESPACE, "sentry-test-case");
        if (kerberos) {
            conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_SECURITY, "true");
        }
    }
    if (webServerEnabled) {
        conf.set(ServerConfig.SENTRY_WEB_ENABLE, "true");
        conf.set(ServerConfig.SENTRY_WEB_PORT, String.valueOf(webServerPort));
        if (webSecurity) {
            httpKeytab = new File(kdcWorkDir, "http.keytab");
            kdc.createPrincipal(httpKeytab, HTTP_PRINCIPAL);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_KERBEROS);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_PRINCIPAL, HTTP_PRINCIPAL);
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_KEYTAB, httpKeytab.getPath());
        } else {
            conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE);
        }
    } else {
        conf.set(ServerConfig.SENTRY_WEB_ENABLE, "false");
    }
    if (pooled) {
        conf.set(ClientConfig.SENTRY_POOL_ENABLED, "true");
    }
    conf.set(ServerConfig.SENTRY_VERIFY_SCHEM_VERSION, "false");
    conf.set(ServerConfig.ADMIN_GROUPS, ADMIN_GROUP);
    conf.set(ServerConfig.RPC_ADDRESS, SERVER_HOST);
    conf.set(ServerConfig.RPC_PORT, String.valueOf(0));
    dbDir = new File(Files.createTempDir(), "sentry_policy_db");
    conf.set(ServerConfig.SENTRY_STORE_JDBC_URL,
            "jdbc:derby:;databaseName=" + dbDir.getPath() + ";create=true");
    conf.set(ServerConfig.SENTRY_STORE_JDBC_PASS, "dummy");
    server = new SentryServiceFactory().create(conf);
    conf.set(ClientConfig.SERVER_RPC_ADDRESS, server.getAddress().getHostName());
    conf.set(ClientConfig.SERVER_RPC_PORT, String.valueOf(server.getAddress().getPort()));
    conf.set(ServerConfig.SENTRY_STORE_GROUP_MAPPING, ServerConfig.SENTRY_STORE_LOCAL_GROUP_MAPPING);
}

From source file:org.apache.ws.security.message.token.KerberosServiceAction.java

public Principal run() {
    try {//from   ww  w  .ja  va  2 s.c  o  m
        GSSManager gssManager = GSSManager.getInstance();

        Oid kerberos5Oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssService = gssManager.createName(serviceName, GSSName.NT_HOSTBASED_SERVICE);
        GSSCredential credentials = gssManager.createCredential(gssService, GSSCredential.DEFAULT_LIFETIME,
                kerberos5Oid, GSSCredential.ACCEPT_ONLY);

        GSSContext secContext = gssManager.createContext(credentials);
        secContext.acceptSecContext(ticket, 0, ticket.length);

        GSSName clientName = secContext.getSrcName();
        secContext.dispose();
        return new KerberosPrincipal(clientName.toString());
    } catch (GSSException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error in validating a Kerberos token", e);
        }
    }

    return null;

}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * Initializes the KerberosRealm by 'kinit'ing using principal and keytab.
 * <p>/*from w  w  w . j ava 2  s.  co  m*/
 * It creates a Kerberos context using the principal and keytab specified in
 * the Shiro configuration.
 * <p>
 * This method should be called only once.
 *
 * @throws RuntimeException thrown if the handler could not be initialized.
 */
@Override
protected void onInit() {
    super.onInit();
    config = getConfiguration();
    try {
        if (principal == null || principal.trim().length() == 0) {
            throw new RuntimeException("Principal not defined in configuration");
        }

        if (keytab == null || keytab.trim().length() == 0) {
            throw new RuntimeException("Keytab not defined in configuration");
        }

        File keytabFile = new File(keytab);
        if (!keytabFile.exists()) {
            throw new RuntimeException("Keytab file 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 RuntimeException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        KeyTab keytabInstance = KeyTab.getInstance(keytabFile);

        serverSubject = new Subject();
        serverSubject.getPrivateCredentials().add(keytabInstance);
        for (String spnegoPrincipal : spnegoPrincipals) {
            Principal krbPrincipal = new KerberosPrincipal(spnegoPrincipal);
            LOG.info("Using keytab {}, for principal {}", keytab, krbPrincipal);
            serverSubject.getPrincipals().add(krbPrincipal);
        }

        if (nameRules == null || nameRules.trim().length() == 0) {
            LOG.warn("No auth_to_local rules defined, DEFAULT will be used.");
            nameRules = "DEFAULT";
        }

        KerberosName.setRules(nameRules);

        if (null == gssManager) {
            try {
                gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {
                    @Override
                    public GSSManager run() {
                        return GSSManager.getInstance();
                    }
                });
                LOG.trace("SPNEGO gssManager initialized.");
            } catch (PrivilegedActionException ex) {
                throw ex.getException();
            }
        }

        if (null == signer) {
            initializeSecretProvider();
        }

        Configuration hadoopConfig = new Configuration();
        hadoopGroups = new Groups(hadoopConfig);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

public HttpResponse callRestUrl(final String url, final String userId, HTTP operation) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Calling YarnClient %s %s %s", this.principal, this.keytab, url));
    }//  ww  w.ja  va  2  s .com
    javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() {
        @SuppressWarnings("serial")
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(
                    "com.sun.security.auth.module.Krb5LoginModule",
                    AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                        {
                            put("useTicketCache", "false");
                            put("useKeyTab", "true");
                            put("keyTab", keytab);
                            // Krb5 in GSS API needs to be refreshed so it does not throw the error
                            // Specified version of key is not available
                            put("refreshKrb5Config", "true");
                            put("principal", principal);
                            put("storeKey", "true");
                            put("doNotPrompt", "true");
                            put("isInitiator", "true");
                            if (LOGGER.isDebugEnabled()) {
                                put("debug", "true");
                            }
                        }
                    }) };
        }
    };

    Set<Principal> principals = new HashSet<Principal>(1);
    principals.add(new KerberosPrincipal(userId));
    Subject sub = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    try {
        // Authentication module: Krb5Login
        LoginContext loginContext = new LoginContext("Krb5Login", sub, null, config);
        loginContext.login();
        Subject serviceSubject = loginContext.getSubject();
        return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
            HttpResponse httpResponse = null;

            @Override
            public HttpResponse run() {
                try {
                    HttpUriRequest request = null;
                    switch (operation) {
                    case DELETE:
                        request = new HttpDelete(url);
                        break;
                    case POST:
                        request = new HttpPost(url);
                        break;
                    default:
                        request = new HttpGet(url);
                        break;
                    }

                    HttpClient spengoClient = buildSpengoHttpClient();
                    httpResponse = spengoClient.execute(request);
                    return httpResponse;
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
                return httpResponse;
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.polymap.core.security.SpnegoFilter.java

private void complex(HttpServletResponse httpResponse, String header) throws ServletException {
    // The data following the word Negotiate is the GSS-API data to process.
    byte gssapiData[] = new byte[0];
    try {/*  w  w  w  . j av a2  s  .  c  o  m*/
        gssapiData = com.sun.org.apache.xml.internal.security.utils.Base64
                .decode(header.substring(10).getBytes());
    } catch (Base64DecodingException e) {
        log.error("", e);
    }

    // Guard clause to check for the unsupported NTLM authentication mechanism.
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return;
    }

    /**
     * The server attempts to establish a security context. Establishment may
     * result in tokens that the server must return to the client. Tokens are
     * BASE-64 encoded GSS-API data.
     */
    GSSContext context = null;
    String outToken = null;

    try {
        GSSManager manager = GSSManager.getInstance();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
        GSSCredential serverCreds = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, spnegoOid,
                GSSCredential.ACCEPT_ONLY);

        context = manager.createContext(serverCreds);

        byte tokenBytes[] = context.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = new String(Base64.encode(tokenBytes));
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the
     * "context initiator." In the case of the Kerberos mechanism, the context
     * initiator is the Kerberos principal of the client. Additionally, the
     * client may be delegating credentials.
     */
    if (context != null && context.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = context.getSrcName();
            Principal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);

            if (context.getCredDelegState()) {
                GSSCredential delegateCredential = context.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            // TODO
            // getSpnegoSession().setUser( clientGSSName.toString() );

            /**
             * A status code 200 status response can also carry a
             * "WWW-Authenticate" response header containing the final leg of an
             * authentication. In this case, the gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                httpResponse.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                httpResponse.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                return;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            httpResponse.addHeader("Client-Warning", gsse.getMessage());
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an
         * authentication error. If a 401 containing a "WWW-Authenticate" header
         * with "Negotiate" and gssapi-data is returned from the server, it is a
         * continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            httpResponse.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return;
        } else {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");
}

From source file:org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.servicePrincipal, "servicePrincipal must be specified");
    Assert.notNull(this.keyTabLocation, "keyTab must be specified");
    if (keyTabLocation instanceof ClassPathResource) {
        LOG.warn(/*from   ww w . ja  v a 2  s  .  c o  m*/
                "Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
    }
    String keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
    // We need to remove the file prefix (if there is one), as it is not supported in Java 7 anymore.
    // As Java 6 accepts it with and without the prefix, we don't need to check for Java 7
    if (keyTabLocationAsString.startsWith("file:")) {
        keyTabLocationAsString = keyTabLocationAsString.substring(5);
    }
    LoginConfig loginConfig = new LoginConfig(keyTabLocationAsString, this.servicePrincipal, this.debug);
    Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    LoginContext lc = new LoginContext("", sub, null, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}

From source file:org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.servicePrincipal, "servicePrincipal must be specified");
    Assert.notNull(this.keyTabLocation, "keyTab must be specified");
    if (keyTabLocation instanceof ClassPathResource) {
        LOG.warn(/*  w  w  w  . j  av a2  s.  c om*/
                "Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
    }
    String keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
    // We need to remove the file prefix (if there is one), as it is not supported in Java 7 anymore.
    // As Java 6 accepts it with and without the prefix, we don't need to check for Java 7
    if (keyTabLocationAsString.startsWith("file:")) {
        keyTabLocationAsString = keyTabLocationAsString.substring(5);
    }
    LoginConfig loginConfig = new LoginConfig(keyTabLocationAsString, this.servicePrincipal, this.debug);
    Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    LoginContext lc = new LoginContext("", sub, null, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}