Search in sources :

Example 26 with RolePrincipal

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

the class JdbcLoginModuleTest method testEngine.

@Test
public void testEngine() throws Exception {
    UserPrincipal user = new UserPrincipal("abc");
    GroupPrincipal group1 = new GroupPrincipal("group1");
    RolePrincipal role1 = new RolePrincipal("role1");
    RolePrincipal role2 = new RolePrincipal("role2");
    RolePrincipal role3 = new RolePrincipal("role3");
    JDBCBackingEngine engine = new JDBCBackingEngine(dataSource);
    assertTrue(engine.listUsers().isEmpty());
    engine.addUser("abc", "xyz");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).isEmpty());
    assertTrue(engine.listRoles(group1).isEmpty());
    assertTrue(engine.listGroups(user).isEmpty());
    assertNotNull(engine.lookupUser("abc"));
    assertEquals("abc", engine.lookupUser("abc").getName());
    engine.addRole("abc", "role1");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).contains(role1));
    assertTrue(engine.listRoles(group1).isEmpty());
    assertTrue(engine.listGroups(user).isEmpty());
    engine.addGroupRole("group1", "role2");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).contains(role1));
    assertTrue(engine.listRoles(group1).contains(role2));
    assertTrue(engine.listGroups(user).isEmpty());
    engine.addGroup("abc", "group1");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).contains(role1));
    assertTrue(engine.listRoles(user).contains(role2));
    assertTrue(engine.listRoles(group1).contains(role2));
    assertTrue(engine.listGroups(user).contains(group1));
    engine.deleteRole("abc", "role1");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).contains(role2));
    assertTrue(engine.listRoles(group1).contains(role2));
    assertTrue(engine.listGroups(user).contains(group1));
    engine.deleteGroupRole("group1", "role2");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).isEmpty());
    assertTrue(engine.listRoles(group1).isEmpty());
    assertTrue(engine.listGroups(user).contains(group1));
    engine.addGroupRole("group1", "role3");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).contains(role3));
    assertTrue(engine.listRoles(group1).contains(role3));
    assertTrue(engine.listGroups(user).contains(group1));
    engine.deleteGroup("abc", "group1");
    assertTrue(engine.listUsers().contains(user));
    assertTrue(engine.listRoles(user).isEmpty());
    assertTrue(engine.listRoles(group1).isEmpty());
    assertTrue(engine.listGroups(user).isEmpty());
    engine.deleteUser("abc");
    assertTrue(engine.listUsers().isEmpty());
    assertTrue(engine.listRoles(user).isEmpty());
    assertTrue(engine.listRoles(group1).isEmpty());
    assertTrue(engine.listGroups(user).isEmpty());
}
Also used : GroupPrincipal(org.apache.karaf.jaas.boot.principal.GroupPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) Test(org.junit.Test)

Example 27 with RolePrincipal

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

