Search in sources :

Example 26 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project karaf by apache.

the class DigestPasswordLoginModule method login.

public boolean login() throws LoginException {
    if (usersFile == null) {
        throw new LoginException("The property users may not be null");
    }
    File f = new File(usersFile);
    if (!f.exists()) {
        throw new LoginException("Users file not found at " + f);
    }
    Properties users;
    try {
        users = new Properties(f);
    } catch (IOException ioe) {
        throw new LoginException("Unable to load user properties file " + f);
    }
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    if (callbackHandler != null) {
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException ioe) {
            throw new LoginException(ioe.getMessage());
        } catch (UnsupportedCallbackException uce) {
            throw new LoginException(uce.getMessage() + " not available to obtain information from user");
        }
    }
    // user callback get value
    if (((NameCallback) callbacks[0]).getName() == null) {
        throw new LoginException("Username can not be null");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user.startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
        // you can't log in under a group name
        throw new FailedLoginException("login failed");
    }
    // password callback get value
    if (((PasswordCallback) callbacks[1]).getPassword() == null) {
        throw new LoginException("Password can not be null");
    }
    String password = new String(((PasswordCallback) callbacks[1]).getPassword());
    // user infos container read from the users properties file
    String userInfos = null;
    try {
        userInfos = users.get(user);
    } catch (NullPointerException e) {
    //error handled in the next statement
    }
    if (userInfos == null) {
        if (!this.detailedLoginExcepion) {
            throw new FailedLoginException("login failed");
        } else {
            throw new FailedLoginException("User " + user + " does not exist");
        }
    }
    // the password is in the first position
    String[] infos = userInfos.split(",");
    String storedPassword = infos[0];
    CallbackHandler myCallbackHandler = null;
    try {
        Field field = callbackHandler.getClass().getDeclaredField("ch");
        field.setAccessible(true);
        myCallbackHandler = (CallbackHandler) field.get(callbackHandler);
    } catch (Exception e) {
        throw new LoginException("Unable to load underlying callback handler");
    }
    if (myCallbackHandler instanceof NameDigestPasswordCallbackHandler) {
        NameDigestPasswordCallbackHandler digestCallbackHandler = (NameDigestPasswordCallbackHandler) myCallbackHandler;
        storedPassword = doPasswordDigest(digestCallbackHandler.getNonce(), digestCallbackHandler.getCreatedTime(), storedPassword);
    }
    // check the provided password
    if (!checkPassword(password, storedPassword)) {
        if (!this.detailedLoginExcepion) {
            throw new FailedLoginException("login failed");
        } else {
            throw new FailedLoginException("Password for " + user + " does not match");
        }
    }
    principals = new HashSet<>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
        if (infos[i].trim().startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
            // it's a group reference
            principals.add(new GroupPrincipal(infos[i].trim().substring(PropertiesBackingEngine.GROUP_PREFIX.length())));
            String groupInfo = users.get(infos[i].trim());
            if (groupInfo != null) {
                String[] roles = groupInfo.split(",");
                for (int j = 1; j < roles.length; j++) {
                    principals.add(new RolePrincipal(roles[j].trim()));
                }
            }
        } else {
            // it's an user reference
            principals.add(new RolePrincipal(infos[i].trim()));
        }
    }
    users.clear();
    if (debug) {
        LOGGER.debug("Successfully logged in {}", user);
    }
    return true;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) IOException(java.io.IOException) Properties(org.apache.felix.utils.properties.Properties) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) FailedLoginException(javax.security.auth.login.FailedLoginException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) Field(java.lang.reflect.Field) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) FailedLoginException(javax.security.auth.login.FailedLoginException) GroupPrincipal(org.apache.karaf.jaas.boot.principal.GroupPrincipal) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) File(java.io.File)

Example 27 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project wildfly by wildfly.

the class SlaveHostControllerAuthenticationTestCase method setupDomain.

@BeforeClass
public static void setupDomain() throws Exception {
    // Set up a domain with a master that doesn't support local auth so slaves have to use configured credentials
    testSupport = DomainTestSupport.create(DomainTestSupport.Configuration.create(SlaveHostControllerAuthenticationTestCase.class.getSimpleName(), "domain-configs/domain-standard.xml", "host-configs/host-master-no-local.xml", "host-configs/host-secrets.xml"));
    // Tweak the callback handler so the master test driver client can authenticate
    // To keep setup simple it uses the same credentials as the slave host
    WildFlyManagedConfiguration masterConfig = testSupport.getDomainMasterConfiguration();
    CallbackHandler callbackHandler = Authentication.getCallbackHandler("slave", RIGHT_PASSWORD, "ManagementRealm");
    masterConfig.setCallbackHandler(callbackHandler);
    testSupport.start();
    domainMasterClient = testSupport.getDomainMasterLifecycleUtil().getDomainClient();
    domainSlaveClient = testSupport.getDomainSlaveLifecycleUtil().getDomainClient();
}
Also used : WildFlyManagedConfiguration(org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration) CallbackHandler(javax.security.auth.callback.CallbackHandler) BeforeClass(org.junit.BeforeClass)

