org.apache.wss4j.common.ext.WSSecurityException Java Examples

The following examples show how to use org.apache.wss4j.common.ext.WSSecurityException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StaxCryptoCoverageChecker.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkSignedBody(List<SecurityEvent> results) throws WSSecurityException {
    if (!signBody) {
        return;
    }

    boolean isBodySigned = false;
    for (SecurityEvent signedEvent : results) {
        AbstractSecuredElementSecurityEvent securedEvent =
            (AbstractSecuredElementSecurityEvent)signedEvent;
        if (!securedEvent.isSigned()) {
            continue;
        }

        List<QName> signedPath = securedEvent.getElementPath();
        if (isBody(signedPath)) {
            isBodySigned = true;
            break;
        }
    }

    if (!isBodySigned) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                                      new Exception("The SOAP Body is not signed"));
    }
}
 
Example #2
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testNoSubjectConfirmationData() throws Exception {
    Response response = createResponse(null);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #3
Source File: BinarySecurityTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {
    RequestData data = new CXFRequestData();
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        data.setCallbackHandler(SecurityUtils.getCallbackHandler(o));
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    data.setMsgContext(message);
    data.setWssConfig(WSSConfig.getNewInstance());

    WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
    data.setWsDocInfo(wsDocInfo);

    BinarySecurityTokenProcessor p = new BinarySecurityTokenProcessor();
    return p.handleToken(tokenElement, data);
}
 
Example #4
Source File: CustomStaxUTValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends UsernameSecurityToken & InboundSecurityToken> T validate(
        UsernameTokenType usernameTokenType, TokenContext tokenContext) throws WSSecurityException {
    UsernameSecurityTokenImpl token =
        super.</*fake @see above*/UsernameSecurityTokenImpl>validate(usernameTokenType, tokenContext);

    Subject subject = new Subject();
    subject.getPrincipals().add(token.getPrincipal());
    if ("Alice".equals(token.getUsername())) {
        subject.getPrincipals().add(new SimpleGroup("manager", token.getUsername()));
    }
    subject.getPrincipals().add(new SimpleGroup("worker", token.getUsername()));
    token.setSubject(subject);

    return (T)token;
}
 
Example #5
Source File: ClaimsProcessorTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, SAXException,
    ParserConfigurationException {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example #6
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void storeTokenInCache(
    TokenStore tokenStore,
    SamlAssertionWrapper assertion,
    Principal principal,
    TokenRenewerParameters tokenParameters
) throws WSSecurityException {
    // Store the successfully renewed token in the cache
    byte[] signatureValue = assertion.getSignatureValue();
    if (tokenStore != null && signatureValue != null && signatureValue.length > 0) {

        SecurityToken securityToken =
            CacheUtils.createSecurityTokenForStorage(assertion.getElement(), assertion.getId(),
                assertion.getNotOnOrAfter(), tokenParameters.getPrincipal(), tokenParameters.getRealm(),
                tokenParameters.getTokenRequirements().getRenewing());
        CacheUtils.storeTokenInCache(
            securityToken, tokenParameters.getTokenStore(), signatureValue);
    }
}
 
Example #7
Source File: SAMLProtocolResponseValidator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Validate a SAML 1.1 Protocol Response
 * @param samlResponse
 * @throws WSSecurityException
 */
public void validateSamlResponse(
    org.opensaml.saml.saml1.core.Response samlResponse,
    FedizContext config
) throws WSSecurityException {
    // Check the Status Code
    if (samlResponse.getStatus() == null
        || samlResponse.getStatus().getStatusCode() == null
        || samlResponse.getStatus().getStatusCode().getValue() == null) {
        LOG.debug("Either the SAML Response Status or StatusCode is null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    String statusValue = samlResponse.getStatus().getStatusCode().getValue().getLocalPart();
    if (!SAML1_STATUSCODE_SUCCESS.equals(statusValue)) {
        LOG.debug(
            "SAML Status code of " + samlResponse.getStatus().getStatusCode().getValue()
            + "does not equal " + SAML1_STATUSCODE_SUCCESS
        );
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    validateResponseSignature(samlResponse, config);
}
 
Example #8
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Element createSAMLAssertion(
    String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler,
    Map<String, RealmProperties> realms, String user, String issuer
) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    samlTokenProvider.setRealmMap(realms);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername,
            callbackHandler, user, issuer
        );
    if (realms != null) {
        providerParameters.setRealm("A");
    }
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    return (Element)providerResponse.getToken();
}
 
Example #9
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testInvalidNotOnOrAfter() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().minusSeconds(1));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    Response response = createResponse(subjectConfirmationData);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #10
Source File: UsernameTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected UsernameTokenPrincipal parseTokenAndCreatePrincipal(Element tokenElement, boolean bspCompliant,
                                                              boolean allowNamespaceQualifiedPWDTypes)
    throws WSSecurityException, Base64DecodingException {
    BSPEnforcer bspEnforcer = new org.apache.wss4j.common.bsp.BSPEnforcer(!bspCompliant);
    org.apache.wss4j.dom.message.token.UsernameToken ut =
        new org.apache.wss4j.dom.message.token.UsernameToken(tokenElement, allowNamespaceQualifiedPWDTypes,
                                                             bspEnforcer);

    WSUsernameTokenPrincipalImpl principal = new WSUsernameTokenPrincipalImpl(ut.getName(), ut.isHashed());
    if (ut.getNonce() != null) {
        principal.setNonce(XMLUtils.decode(ut.getNonce()));
    }
    principal.setPassword(ut.getPassword());
    principal.setCreatedTime(ut.getCreated());
    principal.setPasswordType(ut.getPasswordType());

    return principal;
}
 
Example #11
Source File: SCTTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper transformedToken = validatedCredential.getTransformedToken();
    if (transformedToken == null || transformedToken.getSaml2() == null
        || !"DoubleItSTSIssuer".equals(transformedToken.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    transformedToken.parseSubject(
        new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(),
        data.getCallbackHandler()
    );
    SAMLKeyInfo keyInfo = transformedToken.getSubjectKeyInfo();
    byte[] secret = keyInfo.getSecret();
    validatedCredential.setSecretKey(secret);

    return validatedCredential;
}
 
Example #12
Source File: SAMLDelegationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Element createUnsignedSAMLAssertion(
    String tokenType, String keyType, String user, String issuer
) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    samlTokenProvider.setSignToken(false);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            tokenType, keyType, null, null, null, user, issuer
        );

    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    return (Element)providerResponse.getToken();
}
 
Example #13
Source File: TransportBindingHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private byte[] doIssuedTokenSignature(
    final AbstractToken token, final SupportingTokens wrapper
) throws Exception {
    boolean tokenIncluded = false;
    // Get the issued token
    SecurityToken secTok = getSecurityToken();
    if (secTok == null) {
        LOG.fine("The retrieved SecurityToken was null");
        Exception ex = new Exception("The retrieved SecurityToken was null");
        throw new WSSecurityException(
            WSSecurityException.ErrorCode.FAILURE, ex
        );
    }

    if (isTokenRequired(token.getIncludeTokenType())) {
        //Add the token
        Element el = cloneElement(secTok.getToken());
        //if (securityTok != null) {
            //do we need to sign this as well?
            //String id = addWsuIdToElement(el);
            //sigParts.add(new WSEncryptionPart(id));
        //}

        addEncryptedKeyElement(el);
        tokenIncluded = true;
    }

    List<WSEncryptionPart> sigParts =
            signPartsAndElements(wrapper.getSignedParts(), wrapper.getSignedElements());

    if (token.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
        return doDerivedKeySignature(tokenIncluded, secTok, token, sigParts);
    }
    return doSignature(tokenIncluded, secTok, token, sigParts);
}
 
Example #14
Source File: RSSecurityUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static CallbackHandler getCallbackHandler(Message message,
                                                 Class<?> callingClass,
                                                 String callbackProperty) throws WSSecurityException {
    //Then try to get the password from the given callback handler
    Object o = SecurityUtils.getSecurityPropertyValue(callbackProperty, message);

    try {
        return SecurityUtils.getCallbackHandler(o);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
}
 
Example #15
Source File: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public AbstractWsSecurityHandler.WSSecHeaderGeneratorStep1 on(SOAPMessage message) throws TechnicalConnectorException {
   try {
      Validate.notNull(message);
      this.soapPart = message.getSOAPPart();
      this.wsSecHeader = new WSSecHeader();
      this.wsSecHeader.insertSecurityHeader(this.soapPart);
      WSSConfig config = WSSConfig.getNewInstance();
      config.setAddInclusivePrefixes(false);
      this.sign = new WSSecSignature(config);
      return this;
   } catch (WSSecurityException var3) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var3});
   }
}
 
