Search in sources :

Example 21 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class SamlTokenInterceptor method processToken.

protected void processToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element) h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName()) && (WSS4JConstants.SAML_NS.equals(child.getNamespaceURI()) || WSS4JConstants.SAML2_NS.equals(child.getNamespaceURI()))) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    boolean signed = false;
                    for (WSSecurityEngineResult result : samlResults) {
                        SamlAssertionWrapper wrapper = (SamlAssertionWrapper) result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                        if (wrapper.isSigned()) {
                            signed = true;
                            break;
                        }
                    }
                    assertTokens(message, SPConstants.SAML_TOKEN, signed);
                    Integer key = WSConstants.ST_UNSIGNED;
                    if (signed) {
                        key = WSConstants.ST_SIGNED;
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults, Collections.singletonMap(key, samlResults));
                    results.add(0, rResult);
                    // Check version against policy
                    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
                    for (AssertionInfo ai : PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SAML_TOKEN)) {
                        SamlToken samlToken = (SamlToken) ai.getAssertion();
                        for (WSSecurityEngineResult result : samlResults) {
                            SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper) result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                            if (!checkVersion(aim, samlToken, assertionWrapper)) {
                                ai.setNotAsserted("Wrong SAML Version");
                            }
                            TLSSessionInfo tlsInfo = message.get(TLSSessionInfo.class);
                            Certificate[] tlsCerts = null;
                            if (tlsInfo != null) {
                                tlsCerts = tlsInfo.getPeerCertificates();
                            }
                            if (!DOMSAMLUtil.checkHolderOfKey(assertionWrapper, null, tlsCerts)) {
                                ai.setNotAsserted("Assertion fails holder-of-key requirements");
                                continue;
                            }
                            if (!DOMSAMLUtil.checkSenderVouches(assertionWrapper, tlsCerts, null, null)) {
                                ai.setNotAsserted("Assertion fails sender-vouches requirements");
                                continue;
                            }
                        }
                    }
                    if (signed) {
                        Principal principal = (Principal) samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                        SecurityContext sc = message.get(SecurityContext.class);
                        if (sc == null || sc.getUserPrincipal() == null) {
                            message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                        }
                    }
                }
            } catch (WSSecurityException ex) {
                throw WSS4JUtils.createSoapFault(message, message.getVersion(), ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
Also used : DefaultSecurityContext(org.apache.cxf.interceptor.security.DefaultSecurityContext) AssertionInfo(org.apache.cxf.ws.policy.AssertionInfo) SamlToken(org.apache.wss4j.policy.model.SamlToken) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) AssertionInfoMap(org.apache.cxf.ws.policy.AssertionInfoMap) Header(org.apache.cxf.headers.Header) DefaultSecurityContext(org.apache.cxf.interceptor.security.DefaultSecurityContext) SecurityContext(org.apache.cxf.security.SecurityContext) TLSSessionInfo(org.apache.cxf.security.transport.TLSSessionInfo) Principal(java.security.Principal) Certificate(java.security.cert.Certificate)

Example 22 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class WSS4JInOutTest method testEncryptedUsernameToken.

@Test
public void testEncryptedUsernameToken() throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.USERNAME_TOKEN + " " + ConfigurationConstants.ENCRYPT);
    outProperties.put(ConfigurationConstants.ENC_PROP_FILE, "outsecurity.properties");
    outProperties.put(ConfigurationConstants.USER, "alice");
    outProperties.put("password", "alicePassword");
    outProperties.put(ConfigurationConstants.ENCRYPTION_USER, "myalias");
    outProperties.put(ConfigurationConstants.ENCRYPTION_PARTS, "{Content}{" + WSS4JConstants.WSSE_NS + "}UsernameToken");
    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.USERNAME_TOKEN + " " + ConfigurationConstants.ENCRYPT);
    inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties");
    inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback());
    List<String> xpaths = new ArrayList<>();
    xpaths.add("//wsse:Security");
    SoapMessage inmsg = makeInvocation(outProperties, xpaths, inProperties);
    List<WSHandlerResult> handlerResults = getResults(inmsg);
    assertNotNull(handlerResults);
    assertSame(handlerResults.size(), 1);
    // 
    // This should contain exactly 2 protection results
    // 
    final java.util.List<WSSecurityEngineResult> protectionResults = handlerResults.get(0).getResults();
    assertNotNull(protectionResults);
    assertSame(protectionResults.size(), 2);
    final Principal p1 = (Principal) protectionResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    final Principal p2 = (Principal) protectionResults.get(1).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    assertTrue(p1 instanceof UsernameTokenPrincipal || p2 instanceof UsernameTokenPrincipal);
    Principal utPrincipal = p1 instanceof UsernameTokenPrincipal ? p1 : p2;
    SecurityContext securityContext = inmsg.get(SecurityContext.class);
    assertNotNull(securityContext);
    assertSame(securityContext.getUserPrincipal(), utPrincipal);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal) SecurityContext(org.apache.cxf.security.SecurityContext) Principal(java.security.Principal) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal) Test(org.junit.Test)

Example 23 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class SamlTokenTest method testSaml2TokenWithRolesSingleValue.

