Search in sources :

Example 16 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project calcite-avatica by apache.

the class AvaticaJaasKrbUtil method loginUsingKeytab.

public static Subject loginUsingKeytab(String principal, File keytabFile) throws LoginException {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    Configuration conf = useKeytab(principal, keytabFile);
    String confName = "KeytabConf";
    LoginContext loginContext = new LoginContext(confName, subject, null, conf);
    loginContext.login();
    return loginContext.getSubject();
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) LoginContext(javax.security.auth.login.LoginContext) Configuration(javax.security.auth.login.Configuration) Principal(java.security.Principal) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Subject(javax.security.auth.Subject) HashSet(java.util.HashSet)

Example 17 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project zm-mailbox by Zimbra.

the class GssAuthenticator method initialize.

@Override
public boolean initialize() throws IOException {
    Krb5Keytab keytab = getKeytab(LC.krb5_keytab.value());
    if (keytab == null) {
        sendFailed("mechanism not supported");
        return false;
    }
    debug("keytab file = %s", keytab.getFile());
    final String host;
    if (LC.krb5_service_principal_from_interface_address.booleanValue()) {
        String localSocketHostname = localAddress.getCanonicalHostName().toLowerCase();
        if (localSocketHostname.length() == 0 || Character.isDigit(localSocketHostname.charAt(0)))
            localSocketHostname = LC.zimbra_server_hostname.value();
        host = localSocketHostname;
    } else {
        host = LC.zimbra_server_hostname.value();
    }
    KerberosPrincipal kp = new KerberosPrincipal(getProtocol() + '/' + host);
    debug("kerberos principal = %s", kp);
    Subject subject = getSubject(keytab, kp);
    if (subject == null) {
        sendFailed();
        return false;
    }
    debug("subject = %s", subject);
    final Map<String, String> props = getSaslProperties();
    if (DEBUG && props != null) {
        String qop = props.get(Sasl.QOP);
        debug("Sent QOP = " + (qop != null ? qop : "auth"));
    }
    try {
        mSaslServer = (SaslServer) Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws SaslException {
                return Sasl.createSaslServer(getMechanism(), getProtocol(), host, props, new GssCallbackHandler());
            }
        });
    } catch (PrivilegedActionException e) {
        sendFailed();
        getLog().warn("Could not create SaslServer", e.getCause());
        return false;
    }
    return true;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) PrivilegedActionException(java.security.PrivilegedActionException) SaslException(javax.security.sasl.SaslException) Krb5Keytab(com.zimbra.cs.security.kerberos.Krb5Keytab) Subject(javax.security.auth.Subject)

Example 18 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project wildfly by wildfly.

the class ElytronSubjectFactory method createSubject.

/**
 * Create a {@link Subject} with the principal and password credential obtained from the authentication configuration
 * that matches the target {@link URI}.
 *
 * @param authenticationContext the {@link AuthenticationContext} used to select a configuration that matches the
 *                              target {@link URI}.
 * @return the constructed {@link Subject}. It contains a single principal and a {@link PasswordCredential}.
 */
private Subject createSubject(final AuthenticationContext authenticationContext) {
    final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(this.targetURI, authenticationContext);
    final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration);
    final NameCallback nameCallback = new NameCallback("Username: ");
    final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
    final CredentialCallback credentialCallback = new CredentialCallback(GSSKerberosCredential.class);
    try {
        handler.handle(new Callback[] { nameCallback, passwordCallback, credentialCallback });
        Subject subject = new Subject();
        // if a GSSKerberosCredential was found, add the enclosed GSSCredential and KerberosTicket to the private set in the Subject.
        if (credentialCallback.getCredential() != null) {
            GSSKerberosCredential kerberosCredential = GSSKerberosCredential.class.cast(credentialCallback.getCredential());
            this.addPrivateCredential(subject, kerberosCredential.getKerberosTicket());
            this.addPrivateCredential(subject, kerberosCredential.getGssCredential());
            // use the GSSName to build a kerberos principal and set it in the Subject.
            GSSName gssName = kerberosCredential.getGssCredential().getName();
            subject.getPrincipals().add(new KerberosPrincipal(gssName.toString()));
        }
        // use the name from the callback, if available, to build a principal and set it in the Subject.
        if (nameCallback.getName() != null) {
            subject.getPrincipals().add(new NamePrincipal(nameCallback.getName()));
        }
        // use the password from the callback, if available, to build a credential and set it as a private credential in the Subject.
        if (passwordCallback.getPassword() != null) {
            this.addPrivateCredential(subject, new PasswordCredential(nameCallback.getName(), passwordCallback.getPassword()));
        }
        return subject;
    } catch (Exception e) {
        throw new SecurityException(e);
    }
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) GSSName(org.ietf.jgss.GSSName) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) CallbackHandler(javax.security.auth.callback.CallbackHandler) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(javax.resource.spi.security.PasswordCredential) CredentialCallback(org.wildfly.security.auth.callback.CredentialCallback) Subject(javax.security.auth.Subject) GSSKerberosCredential(org.wildfly.security.credential.GSSKerberosCredential) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback)

Example 19 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project zeppelin by apache.

the class YarnClient method callRestUrl.

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));
    }
    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;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) ZeppelinConfiguration(org.apache.zeppelin.conf.ZeppelinConfiguration) Configuration(org.apache.hadoop.conf.Configuration) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) LoginContext(javax.security.auth.login.LoginContext) HashSet(java.util.HashSet) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) HttpResponse(org.apache.http.HttpResponse) JsonIOException(com.google.gson.JsonIOException) IOException(java.io.IOException) Subject(javax.security.auth.Subject) JsonIOException(com.google.gson.JsonIOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) HttpClient(org.apache.http.client.HttpClient) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) JsonObject(com.google.gson.JsonObject) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal)

Example 20 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project zeppelin by apache.

the class KerberosRealm method onInit.

/**
 * Initializes the KerberosRealm by 'kinit'ing using principal and keytab.
 * <p>
 * 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, (PrivilegedExceptionAction<GSSManager>) 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);
    }
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Configuration(org.apache.hadoop.conf.Configuration) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Subject(javax.security.auth.Subject) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) KeyTab(javax.security.auth.kerberos.KeyTab) Groups(org.apache.hadoop.security.Groups) GSSManager(org.ietf.jgss.GSSManager) File(java.io.File) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal)

Aggregations

KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)71 Principal (java.security.Principal)36 Subject (javax.security.auth.Subject)31 HashSet (java.util.HashSet)21 LoginContext (javax.security.auth.login.LoginContext)20 Test (org.junit.Test)14 X500Principal (javax.security.auth.x500.X500Principal)13 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)11 IOException (java.io.IOException)10 File (java.io.File)9 KerberosKey (javax.security.auth.kerberos.KerberosKey)9 PrivilegedActionException (java.security.PrivilegedActionException)8 StringTokenizer (java.util.StringTokenizer)6 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Properties (java.util.Properties)3 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 KeyTab (javax.security.auth.kerberos.KeyTab)3