Example #16
Source File: WSSecHeaderGeneratorWss4jImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public AbstractWsSecurityHandler.WSSecHeaderGeneratorStep1 on(SOAPMessage message) throws TechnicalConnectorException {
   try {
      Validate.notNull(message);
      this.soapPart = message.getSOAPPart();
      this.wsSecHeader = new WSSecHeader();
      this.wsSecHeader.insertSecurityHeader(this.soapPart);
      WSSConfig config = WSSConfig.getNewInstance();
      config.setAddInclusivePrefixes(false);
      this.sign = new WSSecSignature(config);
      return this;
   } catch (WSSecurityException var3) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var3});
   }
}
 
Example #17
Source File: JWTTokenProviderRealmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private TokenProviderParameters createProviderParameters(
    String tokenType
) throws WSSecurityException {
    TokenProviderParameters parameters = new TokenProviderParameters();

    TokenRequirements tokenRequirements = new TokenRequirements();
    tokenRequirements.setTokenType(tokenType);
    parameters.setTokenRequirements(tokenRequirements);

    KeyRequirements keyRequirements = new KeyRequirements();
    parameters.setKeyRequirements(keyRequirements);

    parameters.setPrincipal(new CustomTokenPrincipal("alice"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    parameters.setMessageContext(msgCtx);

    parameters.setAppliesToAddress("http://dummy-service.com/dummy");

    // Add STSProperties object
    StaticSTSProperties stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    parameters.setStsProperties(stsProperties);

    parameters.setEncryptionProperties(new EncryptionProperties());

    return parameters;
}
 
Example #18
Source File: SAMLDelegationHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Is Delegation allowed for a particular token
 */
protected boolean isDelegationAllowed(
    ReceivedToken receivedToken, String appliesToAddress
) {
    Element validateTargetElement = (Element)receivedToken.getToken();
    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(validateTargetElement);

        for (String confirmationMethod : assertion.getConfirmationMethods()) {
            if (!(SAML1Constants.CONF_BEARER.equals(confirmationMethod)
                || SAML2Constants.CONF_BEARER.equals(confirmationMethod))) {
                LOG.fine("An unsupported Confirmation Method was used: " + confirmationMethod);
                return false;
            }
        }

        if (checkAudienceRestriction && appliesToAddress != null) {
            List<String> addresses = getAudienceRestrictions(assertion);
            if (!(addresses.isEmpty() || addresses.contains(appliesToAddress))) {
                LOG.fine("The AppliesTo address " + appliesToAddress + " is not contained"
                         + " in the Audience Restriction addresses in the assertion");
                return false;
            }
        }
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "Error in ascertaining whether delegation is allowed", ex);
        return false;
    }

    return true;
}
 