/**
 * This test creates a SAML2 Assertion and sends it in the security header to the provider.
 * An attribute is created per role. There are several attributes with the same name.
 */
@Test
public void testSaml2TokenWithRolesSingleValue() throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    outProperties.put(ConfigurationConstants.USER, "alice");
    outProperties.put("password", "password");
    outProperties.put(ConfigurationConstants.SIG_PROP_FILE, "alice.properties");
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(false);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    callbackHandler.setSignAssertion(true);
    callbackHandler.setStatement(Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);
    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_SIGNED);
    inProperties.put(ConfigurationConstants.SIG_VER_PROP_FILE, "insecurity.properties");
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    validator.setRequireSAML1Assertion(false);
    validator.setRequireSenderVouches(false);
    validator.setRequireBearer(true);
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);
    List<String> xpaths = new ArrayList<>();
    xpaths.add("//wsse:Security");
    xpaths.add("//wsse:Security/saml2:Assertion");
    Map<String, String> inMessageProperties = new HashMap<>();
    inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");
    Message message = makeInvocation(outProperties, xpaths, inProperties, inMessageProperties);
    final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
    SecurityContext sc = message.get(SecurityContext.class);
    assertNotNull(sc);
    assertTrue(sc.isUserInRole("user"));
    assertTrue(sc.isUserInRole("admin"));
    WSSecurityEngineResult actionResult = handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
    SamlAssertionWrapper receivedAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
    assertTrue(receivedAssertion.isSigned());
}
Also used : Message(org.apache.cxf.message.Message) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SOAPMessage(javax.xml.soap.SOAPMessage) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SecurityContext(org.apache.cxf.security.SecurityContext) AbstractSecurityTest(org.apache.cxf.ws.security.wss4j.AbstractSecurityTest) Test(org.junit.Test)

Example 24 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project cxf by apache.

the class SamlTokenTest method testSaml2TokenWithRoles.

/**
 * This test creates a SAML2 Assertion and sends it in the security header to the provider.
 * An single attribute is created for the roles but multiple attribute value elements.
 */
@Test
public void testSaml2TokenWithRoles() throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    outProperties.put(ConfigurationConstants.USER, "alice");
    outProperties.put("password", "password");
    outProperties.put(ConfigurationConstants.SIG_PROP_FILE, "alice.properties");
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    callbackHandler.setSignAssertion(true);
    callbackHandler.setStatement(Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);
    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_SIGNED);
    inProperties.put(ConfigurationConstants.SIG_VER_PROP_FILE, "insecurity.properties");
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    validator.setRequireSAML1Assertion(false);
    validator.setRequireSenderVouches(false);
    validator.setRequireBearer(true);
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);
    List<String> xpaths = new ArrayList<>();
    xpaths.add("//wsse:Security");
    xpaths.add("//wsse:Security/saml2:Assertion");
    Map<String, String> inMessageProperties = new HashMap<>();
    inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");
    Message message = makeInvocation(outProperties, xpaths, inProperties, inMessageProperties);
    final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
    SecurityContext sc = message.get(SecurityContext.class);
    assertNotNull(sc);
    assertTrue(sc.isUserInRole("user"));
    assertTrue(sc.isUserInRole("admin"));
    WSSecurityEngineResult actionResult = handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
    SamlAssertionWrapper receivedAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
    assertTrue(receivedAssertion.isSigned());
}
Also used : Message(org.apache.cxf.message.Message) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SOAPMessage(javax.xml.soap.SOAPMessage) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SecurityContext(org.apache.cxf.security.SecurityContext) AbstractSecurityTest(org.apache.cxf.ws.security.wss4j.AbstractSecurityTest) Test(org.junit.Test)

Example 25 with SecurityContext

use of org.apache.cxf.security.SecurityContext in project tesb-rt-se by Talend.

the class MessageToEventMapper method mapToEvent.

/**
 * Map to event.
 *
 * @param message
 *            the message
 * @return the event
 */
