Search in sources :

Example 16 with UserAccount

use of com.cloud.user.UserAccount in project cloudstack by apache.

the class AuthorizeSAMLSSOCmd method execute.

@Override
public void execute() {
    // Check permissions
    UserAccount userAccount = _accountService.getUserAccountById(getId());
    if (userAccount == null) {
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, "Unable to find a user account with the given ID");
    }
    Domain domain = _domainService.getDomain(userAccount.getDomainId());
    Account account = _accountService.getAccount(userAccount.getAccountId());
    _accountService.checkAccess(CallContext.current().getCallingAccount(), domain);
    _accountService.checkAccess(CallContext.current().getCallingAccount(), SecurityChecker.AccessType.OperateEntry, true, account);
    CallContext.current().setEventDetails("UserId: " + getId());
    SuccessResponse response = new SuccessResponse();
    Boolean status = false;
    if (_samlAuthManager.authorizeUser(getId(), getEntityId(), getEnable())) {
        status = true;
    }
    response.setResponseName(getCommandName());
    response.setSuccess(status);
    setResponseObject(response);
}
Also used : Account(com.cloud.user.Account) UserAccount(com.cloud.user.UserAccount) SuccessResponse(org.apache.cloudstack.api.response.SuccessResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) Domain(com.cloud.domain.Domain) UserAccount(com.cloud.user.UserAccount)

Example 17 with UserAccount

use of com.cloud.user.UserAccount in project cloudstack by apache.

the class ListAndSwitchSAMLAccountCmd method authenticate.

@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    if (session == null || session.isNew()) {
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, _apiServer.getSerializedApiError(ApiErrorCode.UNAUTHORIZED.getHttpCode(), "Only authenticated saml users can request this API", params, responseType));
    }
    if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) {
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, _apiServer.getSerializedApiError(ApiErrorCode.UNAUTHORIZED.getHttpCode(), "Unauthorized session, please re-login", params, responseType));
    }
    final long currentUserId = (Long) session.getAttribute("userid");
    final UserAccount currentUserAccount = _accountService.getUserAccountById(currentUserId);
    if (currentUserAccount == null || currentUserAccount.getSource() != User.Source.SAML2) {
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Only authenticated saml users can request this API", params, responseType));
    }
    String userUuid = null;
    String domainUuid = null;
    if (params.containsKey(ApiConstants.USER_ID)) {
        userUuid = ((String[]) params.get(ApiConstants.USER_ID))[0];
    }
    if (params.containsKey(ApiConstants.DOMAIN_ID)) {
        domainUuid = ((String[]) params.get(ApiConstants.DOMAIN_ID))[0];
    }
    if (userUuid != null && domainUuid != null) {
        final User user = _userDao.findByUuid(userUuid);
        final Domain domain = _domainDao.findByUuid(domainUuid);
        final UserAccount nextUserAccount = _accountService.getUserAccountById(user.getId());
        if (nextUserAccount != null && !nextUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
            throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "The requested user account is locked and cannot be switched to, please contact your administrator.", params, responseType));
        }
        if (nextUserAccount == null || !nextUserAccount.getAccountState().equals(Account.State.enabled.toString()) || !nextUserAccount.getUsername().equals(currentUserAccount.getUsername()) || !nextUserAccount.getExternalEntity().equals(currentUserAccount.getExternalEntity()) || (nextUserAccount.getDomainId() != domain.getId()) || (nextUserAccount.getSource() != User.Source.SAML2)) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "User account is not allowed to switch to the requested account", params, responseType));
        }
        try {
            if (_apiServer.verifyUser(nextUserAccount.getId())) {
                final LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, nextUserAccount.getUsername(), nextUserAccount.getUsername() + nextUserAccount.getSource().toString(), nextUserAccount.getDomainId(), null, remoteAddress, params);
                SAMLUtils.setupSamlUserCookies(loginResponse, resp);
                resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
                return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
            }
        } catch (CloudAuthenticationException | IOException exception) {
            s_logger.debug("Failed to switch to request SAML user account due to: " + exception.getMessage());
        }
    } else {
        List<UserAccountVO> switchableAccounts = _userAccountDao.getAllUsersByNameAndEntity(currentUserAccount.getUsername(), currentUserAccount.getExternalEntity());
        if (switchableAccounts != null && switchableAccounts.size() > 0 && currentUserId != User.UID_SYSTEM) {
            List<SamlUserAccountResponse> accountResponses = new ArrayList<SamlUserAccountResponse>();
            for (UserAccountVO userAccount : switchableAccounts) {
                User user = _userDao.getUser(userAccount.getId());
                Domain domain = _domainService.getDomain(userAccount.getDomainId());
                SamlUserAccountResponse accountResponse = new SamlUserAccountResponse();
                accountResponse.setUserId(user.getUuid());
                accountResponse.setUserName(user.getUsername());
                accountResponse.setDomainId(domain.getUuid());
                accountResponse.setDomainName(domain.getName());
                accountResponse.setAccountName(userAccount.getAccountName());
                accountResponse.setIdpId(user.getExternalEntity());
                accountResponses.add(accountResponse);
            }
            ListResponse<SamlUserAccountResponse> response = new ListResponse<SamlUserAccountResponse>();
            response.setResponses(accountResponses);
            response.setResponseName(getCommandName());
            return ApiResponseSerializer.toSerializedString(response, responseType);
        }
    }
    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Unable to switch to requested SAML account. Please make sure your user/account is enabled. Please contact your administrator.", params, responseType));
}
Also used : User(com.cloud.user.User) ListResponse(org.apache.cloudstack.api.response.ListResponse) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) SamlUserAccountResponse(org.apache.cloudstack.api.response.SamlUserAccountResponse) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UserAccountVO(com.cloud.user.UserAccountVO) ServerApiException(org.apache.cloudstack.api.ServerApiException) Domain(com.cloud.domain.Domain) UserAccount(com.cloud.user.UserAccount) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse)

