Search in sources :

Example 21 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.

the class GSSAPILdapLoginModuleTest method testSuccess.

@Test
public void testSuccess() throws Exception {
    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();
    Subject subject = new Subject();
    module.initialize(subject, new NamePasswordCallbackHandler("hnelson", "secret"), null, options);
    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());
    assertEquals(3, subject.getPrincipals().size());
    boolean foundKrb5User = false;
    boolean foundUser = false;
    boolean foundRole = false;
    boolean foundTicket = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundKrb5User = true;
        } else if (pr instanceof UserPrincipal) {
            assertEquals("hnelson", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    for (Object crd : subject.getPrivateCredentials()) {
        if (crd instanceof KerberosTicket) {
            assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
            assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
            foundTicket = true;
            break;
        }
    }
    assertTrue("Principals should contains kerberos user", foundKrb5User);
    assertTrue("Principals should contains ldap user", foundUser);
    assertTrue("Principals should contains ldap role", foundRole);
    assertTrue("PricatePrincipals should contains kerberos ticket", foundTicket);
    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) NamePasswordCallbackHandler(org.apache.karaf.jaas.modules.NamePasswordCallbackHandler) Properties(org.apache.felix.utils.properties.Properties) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) KarafKerberosITest(org.apache.karaf.jaas.modules.krb5.KarafKerberosITest) Test(org.junit.Test)

Example 22 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal 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 23 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.

the class PropertiesLoginModule 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];
    // 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 : IOException(java.io.IOException) Properties(org.apache.felix.utils.properties.Properties) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) 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 24 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.

the class SyncopeBackingEngine method listRolesSyncope1.

private List<RolePrincipal> listRolesSyncope1(Principal principal) {
    List<RolePrincipal> roles = new ArrayList<>();
    HttpGet request = new HttpGet(address + "/users?username=" + principal.getName());
    request.setHeader("Content-Type", "application/xml");
    try {
        HttpResponse response = client.execute(request);
        String responseTO = EntityUtils.toString(response.getEntity());
        if (responseTO != null && !responseTO.isEmpty()) {
            int index = responseTO.indexOf("<roleName>");
            while (index != 1) {
                responseTO = responseTO.substring(index + "<roleName>".length());
                int end = responseTO.indexOf("</roleName>");
                if (end == -1) {
                    index = -1;
                    break;
                }
                String role = responseTO.substring(0, end);
                roles.add(new RolePrincipal(role));
                responseTO = responseTO.substring(end + "</roleName>".length());
                index = responseTO.indexOf("<roleName>");
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error listing roles", e);
    }
    return roles;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 25 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.

the class SyncopeLoginModule method login.

public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    principals = new HashSet<>();
    // authenticate the user on Syncope
    LOGGER.debug("Authenticate user {} on Syncope located {}", user, address);
    DefaultHttpClient client = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials(user, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    HttpGet get = new HttpGet(address + "/users/self");
    boolean version2 = version != null && (version.equals("2.x") || version.equals("2"));
    if (version2) {
        get.setHeader("Content-Type", "application/json");
    } else {
        get.setHeader("Content-Type", "application/xml");
    }
    List<String> roles = new ArrayList<>();
    try {
        CloseableHttpResponse response = client.execute(get);
        LOGGER.debug("Syncope HTTP response status code: {}", response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            LOGGER.warn("User {} not authenticated", user);
            return false;
        }
        LOGGER.debug("User {} authenticated", user);
        LOGGER.debug("Populating principals with user");
        principals.add(new UserPrincipal(user));
        LOGGER.debug("Retrieving user {} roles", user);
        String responseSt = EntityUtils.toString(response.getEntity());
        if (version2) {
            roles = extractingRolesSyncope2(responseSt);
        } else {
            roles = extractingRolesSyncope1(responseSt);
        }
    } catch (Exception e) {
        LOGGER.error("User {} authentication failed", user, e);
        throw new LoginException("User " + user + " authentication failed: " + e.getMessage());
    }
    LOGGER.debug("Populating principals with roles");
    for (String role : roles) {
        principals.add(new RolePrincipal(role));
    }
    return true;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) LoginException(javax.security.auth.login.LoginException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LoginException(javax.security.auth.login.LoginException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Credentials(org.apache.http.auth.Credentials)

Aggregations

RolePrincipal (org.apache.karaf.jaas.boot.principal.RolePrincipal)61 UserPrincipal (org.apache.karaf.jaas.boot.principal.UserPrincipal)20 Subject (javax.security.auth.Subject)19 Principal (java.security.Principal)15 Test (org.junit.Test)15 LoginException (javax.security.auth.login.LoginException)14 IOException (java.io.IOException)13 NameCallback (javax.security.auth.callback.NameCallback)13 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)13 ArrayList (java.util.ArrayList)12 Callback (javax.security.auth.callback.Callback)11 PasswordCallback (javax.security.auth.callback.PasswordCallback)10 FailedLoginException (javax.security.auth.login.FailedLoginException)10 GroupPrincipal (org.apache.karaf.jaas.boot.principal.GroupPrincipal)9 BundleContext (org.osgi.framework.BundleContext)8 Hashtable (java.util.Hashtable)7 HashSet (java.util.HashSet)6 File (java.io.File)4 Configuration (org.osgi.service.cm.Configuration)4 Attribute (ddf.security.assertion.Attribute)3