Example #19
Source File: X509TokenTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAsymmetricSignatureReplay() throws Exception {
    if (test.isStreaming()) {
        return;
    }

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = X509TokenTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = X509TokenTest.class.getResource("DoubleItX509Signature.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItAsymmetricSignaturePort");
    DoubleItPortType x509Port =
            service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(x509Port, test.getPort());

    Client cxfClient = ClientProxy.getClient(x509Port);
    SecurityHeaderCacheInterceptor cacheInterceptor =
        new SecurityHeaderCacheInterceptor();
    cxfClient.getOutInterceptors().add(cacheInterceptor);

    // Make two invocations with the same security header
    assertEquals(50, x509Port.doubleIt(25));
    try {
        x509Port.doubleIt(25);
        fail("Failure expected on a replayed Timestamp");
    } catch (javax.xml.ws.soap.SOAPFaultException ex) {
        assertTrue(ex.getMessage().contains(WSSecurityException.UNIFIED_SECURITY_ERR));
    }

    ((java.io.Closeable)x509Port).close();
    bus.shutdown(true);
}
 
Example #20
Source File: EncryptionUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static XMLCipher initXMLCipher(String symEncAlgo, int mode, Key key)
    throws WSSecurityException {
    try {
        XMLCipher cipher = XMLCipher.getInstance(symEncAlgo);
        cipher.setSecureValidation(true);
        cipher.init(mode, key);
        return cipher;
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, ex);
    }
}
 
