Search in sources :

Example 1 with ConnectionEnvironment

use of com.evolveum.midpoint.security.api.ConnectionEnvironment in project midpoint by Evolveum.

the class WsFaultListener method faultOccurred.

@Override
public boolean faultOccurred(Exception exception, String description, Message message) {
    LOGGER.trace("Handling fault: {}: {} - {}", new Object[] { exception, description, message, exception });
    Object audited = message.getContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME);
    if (audited != null && ((Boolean) audited)) {
        return true;
    }
    if (exception instanceof PasswordCallbackException) {
        return true;
    }
    if (exception.getCause() instanceof PasswordCallbackException) {
        return true;
    }
    if (exception.getCause() != null && exception.getCause().getCause() instanceof PasswordCallbackException) {
        return true;
    }
    try {
        String auditMessage = exception.getMessage();
        if (exception.getClass() != null) {
            // Exception cause has much better message because CXF masks real messages in the SOAP faults.
            auditMessage = exception.getCause().getMessage();
        }
        SOAPMessage saajSoapMessage = message.getContent(SOAPMessage.class);
        String username = securityHelper.getUsernameFromMessage(saajSoapMessage);
        ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
        securityHelper.auditLoginFailure(username, null, connEnv, auditMessage);
    } catch (WSSecurityException e) {
        // Ignore
        LOGGER.trace("Exception getting username from soap message (probably safe to ignore)", e);
    } catch (Exception e) {
        LOGGER.error("Error auditing SOAP fault: " + e.getMessage(), e);
    // but otherwise ignore it
    }
    return true;
}
Also used : WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SOAPMessage(javax.xml.soap.SOAPMessage) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment)

Example 2 with ConnectionEnvironment

use of com.evolveum.midpoint.security.api.ConnectionEnvironment in project midpoint by Evolveum.

the class SpringAuthenticationInjectorInterceptor method handleMessage.

@Override
public void handleMessage(SoapMessage message) throws Fault {
    //Note: in constructor we have specified that we will be called after we have been successfully authenticated the user through WS-Security
    //Now we will only set the Spring Authentication object based on the user found in the header
    LOGGER.trace("Intercepted message: {}", message);
    SOAPMessage saajSoapMessage = securityHelper.getSOAPMessage(message);
    if (saajSoapMessage == null) {
        LOGGER.error("No soap message in handler");
        throw createFault(WSSecurityException.ErrorCode.FAILURE);
    }
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
    String username = null;
    try {
        username = securityHelper.getUsernameFromMessage(saajSoapMessage);
        LOGGER.trace("Attempt to authenticate user '{}'", username);
        if (StringUtils.isBlank(username)) {
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "Empty username");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
        MidPointPrincipal principal;
        try {
            principal = userDetailsService.getPrincipal(username);
        } catch (SchemaException e) {
            LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "Schema error: " + e.getMessage());
            throw new Fault(e);
        }
        LOGGER.trace("Principal: {}", principal);
        if (principal == null) {
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, null, connEnv, "No user");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
        // Account validity and credentials and all this stuff should be already checked
        // in the password callback
        Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String operationName;
        try {
            operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName();
        } catch (SOAPException e) {
            LOGGER.debug("Access to web service denied for user '{}': SOAP error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "SOAP error: " + e.getMessage());
            throw new Fault(e);
        }
        // AUTHORIZATION
        boolean isAuthorized;
        try {
            isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL, AuthorizationPhaseType.REQUEST, null, null, null, null);
            LOGGER.trace("Determined authorization for web service access (action: {}): {}", AuthorizationConstants.AUTZ_WS_ALL_URL, isAuthorized);
        } catch (SchemaException e) {
            LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
            throw createFault(WSSecurityException.ErrorCode.FAILURE);
        }
        if (!isAuthorized) {
            String action = QNameUtil.qNameToUri(new QName(AuthorizationConstants.NS_AUTHORIZATION_WS, operationName));
            try {
                isAuthorized = securityEnforcer.isAuthorized(action, AuthorizationPhaseType.REQUEST, null, null, null, null);
                LOGGER.trace("Determined authorization for web service operation {} (action: {}): {}", operationName, action, isAuthorized);
            } catch (SchemaException e) {
                LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
                message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
                securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
                throw createFault(WSSecurityException.ErrorCode.FAILURE);
            }
        }
        if (!isAuthorized) {
            LOGGER.debug("Access to web service denied for user '{}': not authorized", username);
            message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Not authorized");
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }
    } catch (WSSecurityException e) {
        LOGGER.debug("Access to web service denied for user '{}': security exception: {}", username, e.getMessage(), e);
        message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, null, connEnv, "Security exception: " + e.getMessage());
        throw new Fault(e, e.getFaultCode());
    } catch (ObjectNotFoundException e) {
        LOGGER.debug("Access to web service denied for user '{}': object not found: {}", username, e.getMessage(), e);
        message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, null, connEnv, "No user");
        throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    // Avoid auditing login attempt again if the operation fails on internal authorization
    message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
    LOGGER.debug("Access to web service allowed for user '{}'", username);
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) Fault(org.apache.cxf.interceptor.Fault) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SOAPMessage(javax.xml.soap.SOAPMessage) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) Authentication(org.springframework.security.core.Authentication) SOAPException(javax.xml.soap.SOAPException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 3 with ConnectionEnvironment

use of com.evolveum.midpoint.security.api.ConnectionEnvironment in project midpoint by Evolveum.

the class PasswordCallback method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    LOGGER.trace("Invoked PasswordCallback with {} callbacks: {}", callbacks.length, callbacks);
    WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
    String username = pc.getIdentifier();
    String wssPasswordType = pc.getType();
    LOGGER.trace("Username: '{}', Password type: {}", username, wssPasswordType);
    try {
        ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
        pc.setPassword(passwordAuthenticationEvaluatorImpl.getAndCheckUserPassword(connEnv, username));
    } catch (Exception e) {
        LOGGER.trace("Exception in password callback: {}: {}", e.getClass().getSimpleName(), e.getMessage(), e);
        throw new PasswordCallbackException("Authentication failed");
    }
}
Also used : WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment)