Example 18 with UserAccount

use of com.cloud.user.UserAccount in project cloudstack by apache.

the class PBKDF2UserAuthenticator method authenticate.

@Override
public Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> authenticate(String username, String password, Long domainId, Map<String, Object[]> requestParameters) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Retrieving user: " + username);
    }
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        s_logger.debug("Username or Password cannot be empty");
        return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
    }
    boolean isValidUser = false;
    UserAccount user = this._userAccountDao.getUserAccount(username, domainId);
    if (user != null) {
        isValidUser = true;
    } else {
        s_logger.debug("Unable to find user with " + username + " in domain " + domainId);
    }
    byte[] salt = new byte[0];
    int rounds = s_rounds;
    try {
        if (isValidUser) {
            String[] storedPassword = user.getPassword().split(":");
            if ((storedPassword.length != 3) || (!StringUtils.isNumeric(storedPassword[2]))) {
                s_logger.warn("The stored password for " + username + " isn't in the right format for this authenticator");
                isValidUser = false;
            } else {
                // Encoding format = <salt>:<password hash>:<rounds>
                salt = decode(storedPassword[0]);
                rounds = Integer.parseInt(storedPassword[2]);
            }
        }
        boolean result = false;
        if (isValidUser && validateCredentials(password, salt)) {
            result = ConstantTimeComparator.compareStrings(user.getPassword(), encode(password, salt, rounds));
        }
        UserAuthenticator.ActionOnFailedAuthentication action = null;
        if ((!result) && (isValidUser)) {
            action = UserAuthenticator.ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT;
        }
        return new Pair(Boolean.valueOf(result), action);
    } catch (NumberFormatException e) {
        throw new CloudRuntimeException("Unable to hash password", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CloudRuntimeException("Unable to hash password", e);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable to hash password", e);
    } catch (InvalidKeySpecException e) {
        throw new CloudRuntimeException("Unable to hash password", e);
    }
}
Also used : UserAuthenticator(com.cloud.server.auth.UserAuthenticator) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) UserAccount(com.cloud.user.UserAccount) Pair(com.cloud.utils.Pair)

Example 19 with UserAccount

use of com.cloud.user.UserAccount in project cloudstack by apache.

the class LinkDomainToLdapCmd method execute.