Example 28 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project undertow by undertow-io.

the class KerberosKDCUtil method login.

static Subject login(final String userName, final char[] password) throws LoginException {
    Subject theSubject = new Subject();
    CallbackHandler cbh = new UsernamePasswordCBH(userName, password);
    LoginContext lc = new LoginContext("KDC", theSubject, cbh, createJaasConfiguration());
    lc.login();
    return theSubject;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) Subject(javax.security.auth.Subject)

Example 29 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler 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);
    try {
        handler.handle(new Callback[] { nameCallback, passwordCallback });
        Subject subject = new Subject();
        if (nameCallback.getName() != null) {
            subject.getPrincipals().add(new NamePrincipal(nameCallback.getName()));
        }
        // add the password as a private credential in the Subject.
        if (passwordCallback.getPassword() != null) {
            this.addPrivateCredential(subject, new PasswordCredential(nameCallback.getName(), passwordCallback.getPassword()));
        }
        return subject;
    } catch (IOException | UnsupportedCallbackException e) {
        throw new SecurityException(e);
    }
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) CallbackHandler(javax.security.auth.callback.CallbackHandler) NameCallback(javax.security.auth.callback.NameCallback) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(javax.resource.spi.security.PasswordCredential) PasswordCallback(javax.security.auth.callback.PasswordCallback) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Subject(javax.security.auth.Subject)

Example 30 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project wildfly by wildfly.

the class ElytronSASClientInterceptor method createInitialContextToken.

/**
     * Create an encoded {@link InitialContextToken} with an username/password pair obtained from an Elytron client configuration
     * matched by the specified {@link URI} and purpose.
     *
     * @param uri the target {@link URI}.
     * @param purpose a {@link String} representing the purpose of the configuration that will be used.
     * @param secMech a reference to the {@link CompoundSecMech} that was found in the {@link ClientRequestInfo}.
     * @return the encoded {@link InitialContextToken}, if a valid username is obtained from the matched configuration;
     *         an empty {@code byte[]} otherwise;
     * @throws Exception if an error occurs while building the encoded {@link InitialContextToken}.
     */
private byte[] createInitialContextToken(final URI uri, final String purpose, final CompoundSecMech secMech) throws Exception {
    AuthenticationContext authContext = this.authContext == null ? AuthenticationContext.captureCurrent() : this.authContext;
    // obtain the configuration that matches the URI and purpose.
    final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null, purpose);
    // get the callback handler from the configuration and use it to obtain a username/password pair.
    final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration);
    final NameCallback nameCallback = new NameCallback("Username: ");
    final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
    try {
        handler.handle(new Callback[] { nameCallback, passwordCallback });
    } catch (UnsupportedCallbackException e) {
        return NO_AUTHENTICATION_TOKEN;
    }
    // if the name callback contains a valid username we create the initial context token.
    if (nameCallback.getName() != null && !nameCallback.getName().equals(AnonymousPrincipal.getInstance().getName())) {
        byte[] encodedTargetName = secMech.as_context_mech.target_name;
        String name = nameCallback.getName();
        if (name.indexOf('@') < 0) {
            byte[] decodedTargetName = CSIv2Util.decodeGssExportedName(encodedTargetName);
            String targetName = new String(decodedTargetName, StandardCharsets.UTF_8);
            // "@default"
            name += "@" + targetName;
        }
        byte[] username = name.getBytes(StandardCharsets.UTF_8);
        byte[] password = {};
        if (passwordCallback.getPassword() != null)
            password = new String(passwordCallback.getPassword()).getBytes(StandardCharsets.UTF_8);
        // create the initial context token and ASN.1-encode it, as defined in RFC 2743.
        InitialContextToken authenticationToken = new InitialContextToken(username, password, encodedTargetName);
        return CSIv2Util.encodeInitialContextToken(authenticationToken, codec);
    }
    return NO_AUTHENTICATION_TOKEN;
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) CallbackHandler(javax.security.auth.callback.CallbackHandler) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) NameCallback(javax.security.auth.callback.NameCallback) InitialContextToken(org.omg.GSSUP.InitialContextToken) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Aggregations

CallbackHandler (javax.security.auth.callback.CallbackHandler)89 IOException (java.io.IOException)38 Callback (javax.security.auth.callback.Callback)36 PasswordCallback (javax.security.auth.callback.PasswordCallback)30 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)27 HashMap (java.util.HashMap)25 Subject (javax.security.auth.Subject)24 NameCallback (javax.security.auth.callback.NameCallback)22 LoginContext (javax.security.auth.login.LoginContext)17 LoginException (javax.security.auth.login.LoginException)15 Test (org.junit.Test)15 Map (java.util.Map)10 URL (java.net.URL)8 RealmCallback (javax.security.sasl.RealmCallback)7 QName (javax.xml.namespace.QName)6 Service (javax.xml.ws.Service)6 WSS4JOutInterceptor (org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor)6 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)5 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)5 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)5