Example 4 with ConnectionEnvironment

use of com.evolveum.midpoint.security.api.ConnectionEnvironment in project midpoint by Evolveum.

the class MidPointAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String enteredUsername = (String) authentication.getPrincipal();
    LOGGER.trace("Authenticating username '{}'", enteredUsername);
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI);
    Authentication token;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        String enteredPassword = (String) authentication.getCredentials();
        token = passwordAuthenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(enteredUsername, enteredPassword));
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        token = passwordAuthenticationEvaluator.authenticateUserPreAuthenticated(connEnv, enteredUsername);
    } else {
        LOGGER.error("Unsupported authentication {}", authentication);
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }
    MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
    return token;
}
Also used : PasswordAuthenticationContext(com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 5 with ConnectionEnvironment

use of com.evolveum.midpoint.security.api.ConnectionEnvironment in project midpoint by Evolveum.

the class PageAccountActivation method propagatePassword.

private void propagatePassword(AjaxRequestTarget target, Form<?> form) {
    List<ShadowType> shadowsToActivate = getShadowsToActivate();
    PasswordTextField passwordPanel = (PasswordTextField) form.get(createComponentPath(ID_PASSWORD));
    String value = passwordPanel.getModelObject();
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_USER_URI);
    UsernamePasswordAuthenticationToken token;
    try {
        token = authenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(userModel.getObject().getName().getOrig(), value, userModel.getObject().getClass()));
    } catch (Exception ex) {
        LOGGER.error("Failed to authenticate user, reason {}", ex.getMessage());
        getSession().error(getString("PageAccountActivation.authentication.failed"));
        throw new RestartResponseException(PageAccountActivation.class, getPageParameters());
    }
    if (token == null) {
        LOGGER.error("Failed to authenticate user");
        getSession().error(getString("PageAccountActivation.authentication.failed"));
        throw new RestartResponseException(PageAccountActivation.class, getPageParameters());
    }
    ProtectedStringType passwordValue = new ProtectedStringType();
    passwordValue.setClearValue(value);
    Collection<ObjectDelta<ShadowType>> passwordDeltas = new ArrayList<>(shadowsToActivate.size());
    for (ShadowType shadow : shadowsToActivate) {
        ObjectDelta<ShadowType> shadowDelta = getPrismContext().deltaFactory().object().createModificationReplaceProperty(ShadowType.class, shadow.getOid(), SchemaConstants.PATH_PASSWORD_VALUE, passwordValue);
        shadowDelta.addModificationReplaceProperty(ShadowType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_ACTIVE);
        passwordDeltas.add(shadowDelta);
    }
    OperationResult result = runPrivileged(new Producer<OperationResult>() {

        private static final long serialVersionUID = 1L;

        @Override
        public OperationResult run() {
            OperationResult result = new OperationResult(OPERATION_ACTIVATE_SHADOWS);
            Task task = createAnonymousTask(OPERATION_ACTIVATE_SHADOWS);
            WebModelServiceUtils.save((Collection) passwordDeltas, null, result, task, PageAccountActivation.this);
            return result;
        }
    });
    result.recomputeStatus();
    if (!result.isSuccess()) {
        getSession().error(getString("PageAccountActivation.account.activation.failed"));
        LOGGER.error("Failed to acitvate accounts, reason: {} ", result.getMessage());
        target.add(getFeedbackPanel());
    } else {
        getSession().success(getString("PageAccountActivation.account.activation.successful"));
        target.add(getFeedbackPanel());
        activated = true;
    }
    target.add(PageAccountActivation.this);
}
Also used : PasswordAuthenticationContext(com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext) Task(com.evolveum.midpoint.task.api.Task) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ArrayList(java.util.ArrayList) PasswordTextField(org.apache.wicket.markup.html.form.PasswordTextField) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) RestartResponseException(org.apache.wicket.RestartResponseException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) RestartResponseException(org.apache.wicket.RestartResponseException) Collection(java.util.Collection) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)

Aggregations

ConnectionEnvironment (com.evolveum.midpoint.security.api.ConnectionEnvironment)15 Authentication (org.springframework.security.core.Authentication)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)5 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)5 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)3 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)3 GuiProfiledPrincipal (com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal)3 PasswordAuthenticationContext (com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext)3 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)3 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)3 AuthenticationException (org.springframework.security.core.AuthenticationException)3 PreAuthenticationContext (com.evolveum.midpoint.model.api.context.PreAuthenticationContext)2 Task (com.evolveum.midpoint.task.api.Task)2 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)2 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)2 IOException (java.io.IOException)2 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)2 SOAPMessage (javax.xml.soap.SOAPMessage)2 WSPasswordCallback (org.apache.wss4j.common.ext.WSPasswordCallback)2