Search in sources :

Example 51 with RolePrincipal

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

the class SyncopeBackingEngine method listRolesSyncope2.

private List<RolePrincipal> listRolesSyncope2(Principal principal) {
    List<RolePrincipal> result = new ArrayList<>();
    HttpGet request = new HttpGet(address + "/users/" + principal.getName());
    request.setHeader("Content-Type", "application/json");
    try {
        HttpResponse httpResponse = client.execute(request);
        String response = EntityUtils.toString(httpResponse.getEntity());
        if (response != null && !response.isEmpty()) {
            JSONParser parser = new JSONParser(response);
            List<String> roles = (List<String>) parser.getParsed().get("roles");
            for (String role : roles) {
                result.add(new RolePrincipal(role));
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error listing roles", e);
    }
    return result;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) JSONParser(org.apache.felix.utils.json.JSONParser) ArrayList(java.util.ArrayList) List(java.util.List) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 52 with RolePrincipal

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

the class LDAPLoginModule method doLogin.

protected boolean doLogin() 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 = Util.doRFC2254Encoding(((NameCallback) callbacks[0]).getName());
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // If either a username or password is specified don't allow authentication = "none".
    // This is to prevent someone from logging into Karaf as any user without providing a
    // valid password (because if authentication = none, the password could be any
    // value - it is ignored).
    LDAPOptions options = new LDAPOptions(this.options);
    if (options.isUsernameTrim()) {
        if (user != null) {
            user = user.trim();
        }
    }
    String authentication = options.getAuthentication();
    if ("none".equals(authentication) && (user != null || tmpPassword != null)) {
        logger.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        authentication = "simple";
        Map<String, Object> opts = new HashMap<>(this.options);
        opts.put(LDAPOptions.AUTHENTICATION, authentication);
        options = new LDAPOptions(opts);
    }
    boolean allowEmptyPasswords = options.getAllowEmptyPasswords();
    if (!"none".equals(authentication) && !allowEmptyPasswords && (tmpPassword == null || tmpPassword.length == 0)) {
        throw new LoginException("Empty passwords not allowed");
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    principals = new HashSet<>();
    LDAPCache cache = LDAPCache.getCache(options);
    // step 1: get the user DN
    final String[] userDnAndNamespace;
    try {
        logger.debug("Get the user DN.");
        userDnAndNamespace = cache.getUserDnAndNamespace(user);
        if (userDnAndNamespace == null) {
            return false;
        }
    } catch (Exception e) {
        logger.warn("Can't connect to the LDAP server: {}", e.getMessage(), e);
        throw new LoginException("Can't connect to the LDAP server: " + e.getMessage());
    }
    // step 2: bind the user using the DN
    DirContext context = null;
    try {
        // switch the credentials to the Karaf login user so that we can verify his password is correct
        logger.debug("Bind user (authentication).");
        Hashtable<String, Object> env = options.getEnv();
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
        logger.debug("Set the security principal for " + userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_PRINCIPAL, userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_CREDENTIALS, password);
        logger.debug("Binding the user.");
        context = new InitialDirContext(env);
        logger.debug("User " + user + " successfully bound.");
        context.close();
    } catch (Exception e) {
        logger.warn("User " + user + " authentication failed.", e);
        throw new LoginException("Authentication failed: " + e.getMessage());
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (Exception e) {
            // ignore
            }
        }
    }
    principals.add(new UserPrincipal(user));
    // step 3: retrieving user roles
    try {
        String[] roles = cache.getUserRoles(user, userDnAndNamespace[0], userDnAndNamespace[1]);
        for (String role : roles) {
            principals.add(new RolePrincipal(role));
        }
    } catch (Exception e) {
        throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
    }
    return true;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) 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) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 53 with RolePrincipal

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

the class KarafJaasAuthenticator method assertRolePresent.

private void assertRolePresent(Subject subject) throws FailedLoginException {
    boolean hasCorrectRole = role == null || role.isEmpty();
    int roleCount = 0;
    for (Principal principal : subject.getPrincipals()) {
        if (principal instanceof RolePrincipal) {
            if (!hasCorrectRole) {
                hasCorrectRole = role.equals(principal.getName());
            }
            roleCount++;
        }
    }
    if (roleCount == 0) {
        throw new FailedLoginException("User doesn't have role defined");
    }
    if (!hasCorrectRole) {
        throw new FailedLoginException("User doesn't have the required role " + role);
    }
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) ClientPrincipal(org.apache.karaf.jaas.boot.principal.ClientPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal)

Example 54 with RolePrincipal

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

the class GuardProxyCatalogTest method testInvocationBlocking1.

@SuppressWarnings("unchecked")
@Test
public void testInvocationBlocking1() throws Exception {
    Dictionary<String, Object> c1 = new Hashtable<>();
    c1.put(Constants.SERVICE_PID, "foobar");
    c1.put("service.guard", "(objectClass=" + TestServiceAPI.class.getName() + ")");
    c1.put("doit", "a,b");
    Dictionary<String, Object> c2 = new Hashtable<>();
    c2.put(Constants.SERVICE_PID, "barfoobar");
    c2.put("service.guard", "(objectClass=" + TestObjectWithoutInterface.class.getName() + ")");
    c2.put("compute", "c");
    BundleContext bc = mockConfigAdminBundleContext(c1, c2);
    final Object proxy = testCreateProxy(bc, new Class[] { TestServiceAPI.class, TestObjectWithoutInterface.class }, new CombinedTestService());
    // Run with the right credentials so we can test the expected roles
    Subject subject = new Subject();
    subject.getPrincipals().add(new RolePrincipal("b"));
    Subject.doAs(subject, (PrivilegedAction<Object>) () -> {
        assertEquals("Doing it", ((TestServiceAPI) proxy).doit());
        if (!runningUnderCoverage) {
            try {
                ((TestObjectWithoutInterface) proxy).compute(44L);
                fail("Should have been blocked");
            } catch (SecurityException se) {
            // good
            }
        }
        return null;
    });
}
Also used : Hashtable(java.util.Hashtable) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 55 with RolePrincipal

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

the class GuardProxyCatalogTest method testInvocationBlocking2.

@SuppressWarnings("unchecked")
@Test
public void testInvocationBlocking2() throws Exception {
    Dictionary<String, Object> config = new Hashtable<>();
    config.put(Constants.SERVICE_PID, "barfoobar");
    config.put("service.guard", "(objectClass=" + TestObjectWithoutInterface.class.getName() + ")");
    config.put("compute(long)[\"42\"]", "b");
    config.put("compute(long)", "c");
    BundleContext bc = mockConfigAdminBundleContext(config);
    final Object proxy = testCreateProxy(bc, new Class[] { TestServiceAPI.class, TestObjectWithoutInterface.class }, new CombinedTestService());
    // Run with the right credentials so we can test the expected roles
    Subject subject = new Subject();
    subject.getPrincipals().add(new RolePrincipal("b"));
    Subject.doAs(subject, (PrivilegedAction<Object>) () -> {
        if (!runningUnderCoverage) {
            assertEquals(-42L, ((TestObjectWithoutInterface) proxy).compute(42L));
            try {
                ((TestObjectWithoutInterface) proxy).compute(44L);
                fail("Should have been blocked");
            } catch (SecurityException se) {
            // good
            }
        }
        return null;
    });
}
Also used : Hashtable(java.util.Hashtable) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

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