Example #21
Source File: STSStaxTokenValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public InboundSecurityToken validate(final BinarySecurityTokenType binarySecurityTokenType,
                                     final TokenContext tokenContext)
    throws WSSecurityException {
    STSStaxBSTValidator validator = new STSStaxBSTValidator(alwaysValidateToSts);
    return validator.validate(binarySecurityTokenType, tokenContext);
}
 
Example #22
Source File: SAMLTokenRenewerPOPTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException {
    TokenValidatorParameters parameters = new TokenValidatorParameters();

    TokenRequirements tokenRequirements = new TokenRequirements();
    parameters.setTokenRequirements(tokenRequirements);

    KeyRequirements keyRequirements = new KeyRequirements();
    parameters.setKeyRequirements(keyRequirements);

    parameters.setPrincipal(new CustomTokenPrincipal("alice"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    parameters.setMessageContext(msgCtx);

    // Add STSProperties object
    StaticSTSProperties stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    parameters.setStsProperties(stsProperties);
    parameters.setTokenStore(tokenStore);

    return parameters;
}
 
Example #23
Source File: JexlIssueSamlClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private STSPropertiesMBean createSTSPropertiesMBean(Crypto crypto) throws WSSecurityException {
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    return stsProperties;
}
 
Example #24
Source File: SAMLProviderRealmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private TokenProviderParameters createProviderParameters(
    String tokenType, String keyType
) throws WSSecurityException {
    TokenProviderParameters parameters = new TokenProviderParameters();

    TokenRequirements tokenRequirements = new TokenRequirements();
    tokenRequirements.setTokenType(tokenType);
    parameters.setTokenRequirements(tokenRequirements);

    KeyRequirements keyRequirements = new KeyRequirements();
    keyRequirements.setKeyType(keyType);
    parameters.setKeyRequirements(keyRequirements);

    parameters.setPrincipal(new CustomTokenPrincipal("alice"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    parameters.setMessageContext(msgCtx);

    parameters.setAppliesToAddress("http://dummy-service.com/dummy");

    // Add STSProperties object
    StaticSTSProperties stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    parameters.setStsProperties(stsProperties);

    parameters.setEncryptionProperties(new EncryptionProperties());

    return parameters;
}
 
Example #25
Source File: FedizSignatureTrustValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the credential argument. It must contain either some Certificates or a PublicKey.
 *
 * A Crypto and a CallbackHandler implementation is required to be set.
 *
 * @param credential the Credential to be validated
 * @param data the RequestData associated with the request
 * @throws WSSecurityException on a failed validation
 */
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null
        || ((credential.getCertificates() == null || credential.getCertificates().length == 0)
            && credential.getPublicKey() == null)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }

    verifyTrust(credential, data);

    return credential;
}
 
Example #26
Source File: CustomUTValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }

    // Need to use SAAJ to get the SOAP Body as we are just using the UsernameTokenInterceptor
    SOAPMessage soapMessage = getSOAPMessage((SoapMessage)data.getMsgContext());
    try {
        Element soapBody = SAAJUtils.getBody(soapMessage);

        if (soapBody != null) {
            // Find custom Element in the SOAP Body
            Element realm = XMLUtils.findElement(soapBody, "realm", "http://cxf.apache.org/custom");
            if (realm != null) {
                String realmStr = realm.getTextContent();
                if ("custom-realm".equals(realmStr)) {

                    UsernameTokenValidator validator = new UsernameTokenValidator();
                    return validator.validate(credential, data);
                }
            }
        }
    } catch (SOAPException ex) {
        // ignore
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
}
 
Example #27
Source File: EETClientTest.java    From eet-client with MIT License 5 votes vote down vote up
@Test
public void testInvalidResponseSignature() throws Exception {
    final InputStream clientKey = getClass().getResourceAsStream("/keys/CZ683555118.p12");
    final InputStream serverCertificate = getClass().getResourceAsStream("/certificates/2qca16_rsa.der"); // This CA is not valid for playground, should throw an Exception
    final EETClient client = EETServiceFactory.getInstance(clientKey, "eet", serverCertificate);
    try {
        client.submitReceipt(getData(), CommunicationMode.REAL, EndpointType.PLAYGROUND, SubmissionType.FIRST_ATTEMPT);
        Assert.fail("Should fail due to error during certificate path validation");
    } catch (CommunicationException e) {
        final Throwable securityException = e.getCause().getCause();
        Assert.assertEquals(WSSecurityException.class, securityException.getClass());
        final WSSecurityException wsSecurityException = (WSSecurityException) securityException;
        Assert.assertEquals("certpath", wsSecurityException.getMsgID());
    }
}
 
Example #28
Source File: SAMLTokenRenewerPOPTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private TokenProviderParameters createProviderParameters(
    String tokenType, String keyType, Crypto crypto,
    String signatureUsername, CallbackHandler callbackHandler
) throws WSSecurityException {
    TokenProviderParameters parameters = new TokenProviderParameters();

    TokenRequirements tokenRequirements = new TokenRequirements();
    tokenRequirements.setTokenType(tokenType);
    parameters.setTokenRequirements(tokenRequirements);

    KeyRequirements keyRequirements = new KeyRequirements();
    keyRequirements.setKeyType(keyType);
    ReceivedCredential receivedCredential = new ReceivedCredential();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    receivedCredential.setX509Cert(crypto.getX509Certificates(cryptoType)[0]);
    keyRequirements.setReceivedCredential(receivedCredential);
    parameters.setKeyRequirements(keyRequirements);

    parameters.setPrincipal(new CustomTokenPrincipal("alice"));
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    parameters.setMessageContext(msgCtx);

    parameters.setAppliesToAddress("http://dummy-service.com/dummy");

    // Add STSProperties object
    StaticSTSProperties stsProperties = new StaticSTSProperties();
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setSignatureUsername(signatureUsername);
    stsProperties.setCallbackHandler(callbackHandler);
    stsProperties.setIssuer("STS");
    parameters.setStsProperties(stsProperties);

    parameters.setEncryptionProperties(new EncryptionProperties());
    parameters.setTokenStore(tokenStore);

    return parameters;
}
 
Example #29
Source File: SAML1CallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setIssuer("www.example.com");
            callback.setSamlVersion(Version.SAML_11);
            SubjectBean subjectBean =
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            createAndSetStatement(subjectBean, callback);

            try {
                Crypto crypto = CryptoFactory.getInstance("outsecurity.properties");
                callback.setIssuerCrypto(crypto);
                callback.setIssuerKeyName("myalias");
                callback.setIssuerKeyPassword("myAliasPassword");
                callback.setSignAssertion(signAssertion);
            } catch (WSSecurityException e) {
                throw new IOException(e);
            }

        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #30
Source File: AbstractServiceProviderFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected void setSecurityContext(
    ResponseState responseState, Message m, Element token
) throws WSSecurityException {
    CXFFedizPrincipal principal =
        new CXFFedizPrincipal(responseState.getSubject(), responseState.getClaims(),
                              responseState.getRoles(), token);

    SecurityTokenThreadLocal.setToken(principal.getLoginToken());
    FedizSecurityContext context =
        new FedizSecurityContext(principal, responseState.getRoles());
    m.put(SecurityContext.class, context);
}