@Override
public void execute() throws ServerApiException {
    try {
        LinkDomainToLdapResponse response = _ldapManager.linkDomainToLdap(domainId, type, name, accountType);
        if (admin != null) {
            LdapUser ldapUser = null;
            try {
                ldapUser = _ldapManager.getUser(admin, type, name);
            } catch (NoLdapUserMatchingQueryException e) {
                s_logger.debug("no ldap user matching username " + admin + " in the given group/ou", e);
            }
            if (ldapUser != null && !ldapUser.isDisabled()) {
                Account account = _accountService.getActiveAccountByName(admin, domainId);
                if (account == null) {
                    try {
                        UserAccount userAccount = _accountService.createUserAccount(admin, "", ldapUser.getFirstname(), ldapUser.getLastname(), ldapUser.getEmail(), null, admin, Account.ACCOUNT_TYPE_DOMAIN_ADMIN, RoleType.DomainAdmin.getId(), domainId, null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP);
                        response.setAdminId(String.valueOf(userAccount.getAccountId()));
                        s_logger.info("created an account with name " + admin + " in the given domain " + domainId);
                    } catch (Exception e) {
                        s_logger.info("an exception occurred while creating account with name " + admin + " in domain " + domainId, e);
                    }
                } else {
                    s_logger.debug("an account with name " + admin + " already exists in the domain " + domainId);
                }
            } else {
                s_logger.debug("ldap user with username " + admin + " is disabled in the given group/ou");
            }
        }
        response.setObjectName("LinkDomainToLdap");
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } catch (final InvalidParameterValueException e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString());
    }
}
Also used : Account(com.cloud.user.Account) UserAccount(com.cloud.user.UserAccount) NoLdapUserMatchingQueryException(org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException) LdapUser(org.apache.cloudstack.ldap.LdapUser) LinkDomainToLdapResponse(org.apache.cloudstack.api.response.LinkDomainToLdapResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) UserAccount(com.cloud.user.UserAccount) ServerApiException(org.apache.cloudstack.api.ServerApiException) NoLdapUserMatchingQueryException(org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException)

Example 20 with UserAccount

use of com.cloud.user.UserAccount in project cloudstack by apache.

the class LdapAuthenticator method authenticate.

@Override
public Pair<Boolean, ActionOnFailedAuthentication> authenticate(final String username, final String password, final Long domainId, final Map<String, Object[]> requestParameters) {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        s_logger.debug("Username or Password cannot be empty");
        return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
    }
    boolean result = false;
    ActionOnFailedAuthentication action = null;
    if (_ldapManager.isLdapEnabled()) {
        final UserAccount user = _userAccountDao.getUserAccount(username, domainId);
        LdapTrustMapVO ldapTrustMapVO = _ldapManager.getDomainLinkedToLdap(domainId);
        if (ldapTrustMapVO != null) {
            try {
                LdapUser ldapUser = _ldapManager.getUser(username, ldapTrustMapVO.getType().toString(), ldapTrustMapVO.getName());
                if (!ldapUser.isDisabled()) {
                    result = _ldapManager.canAuthenticate(ldapUser.getPrincipal(), password);
                    if (result) {
                        if (user == null) {
                            // import user to cloudstack
                            createCloudStackUserAccount(ldapUser, domainId, ldapTrustMapVO.getAccountType());
                        } else {
                            enableUserInCloudStack(user);
                        }
                    }
                } else {
                    //disable user in cloudstack
                    disableUserInCloudStack(user);
                }
            } catch (NoLdapUserMatchingQueryException e) {
                s_logger.debug(e.getMessage());
            }
        } else {
            //domain is not linked to ldap follow normal authentication
            if (user != null) {
                try {
                    LdapUser ldapUser = _ldapManager.getUser(username);
                    if (!ldapUser.isDisabled()) {
                        result = _ldapManager.canAuthenticate(ldapUser.getPrincipal(), password);
                    } else {
                        s_logger.debug("user with principal " + ldapUser.getPrincipal() + " is disabled in ldap");
                    }
                } catch (NoLdapUserMatchingQueryException e) {
                    s_logger.debug(e.getMessage());
                }
            }
        }
        if (!result && user != null) {
            action = ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT;
        }
    }
    return new Pair<Boolean, ActionOnFailedAuthentication>(result, action);
}
Also used : UserAccount(com.cloud.user.UserAccount) Pair(com.cloud.utils.Pair)

Aggregations

UserAccount (com.cloud.user.UserAccount)23 ServerApiException (org.apache.cloudstack.api.ServerApiException)11 ServerApiException (com.cloud.api.ServerApiException)5 UserResponse (com.cloud.api.response.UserResponse)5 UserResponse (org.apache.cloudstack.api.response.UserResponse)5 Domain (com.cloud.domain.Domain)4 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)4 Account (com.cloud.user.Account)4 Pair (com.cloud.utils.Pair)3 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)2 UserAccountVO (com.cloud.user.UserAccountVO)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 ArrayList (java.util.ArrayList)2 AccountResponse (org.apache.cloudstack.api.response.AccountResponse)2 LoginCmdResponse (org.apache.cloudstack.api.response.LoginCmdResponse)2 LdapUser (org.apache.cloudstack.ldap.LdapUser)2 NoLdapUserMatchingQueryException (org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException)2