the class GSSAPILdapLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    // force GSSAPI for login
    Map<String, Object> opts = new HashMap<>(this.options);
    opts.put(LDAPOptions.AUTHENTICATION, "GSSAPI");
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        LDAPOptions lOptions = new LDAPOptions(opts);
        NameCallback[] callbacks = new NameCallback[1];
        callbacks[0] = new NameCallback("Username: ");
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException ioException) {
            logger.error("error with callback handler", ioException);
            throw new LoginException(ioException.getMessage());
        } catch (UnsupportedCallbackException unsupportedCallbackException) {
            logger.error("error with callback handler", unsupportedCallbackException);
            throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
        }
        user = callbacks[0].getName();
        principals = new HashSet<>();
        String[] userDnAndNamespace;
        try (LDAPCache cache = LDAPCache.getCache(lOptions)) {
            try {
                logger.debug("Get the user DN.");
                userDnAndNamespace = cache.getUserDnAndNamespace(user);
            } 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());
            }
            if (userDnAndNamespace == null) {
                return false;
            }
            principals.add(new UserPrincipal(user));
            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;
        }
    } finally {
        ManagedSSLSocketFactory.setSocketFactory(null);
        Thread.currentThread().setContextClassLoader(tccl);
    }
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) PrivilegedActionException(java.security.PrivilegedActionException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 28 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project fabric8 by jboss-fuse.

the class ZookeeperLoginModule method login.

@Override
public boolean login() throws LoginException {
    boolean result;
    String user = null;
    try {
        Callback[] callbacks = new Callback[2];
        callbacks[0] = new NameCallback("Username: ");
        callbacks[1] = new PasswordCallback("Password: ", false);
        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 = ((NameCallback) callbacks[0]).getName();
        if (user == null)
            throw new FailedLoginException("user name is null");
        if (user.startsWith(BackingEngine.GROUP_PREFIX)) {
            throw new IllegalArgumentException("Prefix not permitted in user names: " + BackingEngine.GROUP_PREFIX);
        }
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            tmpPassword = new char[0];
        }
        if (debug)
            LOG.debug("Login [" + this + "] - user=" + user + ",users=" + users);
        if (isContainerLogin(user)) {
            String token = containers.getProperty(user);
            if (token == null) {
                // force reload cache of container tokens
                CuratorFramework curator = CuratorFrameworkLocator.getCuratorFramework();
                if (curator != null) {
                    try {
                        getCachedContainerTokens(curator, true);
                        token = containers.getProperty(user);
                    } catch (Exception e) {
                        LOG.warn(e.getMessage());
                    }
                }
                // didn't help
                if (token == null) {
                    throw new FailedLoginException("Container doesn't exist");
                }
            }
            // the password is in the first position
            if (!new String(tmpPassword).equals(token)) {
                // force reload cache of container tokens
                CuratorFramework curator = CuratorFrameworkLocator.getCuratorFramework();
                if (curator != null) {
                    try {
                        getCachedContainerTokens(curator, true);
                        token = containers.getProperty(user);
                    } catch (Exception e) {
                        LOG.warn(e.getMessage());
                    }
                }
                // didn't help
                if (!new String(tmpPassword).equals(token)) {
                    throw new FailedLoginException("Tokens do not match");
                }
            }
            principals = new HashSet<Principal>();
            principals.add(new UserPrincipal(user));
            principals.add(new RolePrincipal("container"));
            principals.add(new RolePrincipal("admin"));
            subject.getPrivateCredentials().add(new String(tmpPassword));
            result = true;
        } else {
            String userInfos = users.getProperty(user);
            if (userInfos == null) {
                // force reload cache of user tokens
                CuratorFramework curator = CuratorFrameworkLocator.getCuratorFramework();
                if (curator != null) {
                    try {
                        getCachedUsers(curator, path, true);
                        userInfos = users.getProperty(user);
                    } catch (Exception e) {
                        LOG.warn(e.getMessage());
                    }
                }
                // didn't help
                if (userInfos == null) {
                    throw new FailedLoginException("User doesn't exist");
                }
            }
            // the password is in the first position
            String[] infos = userInfos.split(",");
            String password = infos[0];
            if (!checkPassword(new String(tmpPassword), password)) {
                // force reload cache of user tokens
                CuratorFramework curator = CuratorFrameworkLocator.getCuratorFramework();
                if (curator != null) {
                    try {
                        getCachedUsers(curator, path, true);
                        userInfos = users.getProperty(user);
                    } catch (Exception e) {
                        LOG.warn(e.getMessage());
                    }
                }
                // didn't help
                if (userInfos == null) {
                    throw new FailedLoginException("User doesn't exist");
                }
                infos = userInfos.split(",");
                password = infos[0];
                if (!checkPassword(new String(tmpPassword), password)) {
                    throw new FailedLoginException("Password does not match");
                }
            }
            principals = new HashSet<Principal>();
            principals.add(new UserPrincipal(user));
            for (int i = 1; i < infos.length; i++) {
                if (infos[i].trim().startsWith(BackingEngine.GROUP_PREFIX)) {
                    // it's a group reference
                    principals.add(new GroupPrincipal(infos[i].trim().substring(BackingEngine.GROUP_PREFIX.length())));
                    String groupInfo = (String) 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()));
                }
            }
            subject.getPrivateCredentials().add(new String(tmpPassword));
            result = true;
        }
    } catch (LoginException ex) {
        if (debug) {
            LOG.debug("Login failed {}", user, ex);
        }
        throw ex;
    }
    if (debug) {
        LOG.debug("Successfully logged in {}", user);
    }
    return result;
}
Also used : IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) FailedLoginException(javax.security.auth.login.FailedLoginException) IOException(java.io.IOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) CuratorFramework(org.apache.curator.framework.CuratorFramework) 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) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal)