public Event mapToEvent(Message message) {
    Event event = new Event();
    MessageInfo messageInfo = new MessageInfo();
    Originator originator = new Originator();
    boolean isRestMessage = isRestMessage(message);
    event.setMessageInfo(messageInfo);
    event.setOriginator(originator);
    String content = getPayload(message);
    event.setContent(content);
    handleContentLength(event);
    event.setEventType(null);
    Date date = new Date();
    event.setTimestamp(date);
    // if (isRestMessage) {
    // String queryString = (String) message.get(Message.QUERY_STRING);
    // if (queryString == null && message.getExchange().getInMessage() != null) {
    // queryString = (String) message.getExchange().getInMessage().get(Message.QUERY_STRING);
    // }
    // if (queryString != null && queryString.contains("_wadl")) {
    // return null;
    // }
    // }
    messageInfo.setFlowId(FlowIdHelper.getFlowId(message));
    if (!isRestMessage) {
        messageInfo.setMessageId(getMessageId(message));
        ServiceInfo serviceInfo = message.getExchange().getBinding().getBindingInfo().getService();
        if (null != serviceInfo) {
            String portTypeName = serviceInfo.getInterface().getName().toString();
            messageInfo.setPortType(portTypeName);
            messageInfo.setOperationName(getOperationName(message));
        }
        SoapBinding soapBinding = (SoapBinding) message.getExchange().getBinding();
        if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) {
            SoapBindingInfo soapBindingInfo = (SoapBindingInfo) soapBinding.getBindingInfo();
            messageInfo.setTransportType(soapBindingInfo.getTransportURI());
        }
    } else {
        messageInfo.setTransportType("http://cxf.apache.org/transports/http");
        messageInfo.setPortType(message.getExchange().getEndpoint().getEndpointInfo().getName().toString());
        String opName = getRestOperationName(message);
        messageInfo.setOperationName(opName);
    }
    if (messageInfo.getTransportType() == null) {
        messageInfo.setTransportType("Unknown transport type");
    }
    // add custom properties from CXF properties
    if (null != message.getExchange().getEndpoint().get(EventFeature.SAM_PROPERTIES)) {
        Map<String, String> customProp = (Map<String, String>) message.getExchange().getEndpoint().get(EventFeature.SAM_PROPERTIES);
        event.getCustomInfo().putAll(customProp);
    }
    String addr = message.getExchange().getEndpoint().getEndpointInfo().getAddress();
    if (null != addr) {
        event.getCustomInfo().put("address", addr);
    }
    String correlationId = CorrelationIdHelper.getCorrelationId(message);
    if (null != correlationId) {
        event.getCustomInfo().put("CorrelationID", correlationId);
    }
    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        originator.setIp(inetAddress.getHostAddress());
        originator.setHostname(inetAddress.getHostName());
    } catch (UnknownHostException e) {
        originator.setHostname("Unknown hostname");
        originator.setIp("Unknown ip address");
    }
    originator.setProcessId(Converter.getPID());
    if (isRestMessage) {
        // String queryString = (String) message.get(Message.QUERY_STRING);
        // if (null == queryString && null != message.getExchange().getInMessage()) {
        // queryString = (String) message.getExchange().getInMessage().get(Message.QUERY_STRING);
        // }
        // if (null != queryString) {
        // event.getCustomInfo().put("Query String", queryString);
        // }
        String accept = (String) message.get(Message.ACCEPT_CONTENT_TYPE);
        if (null != accept) {
            event.getCustomInfo().put("Accept Type", accept);
        }
        // String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
        // if (null != httpMethod) {
        // event.getCustomInfo().put("HTTP Method", httpMethod);
        // }
        String contentType = (String) message.get(Message.CONTENT_TYPE);
        if (null != contentType) {
            event.getCustomInfo().put("Content Type", contentType);
        }
        Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);
        if (null != responseCode) {
            event.getCustomInfo().put("Response Code", responseCode.toString());
        }
    }
    SecurityContext sc = message.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        originator.setPrincipal(sc.getUserPrincipal().getName());
    }
    if (originator.getPrincipal() == null) {
        AuthorizationPolicy authPolicy = message.get(AuthorizationPolicy.class);
        if (authPolicy != null) {
            originator.setPrincipal(authPolicy.getUserName());
        }
    }
    EventTypeEnum eventType = getEventType(message);
    event.setEventType(eventType);
    CustomInfo customInfo = CustomInfo.getOrCreateCustomInfo(message);
    // System.out.println("custom props: " + customInfo);
    event.getCustomInfo().putAll(customInfo);
    return event;
}
Also used : UnknownHostException(java.net.UnknownHostException) Date(java.util.Date) SoapBinding(org.apache.cxf.binding.soap.SoapBinding) MessageInfo(org.talend.esb.sam.common.event.MessageInfo) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Originator(org.talend.esb.sam.common.event.Originator) EventTypeEnum(org.talend.esb.sam.common.event.EventTypeEnum) SoapBindingInfo(org.apache.cxf.binding.soap.model.SoapBindingInfo) SecurityContext(org.apache.cxf.security.SecurityContext) Event(org.talend.esb.sam.common.event.Event) CustomInfo(org.talend.esb.sam.agent.message.CustomInfo) Map(java.util.Map) InetAddress(java.net.InetAddress)

Aggregations

SecurityContext (org.apache.cxf.security.SecurityContext)74 Principal (java.security.Principal)26 Message (org.apache.cxf.message.Message)16 Subject (javax.security.auth.Subject)13 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)12 DefaultSecurityContext (org.apache.cxf.interceptor.security.DefaultSecurityContext)11 SimplePrincipal (org.apache.cxf.common.security.SimplePrincipal)10 Test (org.junit.Test)10 ArrayList (java.util.ArrayList)9 SAMLSecurityContext (org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext)9 WSHandlerResult (org.apache.wss4j.dom.handler.WSHandlerResult)9 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)8 LoginSecurityContext (org.apache.cxf.security.LoginSecurityContext)7 QName (javax.xml.namespace.QName)6 SecurityToken (org.apache.cxf.common.security.SecurityToken)6 MessageImpl (org.apache.cxf.message.MessageImpl)6 HashMap (java.util.HashMap)5 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)5 Element (org.w3c.dom.Element)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4