Example 29 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project fabric8 by jboss-fuse.

the class FabricKarafTestSupport method executeCommands.

/**
 * Executes a shell command and returns output as a String.
 * Commands have a default timeout of 10 seconds.
 * @param timeout The amount of time in millis to wait for the command to execute.
 * @param silent  Specifies if the command should be displayed in the screen.
 * @param commands The command to execute.
 */
public static String executeCommands(final long timeout, final boolean silent, final Set<RolePrincipal> roles, final String... commands) {
    String response = null;
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final PrintStream printStream = new PrintStream(byteArrayOutputStream);
    final CommandProcessor commandProcessor = ServiceLocator.awaitService(FrameworkUtil.getBundle(FabricKarafTestSupport.class).getBundleContext(), CommandProcessor.class);
    final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, printStream);
    commandSession.put("APPLICATION", System.getProperty("runtime.id", "root"));
    commandSession.put("USER", "karaf");
    FutureTask<String> commandFuture = new FutureTask<String>(new Callable<String>() {

        public String call() throws Exception {
            Subject subject = new Subject();
            subject.getPrincipals().add(new UserPrincipal("admin"));
            subject.getPrincipals().add(new RolePrincipal("admin"));
            subject.getPrincipals().add(new RolePrincipal("manager"));
            subject.getPrincipals().add(new RolePrincipal("viewer"));
            if (roles != null) {
                for (RolePrincipal role : roles) {
                    subject.getPrincipals().add(role);
                }
            }
            return Subject.doAs(subject, new PrivilegedAction<String>() {

                @Override
                public String run() {
                    for (String command : commands) {
                        boolean keepRunning = true;
                        if (!silent) {
                            System.out.println(command);
                            System.out.flush();
                        }
                        LOGGER.info("Executing command: " + command);
                        while (!Thread.currentThread().isInterrupted() && keepRunning) {
                            try {
                                commandSession.execute(command);
                                keepRunning = false;
                            } catch (Exception e) {
                                if (retryException(e)) {
                                    keepRunning = true;
                                    sleep(1000);
                                } else {
                                    throw new CommandExecutionException(e);
                                }
                            }
                        }
                    }
                    printStream.flush();
                    return byteArrayOutputStream.toString();
                }
            });
        }
    });
    try {
        executor.submit(commandFuture);
        response = commandFuture.get(timeout, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw CommandExecutionException.launderThrowable(e.getCause());
    } catch (Exception e) {
        throw CommandExecutionException.launderThrowable(e);
    }
    return response;
}
Also used : PrintStream(java.io.PrintStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ExecutionException(java.util.concurrent.ExecutionException) Subject(javax.security.auth.Subject) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) CommandSession(org.apache.felix.service.command.CommandSession) FutureTask(java.util.concurrent.FutureTask) PrivilegedAction(java.security.PrivilegedAction) CommandProcessor(org.apache.felix.service.command.CommandProcessor) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) ExecutionException(java.util.concurrent.ExecutionException)

Example 30 with RolePrincipal

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

the class FuseKarafTestSupport method execute.

protected Object execute(Session session, String command) throws PrivilegedActionException {
    Subject subject = new Subject();
    subject.getPrincipals().add(new RolePrincipal("admin"));
    return Subject.doAs(subject, (PrivilegedExceptionAction<String>) () -> (String) session.execute(command));
}
Also used : RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject)

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