diff --git a/doc/cxf-and-ws-securitypolicy.md b/doc/cxf-and-ws-securitypolicy.md new file mode 100644 index 0000000..ccd6629 --- /dev/null +++ b/doc/cxf-and-ws-securitypolicy.md @@ -0,0 +1,1163 @@ +CXF and WS-SecurityPolicy + +Status: Version 1.2 + +Version: 17.07.2018 + +[Changelog [4](#changelog)](#changelog) + +[1 Introduction [5](#introduction)](#introduction) + +[1.1 Intended audience [5](#intended-audience)](#intended-audience) + +[1.2 Prerequisites [5](#prerequisites)](#prerequisites) + +[1.3 Apache CXF Version [5](#apache-cxf-version)](#apache-cxf-version) + +[1.4 Disclaimer [5](#disclaimer)](#disclaimer) + +[2 Building a Web Service Provider [6](#building-a-web-service-provider)](#building-a-web-service-provider) + +[2.1 Hello World Service [6](#hello-world-service)](#hello-world-service) + +[2.2 Reference Code [6](#reference-code)](#reference-code) + +[2.3 Design Choices [6](#design-choices)](#design-choices) + +[2.4 Security Requirements [7](#security-requirements)](#security-requirements) + +[2.5 WS-SecurityPolicy Configuration [7](#ws-securitypolicy-configuration)](#ws-securitypolicy-configuration) + +[2.5.1 The General Security Policy [7](#the-general-security-policy)](#the-general-security-policy) + +[2.5.2 The Input Policy [8](#the-input-policy)](#the-input-policy) + +[2.5.3 The Output Policy [9](#the-output-policy)](#the-output-policy) + +[2.6 Configuring Keystores for the Service [9](#configuring-keystores-for-the-service)](#configuring-keystores-for-the-service) + +[2.7 Support Classes [10](#support-classes)](#support-classes) + +[2.7.1 Dealing with custom headers [10](#dealing-with-custom-headers)](#dealing-with-custom-headers) + +[2.7.2 Pulling data from incoming token and storing for later access [12](#pulling-data-from-incoming-token-and-storing-for-later-access)](#pulling-data-from-incoming-token-and-storing-for-later-access) + +[2.8 Additional Configuration of Apache CXF [15](#additional-configuration-of-apache-cxf)](#additional-configuration-of-apache-cxf) + +[2.8.1 Validating Audience Restriction [15](#validating-audience-restriction)](#validating-audience-restriction) + +[2.8.2 Configure TimeToLive [16](#configure-timetolive)](#configure-timetolive) + +[2.8.3 Configure BSP 1.1 Compliance [16](#configure-bsp-1.1-compliance)](#configure-bsp-1.1-compliance) + +[2.9 The bearer-token version of the service [17](#the-bearer-token-version-of-the-service)](#the-bearer-token-version-of-the-service) + +[2.9.1 Modify the WS-SecurityPolicy [17](#modify-the-ws-securitypolicy)](#modify-the-ws-securitypolicy) + +[2.9.2 Modify the truststore [18](#modify-the-truststore)](#modify-the-truststore) + +[2.10 Other Considerations [18](#other-considerations)](#other-considerations) + +[2.10.1 Replay detection [18](#replay-detection)](#replay-detection) + +[2.10.2 WS-SecureConversation [18](#ws-secureconversation)](#ws-secureconversation) + +[3 Building a Web Service Consumer [19](#building-a-web-service-consumer)](#building-a-web-service-consumer) + +[3.1 Reference Code [19](#reference-code-1)](#reference-code-1) + +[3.2 Design Choices [19](#design-choices-1)](#design-choices-1) + +[3.3 Security Requirements [19](#security-requirements-1)](#security-requirements-1) + +[3.4 WS-SecurityPolicy [19](#ws-securitypolicy)](#ws-securitypolicy) + +[3.4.1 Configuring WS-SecurityPolicy for the STS [19](#configuring-ws-securitypolicy-for-the-sts)](#configuring-ws-securitypolicy-for-the-sts) + +[3.4.2 Configuring WS-SecurityPolicy for the WSP [20](#configuring-ws-securitypolicy-for-the-wsp)](#configuring-ws-securitypolicy-for-the-wsp) + +[3.5 Configuring Keystores for the WSC [20](#configuring-keystores-for-the-wsc)](#configuring-keystores-for-the-wsc) + +[3.6 The STSClient Configuration and Implementation [21](#the-stsclient-configuration-and-implementation)](#the-stsclient-configuration-and-implementation) + +[3.7 Support Classes [22](#support-classes-1)](#support-classes-1) + +[3.8 Additional Configuration of Apache CXF [23](#additional-configuration-of-apache-cxf-1)](#additional-configuration-of-apache-cxf-1) + +[3.8.1 Configure BSP 1.1 Compliance [23](#configure-bsp-1.1-compliance-1)](#configure-bsp-1.1-compliance-1) + +[3.9 Other Considerations [23](#other-considerations-1)](#other-considerations-1) + +[4 Typical Errors [24](#typical-errors)](#typical-errors) + +[4.1 Java Strong Crypto Not Installed [24](#java-strong-crypto-not-installed)](#java-strong-crypto-not-installed) + +[4.2 A .keystore File in Home Folder [24](#a-.keystore-file-in-home-folder)](#a-.keystore-file-in-home-folder) + +[5 Summary [25](#summary)](#summary) + +[6 References [26](#references)](#references) + +# Changelog + +17-07-2018 Initial release + +# Introduction + +This document is a technical appendix to the Java reference source code, that showcases how to use the Apache CXF framework to implement various identity based webservices, following either the Liberty Basic SOAP Binding profile, the OIO IDWS Profile or the XUA variant of the OIO IDWS Profile. + +This document is derived from the original documentation for the NemLog-in2 reference implementation, but as there now exist several implemented profiles, the CXF and WS-SecurityPolicy specific parts of the implementation has been moved into this separate appendix, and the profile-specific documentation is left in the main documents. + +In this document it is assumed that the reader already possesses some background knowledge about federated security, and knows what Web Service Consumers (WSC), Web Service Providers (WSP), Service Providers (SP), Identity Providers (IdP) and Security Token Services (STS) are, and how they correspond to each other. Furthermore, it is assumed that the reader is familiar with the concepts of holder-of-key and bearer-tokens. + +## Intended audience + +This document is written for developers, and while all configuration and customization of Apache CXF concerning security is dealt with, some experience with Apache CXF or a similar web service framework is recommended. The reader is also expected to have experience with Java development in general. + +## Prerequisites + +The source code uses Apache Maven 3 \[MAVEN\] as a build tool, and the source code requires at least Java 7 with Strong Crypto \[CRYPTO\] to compile and run. The reader is expected to have these tools available before using the reference source code. Maven handles all other dependencies. + +## Apache CXF Version + +The reference code is based on Apache CXF 3.0.16, but the same concepts outlined in this document can be applied to the 3.1.x and 3.2.x branches of CXF. + +## Disclaimer + +The Danish Agency for Digitisation provides the reference code as is and assumes no responsibility for the code by service providers. Service Providers should understand the limitations of the code and deal with these according to their own needs. + +# Building a Web Service Provider + +This chapter covers all the steps necessary to secure a web service using Apache CXF. + +The reference source code is split into several subfolders, one for each profile. There exists a set of WSP reference implementations for each of these profiles. The approach to building them is identical, and there are only minor differences in the actual source/configuration. + +Currently the following profiles are available + +- **“lbsb-scenarios”**. This folder shows how to implement the Liberty Basic SOAP Binding using CXF and WS-SecurityPolicy + +- **“oioidws-scenarios”**. This folder shows how to implement the OIO IDWS 1.1 profile using CXF and WS-SecurityPolicy + +- **“oioidws-xua-scenarios”**. This folder shows how to implement the XUA variant of the OIO IDWS 1.1 profile using CXF and WS-SecurityPolicy + +## Hello World Service + +The reference source code is based on a very simple web service called HelloWorld, and all parts of the code are clearly packaged and commented, so those sections relevant to dealing with security are easily identified. + +Please note that the documentation covers two different versions of the same service. The first service accepts holder-of-key tokens and the second accepts bearer-tokens. The documentation will outline the difference in configuration and implementation between these two variants. + +The HelloWorld service has a single operation, that takes a text-string as input, and returns the corresponding “Hello \[input\]” text-string. + +## Reference Code + +The code for the Hello World service is found in the two folders “service-hok” and “service-bearer” found in each of the profile folders in the reference code distribution. + +The “service-hok” folder contains the code and configuration for the version of the service that accepts holder-of-key tokens, and the “service-bearer” folder contains the code and configuration for the version of the service that accepts bearer-tokens. + +The following chapters cover the steps necessary to build the holder-of-key version of the service, followed by a chapter that covers the set of modifications required to use bearer-tokens instead of holder-of-key tokens. + +## Design Choices + +In the reference source for the web service, a WSDL-first design approach has been chosen, as this is the recommended approach to building web services using Apache CXF. + +XML-based configuration has been chosen over code-based configuration, which ensures separation between code and configuration. Apache CXF depends on Spring for XML-based configuration. + +## Security Requirements + +The service must be configured to enforce validation of the client request according to the chosen security profile (e.g. OIO IDWS 1.1). + +Using Apache CXF this can be accomplished in two ways. The recommended way is to use WS-SecurityPolicy \[WS-SEC-POL\], and the alternate way is to use WSS4J Interceptors. We will use the recommended approach, and configure the service using WS-SecurityPolicy. + +The service must also be configured to trust at least one STS, which requires a keystore containing the STS certificate(s) to be configured as a truststore. + +## WS-SecurityPolicy Configuration + +WS-SecurityPolicy is a contract-based approach for dealing with security requirements. The WSDL of the service is extended with a wsp:Policy section, that describes the exact security policy that both the client and service must follow. + +This document is not a manual for using WS-SecurityPolicy, and it will only focus on describing the solution used in the reference source – for a more detailed description of WS-SecurityPolicy, please consult the standard \[WS-SEC-POL\]. + +A security policy is split into three parts + +- A general security policy that describes the tokens used as well as the processing and validation rules. + +- An input policy that describes the signing and encryption requirements that the client must follow when generating requests + +- An output policy that describes the signing and encryption requirements that the service must follow when generating responses + +### The General Security Policy + +In all the profiles covered by the reference code, an AsymmetricBinding policy is used. This type of policy covers the use-cases where the communicating parties have access to some asymmetric secret (e.g. certificates). The policy specifies how these asymmetric secrets are to be used. + +Besides the specification of the asymmetric binding, the policy can contain some generic settings (e.g. specify that WS-Adressing MUST be used), as well as information about any tokens that are to be used. + +The context in which the policy section is placed in the WSDL can be found in the file HelloWorld-Hok.wsdl (or HelloWorld-Bearer.wsdl) found in the src/main/resources folder of the service projects. + +If we look at the policies used in the reference code, they contain these three sections + +\ + +\ + +\ + +The first element enables WS-Addressing and should be set on profiles that require WS-Addressing (and can be set on profiles that do not explicitly prohibit WS-Addressing). Setting this will require the WSC to send WS-Addressing headers in any request sent to the WSP. + +The second element specifies the request/response tokens (the asymmetric secrets) to be used by the WSC and WSP, as well as a series of configuration settings that apply to this usage. + +Below are listed the elements that are used in the profiles implemented in the reference code. There are more settings available, please see \[WS-SEC-POL\] for details. + +\ + +\ + +\ + +\ + +\ + +\ + +\ + +The InitiatorToken and RecipientToken element specify the type of token that the WSC and WSP must use. The InitiatorToken specifies the type of key-material used for request signature and response encryption, and similarly, the RecipientToken element specify the type of key-material used for response signature and request encryption. + +Note that the term “token” covers both actual SAML tokens as well as certificates. The elements also specify whether the WSC/WSP should just use the token, or the token must also be included in the message sent to the other party. + +In general, if the message-receiver needs the token to validate the message, the policy should specify that the token must be included. Note that the various profiles usually govern exactly when a token must be included in the message. + +The AlgorithmSuite element describes which cryptographic algorithms the client and service must use when signing and encrypting data. Useful settings are (see \[WS-SEC-POL\] for a full list) + +- **Basic256**. RSA-SHA1 for signatures, AES-256 for encryption. + +- **Basic256Sha256**. RSA-SHA256 for signatures, AES-256 for encryption. + +The Layout element describes how header elements must be added to the Security header. This value is usually set to Strict, but Lax is allowed by some profiles. + +Adding the ProtectTokens element, requires that the Token Protection rules are followed by the WSC and WSP. The Token Protection rules states that any token used for generating signatures, must also be covered by the generated signature. + +The IncludeTimestamp element requires that both the WSC and the WSP must add a timestamp header to the messages being send. + +Finally, the OnlySignEntireHeadersAndBody element requires that the WSC and WSP must sign entire header elements and the entire body (if required by the input/output policy) and cannot sign only a part of a header or the body. + +The third element describes the supporting tokens (the token supplied by the STS) that the WSC must use when calling the service. Note that either a SignedSupportingToken or SupportingToken section can be used. SupportingToken(s) can be used in the Bearer case, otherwise a SignedSupportingToken is used. This section can be used to specify KeyType, TokenType and other attributes for the supporting token. + +### The Input Policy + +The input policy specifies which parts of the request generated by the WSC must be signed and which must be encrypted. The policy can reference specific headers as well as the body element, and specify individual rules for each header, as well as for the body element. + +In the WSDL, the input policy can then be applied to the individual operations as needed. + +The basic structure of the input policy contains a SignedParts and an EncryptedParts element, each indicating which elements should be signed or encrypted, + +\ + +\ + +The different policies implemented in the reference code each have rules regarding which fields are to be signed and which (if any) that need to be encrypted. + +### The Output Policy + +The output policy is similar to the input policy, with the sole difference that it specifies the rules for the response generated by the WSP. + +## Configuring Keystores for the Service + +The service must be configured with 2 keystores. One containing the service’s own certificate and corresponding private key and another containing only the certificate(s) of the trusted STSs. The latter is referred to as a truststore. + +Both JKS and PKCS12 keystore formats are supported by Apache CXF. + +Apache CXF must be configured to use these keystores, which is done by creating a property file with the relevant information, and then pointing CXF towards this property file. + +The property file uses the following settings – the values are examples taken from the reference code. + +org.apache.ws.security.crypto.merlin.keystore.type**=**jks + +org.apache.ws.security.crypto.merlin.keystore.password**=**Test1234 + +org.apache.ws.security.crypto.merlin.keystore.alias**=**server + +org.apache.ws.security.crypto.merlin.file**=**service.jks + +org.apache.ws.security.crypto.merlin.truststore.type**=**jks + +org.apache.ws.security.crypto.merlin.truststore.file**=**trust.jks + +org.apache.ws.security.crypto.merlin.truststore.password**=**Test1234 + +CXF must know about this property file, so it should be referenced from the main CXF configuration file – in the WSP this is called cxf-servlet.xml and is found under the webapp/WEB-INF folder. + +The “ws-security.signature.properties” property found I the cxf-servlet.xml file can be used to point to the keystore configuration file, as shown below. + +\ + +\ + +\ + +\ + +\ + +\ + +Note the reference to a callback-handler (ws-security.callback-handler). This is a reference to a Java class whose sole purpose is to supply the password to the server keystore. The Apache CXF framework uses the keystore in various places, and sometimes it looks up the password directly in the property file, and other times it requires that the password is supplied through a callback handler. Hence the keystore password needs to be supplied both in the property file and the callback handler. + +Below is shown the source from the callback handler in the reference code – in a real implementation, the password should not be hardcoded, but rather read from some external configuration file. + +public class KeystorePasswordCallback **implements** CallbackHandler **{** + +@Override + +public void handle**(**Callback**\[\]** callbacks**)** **throws** IOException**,** UnsupportedCallbackException **{** + +**for** **(**int i **=** 0**;** i **\<** callbacks**.**length**;** i**++)** **{** + +WSPasswordCallback pc **=** **(**WSPasswordCallback**)** callbacks**\[**i**\];** + +int usage **=** pc**.**getUsage**();** + +**if** **(**usage **==** WSPasswordCallback**.**DECRYPT **\|\|** + +usage **==** WSPasswordCallback**.**SIGNATURE**)** **{** + +pc**.**setPassword**(**"Test1234"**);** + +**}** + +**}** + +**}** + +**}** + +Once the property file and callback handler have been implemented, and the XML configuration updated, no further configuration is needed to ensure Apache CXF has access to the keystores. + +## Support Classes + +Apache CXF can deal with the standard cryptographic operations and SOAP headers like WS-Addressing, but custom headers, custom attributes or anything else that is not governed by the framework, requires additional code. + +Some examples of this are shown below + +### Dealing with custom headers + +Some profiles might require specific SOAP headers to be sent by the WSC to the WSP, and if these headers contain information that needs to be parsed (or they simply have a mustUnderstand=”1” attribute set), then custom handlers must be implemented to deal with this. + +If the WSC sends a header that the WSP must understand, an interceptor must be implemented that can deal with this header. The getUnderstoodHeaders() method should return the headers that the WSP can understand (the CXF framework will reject any incoming messages that contains headers with mustUnderstand=”1” that it does not understand). + +The example below flags the Framework header from the Liberty Basic SOAP Binding profile as a header it understands. + +public class UnderstandFrameworkHeaderInterceptor **extends** AbstractSoapInterceptor **{** + +private static final QName frameworkQName **=** **new** + +QName**(**"urn:liberty:sb"**,** "Framework"**,** "sbf"**);** + +public UnderstandFrameworkHeaderInterceptor**()** **{** + +**super(**Phase**.**PRE_PROTOCOL**);** + +**}** + +@Override + +public void handleMessage**(**SoapMessage message**)** **throws** Fault **{** + +Header framework **=** message**.**getHeader**(**frameworkQName**);** + +**if** **(**framework **==** **null)** **{** + +**throw** **new** XMLFault**(**"Missing framework header"**);** + +**}** + +**}** + +@Override + +public Set**\<**QName**\>** getUnderstoodHeaders**()** **{** + +Set**\<**QName**\>** set **=** **new** HashSet**\<\>();** + +set**.**add**(**frameworkQName**);** + +**return** set**;** + +**}** + +**}** + +The interceptor must be added in the cxf-servlet.xml configuration file, so CXF knows to use it. This is done by adding the interceptor as a configured bean, and then adding it to the bus element as shown below + +\ + +\ + +\ + +\ + +\ + +\ + +If the WSP must respond with custom headers, then a similar interceptor must be implemented and configured in cxf-servlet.xml. + +First generate a JAXB representation of the header, using the @Xml annotations in the Java language. This class can then be used to serialize and deserialize the XML headers. + +An example of such a header representation is shown below – in this case the Framework Header required by the Liberty Basic SOAP Binding profile. + +@XmlAccessorType**(**XmlAccessType**.**FIELD**)** + +public class SbfFrameworkHeader **{** + +@XmlAttribute**(**name**=**"version"**)** + +private final String version **=** "2.0"**;** + +@XmlAttribute**(**name**=**"profile"**,** namespace**=**"urn:liberty:sb:profile"**)** + +private final String profile **=** "urn:liberty:sb:profile:basic"**;** + +public String getVersion**()** **{** + +**return** version**;** + +**}** + +public String getProfile**()** **{** + +**return** profile**;** + +**}** + +**}** + +An interceptor that deals with this specific header should then be implemented, where the handleMessage() method generates the required header and adds it to the output + +public class FrameworkHeaderInterceptor **extends** AbstractSoapInterceptor **{** + +public FrameworkHeaderInterceptor**()** **{** + +**super(**Phase**.**PRE_PROTOCOL**);** + +**}** + +@Override + +public void handleMessage**(**SoapMessage message**)** **throws** Fault **{** + +List**\<**Header**\>** headers **=** message**.**getHeaders**();** + +**try** **{** + +Header framework **=** **new** SoapHeader**(** + +**new** QName**(**"urn:liberty:sb"**,** "Framework"**,** "sbf"**),** + +**new** SbfFrameworkHeader**(),** + +**new** JAXBDataBinding**(**SbfFrameworkHeader**.**class**));** + +headers**.**add**(**framework**);** + +**}** + +**catch** **(**Exception ex**)** **{** + +**throw** **new** XMLFault**(**ex**.**getMessage**());** + +**}** + +message**.**put**(**Header**.**HEADER_LIST**,** headers**);** + +**}** + +**}** + +Finally, we need to configure this interceptor, which is done in the cxf-servlet.xml file. The relevant part of the XML configuration file is shown below – note that the header can be configured to be added to both regular responses, as well as fault responses. + +\ + +\ + +\ + +\ + +\ + +\ + +\ + +\ + +\ + +### Pulling data from incoming token and storing for later access + +When the WSP receives a request from the WSC, CXF will validate the security of incoming request, up to and including the validity of the token. + +What CXF will not do, is look in the attributes of the token, and make authorization decision based on these attributes. + +If the supplied token is used for more than just access=yes/no, and contains additional information that the WSP needs to make authorization decisions, then the incoming token should be parsed, and the relevant information made available to the parts of the WSP code that makes these decisions. + +The approach outlined below, parses the incoming token, and pulls the relevant information into a ThreadLocal, making the information globally accessible in the WSP code. Depending on the type of security framework used, it might make better sense to push the information into whatever security framework is used – the general concept outline below can be adapted to such a purpose, but that is out of scope for this document. + +To implement this functionality, three support classes are needed. A class to hold the ThreadLocal (PriviligeHolder.java), a class to clean up the ThreadLocal once the request has been processed (SamlTokenFilter.java) and finally a class to parse the attribute in the token (SamlTokenValidator.java). + +The first class is an ordinary ThreadLocal holder, which stores instances of the class PrivilgeListType (a class used to represent an OIO-BPP set of privilege issued by the NemLog-in STS). This holder can be adapted to store whatever information is relevant about the WSC. + +public class PriviligeHolder **{** + +private static final ThreadLocal**\<**PrivilegeListType**\>** privileges **=** **new** ThreadLocal**\<\>();** + +public static void set**(**PrivilegeListType privilege**)** **{** + +privileges**.**set**(**privilege**);** + +**}** + +public static PrivilegeListType get**()** **{** + +**return** privileges**.**get**();** + +**}** + +public static void clear**()** **{** + +privileges**.**remove**();** + +**}** + +**}** + +The second class is a very simple servlet filter, whose sole purpose is to ensure that the above ThreadLocal holder is cleared once the request has been processed. It is shown below for completeness: + +public class SamlTokenFilter **implements** Filter **{** + +@Override + +public void init**(**FilterConfig filterConfig**)** + +**throws** ServletException **{** **}** + +@Override + +public void doFilter**(**ServletRequest request**,** + +ServletResponse response**,** + +FilterChain chain**)** + +**throws** IOException**,** ServletException **{** + +**try** **{** + +chain**.**doFilter**(**request**,** response**);** + +**}** + +**finally** **{** + +PriviligeHolder**.**clear**();** + +**}** + +**}** + +@Override + +public void destroy**()** **{** **}** + +**}** + +As with all servlet filters, it must be configured to intercept requests to the application. As the reference source code is packaged as a WAR file, this is done in the web.xml file in the ordinary way. The relevant parts of the web.xml file are shown below for completeness. + +\ + +\**SamlTokenFilter**\ + +\**service.saml.SamlTokenFilter**\ + +\ + +\ + +\**SamlTokenFilter**\ + +\**\***\ + +\ + +The final class extends the CXF SamlAssertionValidator class, and must implement the validate() method – it receives the incoming SAML token after CXF is done parsing it, and we can then use the validate() method to pull any relevant information from the SAML token. In the example below, the code attempts to parse the Privileges attribute in the SAML token (the attribute used by the NemLog-in STS to issue roles to a WSC). + +public class SamlTokenValidator **extends** SamlAssertionValidator **{** + +@SuppressWarnings**(**"unchecked"**)** + +@Override + +public Credential validate**(**Credential credential**,** + +RequestData data**)** + +**throws** WSSecurityException **{** + +Credential vCredential **=** **super.**validate**(**credential**,** data**);** + +SamlAssertionWrapper samlAssertion **=** + +credential**.**getSamlAssertion**();** + +**if** **(**samlAssertion**.**getSaml2**()** **!=** **null)** **{** + +Assertion saml2 **=** samlAssertion**.**getSaml2**();** + +**for** **(**AttributeStatement attributeStatement **:** + +saml2**.**getAttributeStatements**())** **{** + +**for** **(**Attribute attribute **:** + +attributeStatement**.**getAttributes**())** **{** + +**if** **(**"Privileges"**.**equals**(** + +attribute**.**getFriendlyName**()))** **{** + +**for** **(**XMLObject attributeValue **:** + +attribute**.**getAttributeValues**())** **{** + +**if** **(!**attributeValue.isNil()) **{** + +String privilege **=** + +attributeValue**.**getDOM**().**getTextContent**();** + +byte**\[\]** privilegeBytes **=** + +Base64**.**decodeBase64**(**privilege**);** + +**try** **{** + +JAXBContext context **=** + +JAXBContext**.**newInstance**(**ObjectFactory**.**class**);** + +Unmarshaller unmarsheller **=** + +context**.**createUnmarshaller**();** + +JAXBElement**\<**PrivilegeListType**\>** privilegeList **=** **(**JAXBElement**\<**PrivilegeListType**\>)** unmarsheller**.**unmarshal**(new** ByteArrayInputStream**(**privilegeBytes**));** + +PriviligeHolder**.**set**(** + +privilegeList**.**getValue**());** + +**}** + +**catch** **(**Exception ex**)** **{** + +**throw** **new** WSSecurityException**(** + +WSSecurityException**.**ErrorCode**.**FAILURE**,** "invalidSAMLsecurity"**,** ex**);** + +**}** + +**}** + +**}** + +**}** + +**}** + +**}** + +**}** + +**return** vCredential**;** + +**}** + +**}** + +The SamlTokenValidator class must be configured to be used by the Apache CXF framework. This is done in the cxf-servlet.xml configuration file. The relevant parts of the configuration file are shown below + +\ + +\ + +\ + +\ + +\ + +At any given point in the WSP code, the PriviligeHolders get() method can then be used to access the stored information about the WSC. + +## Additional Configuration of Apache CXF + +There are a few more configuration steps that are needed before the service is ready to be deployed. The Audience Restriction of the token must be properly validated, it should be validated that the clients request is no older than say 5 minutes, and finally we may need to configure Apache CXF to accept that the token issued by the STS is not Basic Security Profile (BSP) 1.1 compliant. + +### Validating Audience Restriction + +The token issued by the STS contains an element, called the Audience, that tells which service this token is intended for (an EntityId value). This element must be validated, to ensure that the client (or some other party) is not using a token intended for another service. By default, the Apache CXF framework will validate the value found in the token against the hostname that the service is deployed on as well as the QName of the service. As this is not always the EntityId that the service is registered under, the reference code contains code that adds an additional EntityId to the list that the token’s Audience is validated against. + +The SamlTokenValidator found above can be used for performing this validation. We need a List of allowed audiences, so for instance, if we allow tokens issued to to be used, then the code below could be used to create such a list. + +private List**\<**String**\>** audienceRestrictions **=** **new** ArrayList**\<**String**\>()** **{** + +private static final long serialVersionUID **=** 1L**;** + +**{** + +add**(**"https://wsp.itcrew.dk"**);** + +**}** + +**};** + +Then before we call super.validate() in our own class’s validate() method, we set this list as the allowed set of audiences, overwriting CXFs default validation. + +@SuppressWarnings**(**"unchecked"**)** + +@Override + +public Credential validate**(**Credential credential**,** RequestData data**)** **throws** WSSecurityException **{** + +// Set the valid audiences for this request + +data**.**setAudienceRestrictions**(**audienceRestrictions**);** + +Credential validatedCredential **=** **super.**validate**(**credential**,** data**);** + +SamlAssertionWrapper samlAssertion **= ...** + +### Configure TimeToLive + +By default, the Apache CXF framework will not accept messages that are older than 5 minutes, but if a different time period is required, this can be configured in the cxf-servlet.xml configuration file by setting the following property (the value is in seconds, so 300 = 5 minutes) + +\ + +\ + +\ + +\ + +\ + +### Configure BSP 1.1 Compliance + +The Apache CXF framework enforces Basic Security Profile 1.1 compliance by default, and as CXF does not have full support for encrypted tokens, this causes some validation errors to occur during BSP 1.1 compliance checking if such are used. If needed, BSP validation can be disabled; this is done in the cxf-servlet.xml configuration file, and the relevant settings are shown below. + +\ + +\ + +\ + +\ + +\ + +## The bearer-token version of the service + +A bearer token simply grants the WSC the identity and privileges indicated by the token, without requiring the WSC to prove that it is the rightful bearer of the token (possession of the token is enough). + +The implementation notes above all cover the case for implementing a WSP that accepts holder-of-key tokens, but the changes required to accept bearer tokens are minimal and are covered in this section. + +Before making the changes, consider whether the WSC should still sign the message, or is the bearer token enough on its own? The WSC can still sign the message (allowing for message integrity and non-repudiation), but the supplied token is not used in the signature validation process, so the identity supplied by the token is not associated with the signature validation process (which is considered a feature in some cases). + +This choice depends on the implementation profile, and for instance the Liberty Basic SOAP Binding profile requires a signature when using bearer tokens. + +Assuming the previous steps in this chapter have been implemented, the following modifications are required to implement bearer tokens. + +### Modify the WS-SecurityPolicy + +As the WSC calling the WSP only supplies a bearer-token, we need to ensure that the client supplies its certificate (if the message needs to be signed, or the response needs to be encrypted), this is done by changing this section of the WSDL file + +\http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never"**\> + +\ + +\ + +\ + +\ + +To the following + +\http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient"**\> + +\ + +\ + +\ + +\ + +This will require the WSC to supply its certificate in the request to the service. + +We also need to empty the inner wsp:Policy section from the SignedSupportingToken element, otherwise CXF will attempt to use the token instead of the certificate. + +Note that if the profile does not mandate that the bearer token should be signed by the WSC, then a SupportingTokens section can be used instead of a SignedSupportingTokens section. + +\http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702"**\> + +\ + +\http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient"**\> + +\ + +\ + +\ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/bootstrap-scenario/oiosaml-config/oiosaml-sp.properties b/examples/lbsb/bootstrap-scenario/oiosaml-config/oiosaml-sp.properties deleted file mode 100644 index c18ec36..0000000 --- a/examples/lbsb/bootstrap-scenario/oiosaml-config/oiosaml-sp.properties +++ /dev/null @@ -1,28 +0,0 @@ -# Properties used by oiosaml-j - -# Reference to the location of the certificate used for signing SAML documents with - relative to ${oiosaml.home} -oiosaml-sp.certificate.location=./certificate/keystore - -# Opaque/encrypted password to the certificate used for signing SAML documents -oiosaml-sp.certificate.password=Test1234 - -# Required authentication level. 2=password, 3=certificate -oiosaml-sp.assurancelevel=2 - -# Name of the meta data file for the current service provider - overrides setting in brs-common.properties -common.saml2.metadata.sp.filename=SPMetadata.xml - -# URI References to the current service provider -oiosaml-sp.uri.home=/cxf-sp-ws-consumer - -# Force login -#oiosaml-sp.authn.force=/login - -# OCSP validation. -#oiosaml-sp.crl.ocsp.ca=https://www.certifikat.dk/export/sites/dk.certifikat.oc/da/developer/eksempler/oces_I_eksempler/oces_I_certifikater/tdc_systemtest_2.cer -#oiosaml-sp.crl.ocsp.responder=http://test.ocsp.certifikat.dk/ocsp/status - -# disable revocation -oiosaml-sp.crl.period=0 - -oiosaml-sp.signature.algorithm=http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 diff --git a/examples/lbsb/bootstrap-scenario/pom.xml b/examples/lbsb/bootstrap-scenario/pom.xml deleted file mode 100644 index 3591244..0000000 --- a/examples/lbsb/bootstrap-scenario/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-lbsb-parent - 1.0.0-SNAPSHOT - - war - cxf-wsc-lbsb-bootstrap - CXF WS Consumer for Bootstrap Scenario (LBSB) - - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - - 8094 - 8095 - ${project.basedir}/ssl-keystore - Test1234 - - - - - org.apache.cxf - cxf-codegen-plugin - - - commons-logging - commons-logging - 1.1.1 - - - - - - - ${basedir}/target/generated-sources - - - - - ${basedir}/src/main/resources/HelloWorld-Hok.wsdl - - classpath:HelloWorld-Hok.wsdl - - - - - - - - - cxf-sp-ws-consumer - - - - - - org.apache.santuario - xmlsec - 2.1.4 - - - - dk.digst - oiosaml2.java - 2.0.8 - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - org.apache.cxf - cxf-rt-transports-http - - - - org.apache.cxf - cxf-rt-ws-security - - - - commons-io - commons-io - - - - org.springframework - spring-context - - - - org.slf4j - slf4j-jdk14 - - - - javax.servlet - servlet-api - provided - - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/client/callback/ClientCallbackHandler.java b/examples/lbsb/bootstrap-scenario/src/main/java/client/callback/ClientCallbackHandler.java deleted file mode 100644 index 58fbb49..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/client/callback/ClientCallbackHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package client.callback; - -import java.io.IOException; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.wss4j.common.ext.WSPasswordCallback; - -public class ClientCallbackHandler implements CallbackHandler { - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (int i = 0; i < callbacks.length; i++) { - if (callbacks[i] instanceof WSPasswordCallback) { - WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; - - if (pc.getUsage() == WSPasswordCallback.DECRYPT || pc.getUsage() == WSPasswordCallback.SIGNATURE) { - pc.setPassword("Test1234"); - } - } - } - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java b/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java deleted file mode 100644 index 9901ceb..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package client.interceptor; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapHeader; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; - -import client.model.SbfFrameworkHeader; - -public class FrameworkHeaderInterceptor extends AbstractSoapInterceptor { - public FrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - try { - Header framework = new SoapHeader(new QName("urn:liberty:sb", "Framework", "sbf"), new SbfFrameworkHeader(), new JAXBDataBinding(SbfFrameworkHeader.class)); - headers.add(framework); - } - catch (Exception ex) { - throw new XMLFault(ex.getMessage()); - } - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java b/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java deleted file mode 100644 index 75e1a01..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java +++ /dev/null @@ -1,62 +0,0 @@ -package client.interceptor; - -import java.util.List; -import java.util.UUID; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; -import org.apache.cxf.ws.addressing.AttributedURIType; -import org.apache.cxf.ws.addressing.ObjectFactory; - -public class STSAddressingInterceptor extends AbstractSoapInterceptor { - public STSAddressingInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - ObjectFactory wsAddressingFactory = new ObjectFactory(); - - AttributedURIType to = new AttributedURIType(); - AttributedURIType messageId = new AttributedURIType(); - AttributedURIType action = new AttributedURIType(); - - // OBS! the url must end with / otherwise the STS will reject the call (this differs from the documentation on the STS) - to.setValue("https://bootstrap.sts.nemlog-in.dk/"); - action.setValue("http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); - messageId.setValue("uuid:" + UUID.randomUUID().toString()); - - JAXBElement createTo = wsAddressingFactory.createTo(to); - JAXBElement msgId = wsAddressingFactory.createMessageID(messageId); - JAXBElement newAction = wsAddressingFactory.createAction(action); - - JAXBDataBinding jaxbDataBinding = null; - try { - jaxbDataBinding = new JAXBDataBinding(AttributedURIType.class); - } - catch (JAXBException ex) { - throw new XMLFault(ex.getMessage()); - } - - Header toHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), createTo, jaxbDataBinding); - Header msgIdHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), msgId, jaxbDataBinding); - Header actionHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), newAction, jaxbDataBinding); - - headers.add(actionHeader); - headers.add(msgIdHeader); - headers.add(toHeader); - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/client/model/SbfFrameworkHeader.java b/examples/lbsb/bootstrap-scenario/src/main/java/client/model/SbfFrameworkHeader.java deleted file mode 100644 index 0784fba..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/client/model/SbfFrameworkHeader.java +++ /dev/null @@ -1,23 +0,0 @@ -package client.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; - -@XmlAccessorType(XmlAccessType.FIELD) -public class SbfFrameworkHeader { - - @XmlAttribute(name="version") - private final String version = "2.0"; - - @XmlAttribute(name="profile", namespace="urn:liberty:sb:profile") - private final String profile = "urn:liberty:sb:profile:basic"; - - public String getVersion() { - return version; - } - - public String getProfile() { - return profile; - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/client/sts/DigstSTSClient.java b/examples/lbsb/bootstrap-scenario/src/main/java/client/sts/DigstSTSClient.java deleted file mode 100644 index a14ac0c..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/client/sts/DigstSTSClient.java +++ /dev/null @@ -1,62 +0,0 @@ -package client.sts; - -import java.nio.charset.Charset; -import java.util.UUID; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import org.apache.commons.codec.binary.Base64; -import org.apache.cxf.Bus; -import org.apache.cxf.ws.security.trust.STSClient; -import org.w3c.dom.Element; - -import client.interceptor.STSAddressingInterceptor; -import dk.itst.oiosaml.sp.UserAssertion; -import dk.itst.oiosaml.sp.UserAssertionHolder; -import dk.itst.oiosaml.sp.UserAttribute; - -public class DigstSTSClient extends STSClient { - public DigstSTSClient(Bus b) { - super(b); - - this.out.add(new STSAddressingInterceptor()); - - createUniqueContextAttribute(); - } - - @Override - protected void addAppliesTo(XMLStreamWriter writer, String appliesTo) throws XMLStreamException { - createUniqueContextAttribute(); - - if (appliesTo != null && addressingNamespace != null) { - // modified the namespace so it uses ws-policy 1.1 namespace (not supported by CXF, so we have to do this hacky thing) - writer.writeStartElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeNamespace("wsp", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeStartElement("wsa", "EndpointReference", addressingNamespace); - writer.writeNamespace("wsa", addressingNamespace); - writer.writeStartElement("wsa", "Address", addressingNamespace); - writer.writeCharacters(appliesTo); - writer.writeEndElement(); - writer.writeEndElement(); - writer.writeEndElement(); - } - } - - @Override - public Element getActAsToken() throws Exception { - // grab the IdP supplied token from the UserAssertionHolder and copy the relevant attribute into the ActAs field in the STS request - UserAssertion userAssertion = UserAssertionHolder.get(); - UserAttribute attribute = userAssertion.getAttribute("urn:liberty:disco:2006-08:DiscoveryEPR"); - byte[] rawAssertion = Base64.decodeBase64(attribute.getValue()); - - String actAsToken = new String(rawAssertion, Charset.forName("UTF-8")); - - return getDelegationSecurityToken(actAsToken); - } - - // we are required to set a unique @Context attribute on the request - private void createUniqueContextAttribute() { - this.context = "urn:uuid:" + UUID.randomUUID().toString(); - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java b/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java deleted file mode 100644 index 3c4724a..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java +++ /dev/null @@ -1,2273 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.cxf.ws.security.wss4j.policyhandlers; - -import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.callback.CallbackHandler; -import javax.xml.crypto.dsig.Reference; -import javax.xml.namespace.QName; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPHeader; -import javax.xml.soap.SOAPMessage; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.apache.cxf.Bus; -import org.apache.cxf.attachment.AttachmentUtil; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.saaj.SAAJUtils; -import org.apache.cxf.common.classloader.ClassLoaderUtils; -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.endpoint.Endpoint; -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.helpers.DOMUtils; -import org.apache.cxf.helpers.MapNamespaceContext; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.message.MessageUtils; -import org.apache.cxf.resource.ResourceManager; -import org.apache.cxf.service.model.EndpointInfo; -import org.apache.cxf.staxutils.StaxUtils; -import org.apache.cxf.staxutils.W3CDOMStreamWriter; -import org.apache.cxf.ws.policy.AssertionInfo; -import org.apache.cxf.ws.policy.AssertionInfoMap; -import org.apache.cxf.ws.policy.PolicyConstants; -import org.apache.cxf.ws.security.SecurityConstants; -import org.apache.cxf.ws.security.tokenstore.SecurityToken; -import org.apache.cxf.ws.security.tokenstore.TokenStore; -import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler; -import org.apache.cxf.ws.security.wss4j.WSS4JUtils; -import org.apache.cxf.wsdl.WSDLConstants; -import org.apache.neethi.Assertion; -import org.apache.wss4j.common.WSEncryptionPart; -import org.apache.wss4j.common.crypto.Crypto; -import org.apache.wss4j.common.crypto.CryptoFactory; -import org.apache.wss4j.common.crypto.CryptoType; -import org.apache.wss4j.common.derivedKey.ConversationConstants; -import org.apache.wss4j.common.ext.WSPasswordCallback; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.common.principal.UsernameTokenPrincipal; -import org.apache.wss4j.common.saml.SAMLCallback; -import org.apache.wss4j.common.saml.SAMLUtil; -import org.apache.wss4j.common.saml.SamlAssertionWrapper; -import org.apache.wss4j.common.util.Loader; -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSSConfig; -import org.apache.wss4j.dom.WSSecurityEngineResult; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.handler.WSHandlerConstants; -import org.apache.wss4j.dom.handler.WSHandlerResult; -import org.apache.wss4j.dom.message.WSSecBase; -import org.apache.wss4j.dom.message.WSSecDKSign; -import org.apache.wss4j.dom.message.WSSecEncryptedKey; -import org.apache.wss4j.dom.message.WSSecHeader; -import org.apache.wss4j.dom.message.WSSecSignature; -import org.apache.wss4j.dom.message.WSSecSignatureConfirmation; -import org.apache.wss4j.dom.message.WSSecTimestamp; -import org.apache.wss4j.dom.message.WSSecUsernameToken; -import org.apache.wss4j.dom.message.token.BinarySecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; -import org.apache.wss4j.policy.SPConstants; -import org.apache.wss4j.policy.SPConstants.IncludeTokenType; -import org.apache.wss4j.policy.model.AbstractBinding; -import org.apache.wss4j.policy.model.AbstractSecurityAssertion; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding.ProtectionOrder; -import org.apache.wss4j.policy.model.AbstractToken; -import org.apache.wss4j.policy.model.AbstractToken.DerivedKeys; -import org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType; -import org.apache.wss4j.policy.model.AsymmetricBinding; -import org.apache.wss4j.policy.model.Attachments; -import org.apache.wss4j.policy.model.ContentEncryptedElements; -import org.apache.wss4j.policy.model.EncryptedElements; -import org.apache.wss4j.policy.model.EncryptedParts; -import org.apache.wss4j.policy.model.Header; -import org.apache.wss4j.policy.model.IssuedToken; -import org.apache.wss4j.policy.model.KerberosToken; -import org.apache.wss4j.policy.model.KeyValueToken; -import org.apache.wss4j.policy.model.Layout.LayoutType; -import org.apache.wss4j.policy.model.SamlToken; -import org.apache.wss4j.policy.model.SamlToken.SamlTokenType; -import org.apache.wss4j.policy.model.SecureConversationToken; -import org.apache.wss4j.policy.model.SecurityContextToken; -import org.apache.wss4j.policy.model.SignedElements; -import org.apache.wss4j.policy.model.SignedParts; -import org.apache.wss4j.policy.model.SpnegoContextToken; -import org.apache.wss4j.policy.model.SupportingTokens; -import org.apache.wss4j.policy.model.SymmetricBinding; -import org.apache.wss4j.policy.model.UsernameToken; -import org.apache.wss4j.policy.model.Wss10; -import org.apache.wss4j.policy.model.Wss11; -import org.apache.wss4j.policy.model.X509Token; -import org.apache.wss4j.policy.model.X509Token.TokenType; -import org.opensaml.common.SAMLVersion; - -/** - * - */ -public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandler { - public static final String CRYPTO_CACHE = "ws-security.crypto.cache"; - protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBindingBuilder.class); - - protected AbstractSymmetricAsymmetricBinding.ProtectionOrder protectionOrder = - AbstractSymmetricAsymmetricBinding.ProtectionOrder.SignBeforeEncrypting; - - protected final WSSConfig wssConfig; - protected SOAPMessage saaj; - protected WSSecHeader secHeader; - protected AssertionInfoMap aim; - protected AbstractBinding binding; - protected WSSecTimestamp timestampEl; - protected String mainSigId; - protected List sigConfList; - - protected Set encryptedTokensList = new HashSet(); - - protected List signatures = new ArrayList(); - - protected Element bottomUpElement; - protected Element topDownElement; - protected Element bstElement; - protected Element lastEncryptedKeyElement; - protected boolean storeBytesInAttachment; - - private Element lastSupportingTokenElement; - private Element lastDerivedKeyElement; - - private List suppTokenParts = new ArrayList(); - private List endSuppTokList; - private List sgndEndSuppTokList; - - public AbstractBindingBuilder( - WSSConfig config, - AbstractBinding binding, - SOAPMessage saaj, - WSSecHeader secHeader, - AssertionInfoMap aim, - SoapMessage message) { - super(message); - this.wssConfig = config; - this.binding = binding; - this.aim = aim; - this.secHeader = secHeader; - this.saaj = saaj; - message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures); - - boolean storeBytes = - MessageUtils.getContextualBoolean( - message, SecurityConstants.STORE_BYTES_IN_ATTACHMENT, false - ); - if (storeBytes && AttachmentUtil.isMtomEnabled(message)) { - storeBytesInAttachment = true; - if (binding instanceof AbstractSymmetricAsymmetricBinding - && (ProtectionOrder.EncryptBeforeSigning - == ((AbstractSymmetricAsymmetricBinding)binding).getProtectionOrder() - || ((AbstractSymmetricAsymmetricBinding)binding).isProtectTokens())) { - LOG.fine("Disabling SecurityConstants.STORE_BYTES_IN_ATTACHMENT due to " - + "EncryptBeforeSigning or ProtectTokens policy."); - storeBytesInAttachment = false; - } - } - - } - - protected void insertAfter(Element child, Element sib) { - if (sib.getNextSibling() == null) { - secHeader.getSecurityHeader().appendChild(child); - } else { - secHeader.getSecurityHeader().insertBefore(child, sib.getNextSibling()); - } - } - - protected void addDerivedKeyElement(Element el) { - if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addEncryptedKeyElement(Element el) { - if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (lastDerivedKeyElement != null) { - secHeader.getSecurityHeader().insertBefore(el, lastDerivedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addSupportingElement(Element el) { - if (lastSupportingTokenElement != null) { - insertAfter(el, lastSupportingTokenElement); - } else if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (bottomUpElement != null) { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastSupportingTokenElement = el; - } - - protected void insertBeforeBottomUp(Element el) { - if (bottomUpElement == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } - bottomUpElement = el; - } - - protected void addTopDownElement(Element el) { - if (topDownElement == null) { - if (secHeader.getSecurityHeader().getFirstChild() == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } - } else { - insertAfter(el, topDownElement); - } - topDownElement = el; - } - - protected final Map getCryptoCache() { - EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo(); - synchronized (info) { - Map o = - CastUtils.cast((Map)message.getContextualProperty(CRYPTO_CACHE)); - if (o == null) { - o = CastUtils.cast((Map)info.getProperty(CRYPTO_CACHE)); - } - if (o == null) { - o = new ConcurrentHashMap(); - info.setProperty(CRYPTO_CACHE, o); - } - return o; - } - } - - protected final TokenStore getTokenStore() { - return WSS4JUtils.getTokenStore(message); - } - - protected WSSecTimestamp createTimestamp() { - if (binding.isIncludeTimestamp()) { - Object o = message.getContextualProperty(SecurityConstants.TIMESTAMP_TTL); - int ttl = 300; //default is 300 seconds - if (o instanceof Number) { - ttl = ((Number)o).intValue(); - } else if (o instanceof String) { - ttl = Integer.parseInt((String)o); - } - if (ttl <= 0) { - ttl = 300; - } - timestampEl = new WSSecTimestamp(wssConfig); - timestampEl.setTimeToLive(ttl); - timestampEl.prepare(saaj.getSOAPPart()); - - Collection ais = getAllAssertionsByLocalname(SPConstants.INCLUDE_TIMESTAMP); - for (AssertionInfo ai : ais) { - ai.setAsserted(true); - } - } - return timestampEl; - } - - protected WSSecTimestamp handleLayout(WSSecTimestamp timestamp) { - if (binding.getLayout() != null) { - Collection ais = getAllAssertionsByLocalname(SPConstants.LAYOUT); - AssertionInfo ai = null; - for (AssertionInfo layoutAi : ais) { - layoutAi.setAsserted(true); - ai = layoutAi; - } - - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_LAST + " requires a timestamp"); - } else { - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_LAST)); - Element el = timestamp.getElement(); - secHeader.getSecurityHeader().appendChild(el); - if (bottomUpElement == null) { - bottomUpElement = el; - } - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST + " requires a timestamp"); - } else { - addTopDownElement(timestampEl.getElement()); - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST)); - } - } else if (timestampEl != null) { - if (ai != null) { - ai.setAsserted(true); - } - addTopDownElement(timestampEl.getElement()); - } else if (ai != null) { - ai.setAsserted(true); - } - - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_LAX)); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_STRICT)); - } else if (timestampEl != null) { - addTopDownElement(timestampEl.getElement()); - } - return timestamp; - } - - protected void reshuffleTimestamp() { - // Make sure that the Timestamp is in first place, if that is what the policy requires - if (binding.getLayout() != null && timestampEl != null) { - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst - && secHeader.getSecurityHeader().getFirstChild() != timestampEl.getElement()) { - Node firstChild = secHeader.getSecurityHeader().getFirstChild(); - while (firstChild != null && firstChild.getNodeType() != Node.ELEMENT_NODE) { - firstChild = firstChild.getNextSibling(); - } - if (firstChild != null && firstChild != timestampEl.getElement()) { - secHeader.getSecurityHeader().insertBefore(timestampEl.getElement(), firstChild); - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast - && secHeader.getSecurityHeader().getLastChild() != timestampEl.getElement()) { - secHeader.getSecurityHeader().appendChild(timestampEl.getElement()); - } - } - } - - private List handleSupportingTokens( - Collection tokensInfos, - boolean endorse - ) throws WSSecurityException { - List ret = new ArrayList(); - if (tokensInfos != null) { - for (AssertionInfo assertionInfo : tokensInfos) { - if (assertionInfo.getAssertion() instanceof SupportingTokens) { - assertionInfo.setAsserted(true); - try { - handleSupportingTokens((SupportingTokens)assertionInfo.getAssertion(), endorse, ret); - } catch (SOAPException ex) { - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); - } - } - } - } - return ret; - } - - protected List handleSupportingTokens( - SupportingTokens suppTokens, - boolean endorse, - List ret - ) throws WSSecurityException, SOAPException { - if (suppTokens == null) { - return ret; - } - for (AbstractToken token : suppTokens.getTokens()) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - // Check for any SignedParts so as *not* to sign them - getSignedParts(suppTokens); - continue; - } - if (token instanceof UsernameToken) { - handleUsernameTokenSupportingToken( - (UsernameToken)token, endorse, suppTokens.isEncryptedToken(), ret - ); - } else if (token instanceof IssuedToken - || token instanceof SecureConversationToken - || token instanceof SecurityContextToken - || token instanceof KerberosToken - || token instanceof SpnegoContextToken) { - //ws-trust/ws-sc stuff....... - SecurityToken secToken = getSecurityToken(); - if (secToken == null) { - policyNotAsserted(token, "Could not find IssuedToken"); - } - Element clone = cloneElement(secToken.getToken()); - secToken.setToken(clone); - addSupportingElement(clone); - - String id = secToken.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(id, "Element"); - part.setElement(clone); - encryptedTokensList.add(part); - } - - if (secToken.getX509Certificate() == null) { - ret.add( - new SupportingToken(token, new WSSecurityTokenHolder(wssConfig, secToken), - getSignedParts(suppTokens)) - ); - } else { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setX509Certificate(secToken.getX509Certificate()); - sig.setCustomTokenId(id); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - String tokenType = secToken.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - - Crypto crypto = secToken.getCrypto(); - String uname = null; - try { - uname = crypto.getX509Identifier(secToken.getX509Certificate()); - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - - String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(uname, password); - try { - sig.prepare(saaj.getSOAPPart(), secToken.getCrypto(), secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - throw new Fault(e); - } - - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } - - } else if (token instanceof X509Token) { - //We have to use a cert. Prepare X509 signature - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - Element bstElem = sig.getBinarySecurityTokenElement(); - if (bstElem != null) { - if (lastEncryptedKeyElement != null) { - if (lastEncryptedKeyElement.getNextSibling() != null) { - secHeader.getSecurityHeader().insertBefore(bstElem, - lastEncryptedKeyElement.getNextSibling()); - } else { - secHeader.getSecurityHeader().appendChild(bstElem); - } - } else { - sig.prependBSTElementToHeader(secHeader); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - part.setElement(bstElem); - encryptedTokensList.add(part); - } - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof KeyValueToken) { - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - encryptedTokensList.add(part); - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof SamlToken) { - SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken)token); - if (assertionWrapper != null) { - Element assertionElement = assertionWrapper.toDOM(saaj.getSOAPPart()); - addSupportingElement(assertionElement); - ret.add(new SupportingToken(token, assertionWrapper, getSignedParts(suppTokens))); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(assertionWrapper.getId(), "Element"); - part.setElement(assertionElement); - encryptedTokensList.add(part); - } - } - } - } - - return ret; - } - - protected void handleUsernameTokenSupportingToken( - UsernameToken token, boolean endorse, boolean encryptedToken, List ret - ) throws WSSecurityException { - if (endorse) { - WSSecUsernameToken utBuilder = addDKUsernameToken(token, true); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - if (encryptedToken) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } else { - WSSecUsernameToken utBuilder = addUsernameToken(token); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - //WebLogic and WCF always encrypt these - //See: http://e-docs.bea.com/wls/docs103/webserv_intro/interop.html - //encryptedTokensIdList.add(utBuilder.getId()); - if (encryptedToken - || MessageUtils.getContextualBoolean(message, - SecurityConstants.ALWAYS_ENCRYPT_UT, - true)) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } - } - - protected Element cloneElement(Element el) { - Document doc = secHeader.getSecurityHeader().getOwnerDocument(); - if (!doc.equals(el.getOwnerDocument())) { - - XMLStreamReader reader = StaxUtils.createXMLStreamReader(el); - DocumentFragment fragment = doc.createDocumentFragment(); - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(fragment); - try { - StaxUtils.copy(reader, writer); - return (Element)fragment.getFirstChild(); - } catch (XMLStreamException ex) { - LOG.log(Level.FINE, "Error cloning security element", ex); - } - } - return el; - } - - protected void addSignatureParts(List tokenList, - List sigParts) { - - boolean useSTRTransform = - MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_STR_TRANSFORM, true - ); - - for (SupportingToken supportingToken : tokenList) { - - Object tempTok = supportingToken.getTokenImplementation(); - WSEncryptionPart part = null; - - if (tempTok instanceof WSSecSignature) { - WSSecSignature tempSig = (WSSecSignature) tempTok; - SecurityTokenReference secRef = tempSig.getSecurityTokenReference(); - - if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType()) - || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { - - Element secRefElement = cloneElement(secRef.getElement()); - addSupportingElement(secRefElement); - - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(tempSig.getSecurityTokenReferenceURI()); - part.setElement(secRefElement); - } else { - if (tempSig.getBSTTokenId() != null) { - part = new WSEncryptionPart(tempSig.getBSTTokenId()); - part.setElement(tempSig.getBinarySecurityTokenElement()); - } - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken unt = (WSSecUsernameToken)tempTok; - part = new WSEncryptionPart(unt.getId()); - part.setElement(unt.getUsernameTokenElement()); - } else if (tempTok instanceof BinarySecurity) { - BinarySecurity bst = (BinarySecurity)tempTok; - part = new WSEncryptionPart(bst.getID()); - part.setElement(bst.getElement()); - } else if (tempTok instanceof SamlAssertionWrapper) { - SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper)tempTok; - - Document doc = assertionWrapper.getElement().getOwnerDocument(); - boolean saml1 = assertionWrapper.getSaml1() != null; - if (useSTRTransform) { - // TODO We only support using a KeyIdentifier for the moment - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, assertionWrapper.getId(), saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(assertionWrapper.getId()); - part.setElement(assertionWrapper.getElement()); - } - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - String tokenType = token.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType) - || WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - Document doc = token.getToken().getOwnerDocument(); - boolean saml1 = WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType); - String id = token.getId(); - if (id == null || "".equals(id)) { - if (saml1) { - id = token.getToken().getAttributeNS(null, "AssertionID"); - } else { - id = token.getToken().getAttributeNS(null, "ID"); - } - } - if (useSTRTransform) { - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, id, saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - String id = token.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - policyNotAsserted(supportingToken.getToken(), - "UnsupportedTokenInSupportingToken: " + tempTok); - } - if (part != null) { - sigParts.add(part); - } - } - } - - /** - * Create a SecurityTokenReference to point to a SAML Assertion - * @param doc The owner Document instance - * @param id The Assertion ID - * @param saml1 Whether the Assertion is a SAML1 or SAML2 Assertion - * @param useDirectReferenceToAssertion whether to refer directly to the assertion or not - * @return a SecurityTokenReference to a SAML Assertion - */ - private SecurityTokenReference createSTRForSamlAssertion( - Document doc, - String id, - boolean saml1, - boolean useDirectReferenceToAssertion - ) { - SecurityTokenReference secRefSaml = new SecurityTokenReference(doc); - String secRefID = wssConfig.getIdAllocator().createSecureId("STR-", secRefSaml); - secRefSaml.setID(secRefID); - - if (useDirectReferenceToAssertion) { - org.apache.wss4j.dom.message.token.Reference ref = - new org.apache.wss4j.dom.message.token.Reference(doc); - ref.setURI("#" + id); - if (saml1) { - ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - secRefSaml.setReference(ref); - } else { - Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); - String valueType = null; - if (saml1) { - valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - keyId.setAttributeNS( - null, "ValueType", valueType - ); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRefSaml.getElement(); - elem.appendChild(keyId); - } - return secRefSaml; - } - - protected WSSecUsernameToken addUsernameToken(UsernameToken token) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - // If NoPassword property is set we don't need to set the password - if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) { - utBuilder.setUserInfo(userName, null); - utBuilder.setPasswordType(null); - } else { - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) { - utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST); - } else { - utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT); - } - utBuilder.setUserInfo(userName, password); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - } - - if (token.isCreated() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addCreated(); - } - if (token.isNonce() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addNonce(); - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected WSSecUsernameToken addDKUsernameToken(UsernameToken token, boolean useMac) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - utBuilder.setUserInfo(userName, password); - utBuilder.addDerivedKey(useMac, null, 1000); - utBuilder.prepare(saaj.getSOAPPart()); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - // - // Get the SAML CallbackHandler - // - Object o = message.getContextualProperty(SecurityConstants.SAML_CALLBACK_HANDLER); - - if (o == null) { - SecurityToken securityToken = getSecurityToken(); - if (securityToken != null) { - Element tokenElement = (Element)securityToken.getToken(); - String namespace = tokenElement.getNamespaceURI(); - String localname = tokenElement.getLocalName(); - SamlTokenType tokenType = token.getSamlTokenType(); - if ((tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) - && WSConstants.SAML_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } else if (tokenType == SamlTokenType.WssSamlV20Token11 - && WSConstants.SAML2_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } - } - } - - CallbackHandler handler = null; - if (o instanceof CallbackHandler) { - handler = (CallbackHandler)o; - } else if (o instanceof String) { - try { - handler = (CallbackHandler)ClassLoaderUtils - .loadClass((String)o, this.getClass()).newInstance(); - } catch (Exception e) { - handler = null; - } - } - if (handler == null) { - policyNotAsserted(token, "No SAML CallbackHandler available"); - return null; - } - - SAMLCallback samlCallback = new SAMLCallback(); - SamlTokenType tokenType = token.getSamlTokenType(); - if (tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_11); - } else if (tokenType == SamlTokenType.WssSamlV20Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_20); - } - SAMLUtil.doSAMLCallback(handler, samlCallback); - SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback); - - if (samlCallback.isSignAssertion()) { - String issuerName = samlCallback.getIssuerKeyName(); - if (issuerName == null) { - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - issuerName = (String)message.getContextualProperty(userNameKey); - } - String password = samlCallback.getIssuerKeyPassword(); - if (password == null) { - password = getPassword(issuerName, token, WSPasswordCallback.SIGNATURE); - } - Crypto crypto = samlCallback.getIssuerCrypto(); - if (crypto == null) { - crypto = getSignatureCrypto(); - } - - assertion.signAssertion( - issuerName, - password, - crypto, - samlCallback.isSendKeyValue(), - samlCallback.getCanonicalizationAlgorithm(), - samlCallback.getSignatureAlgorithm(), - samlCallback.getSignatureDigestAlgorithm() - ); - } - - return assertion; - } - - /** - * Store a SAML Assertion as a SecurityToken - */ - protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) { - String id = findIDFromSamlToken(assertion.getElement()); - if (id == null) { - return; - } - SecurityToken secToken = new SecurityToken(id); - if (assertion.getSaml2() != null) { - secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } else { - secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } - secToken.setToken(assertion.getElement()); - getTokenStore().add(secToken); - message.put(SecurityConstants.TOKEN_ID, secToken.getId()); - } - - protected String findIDFromSamlToken(Element samlToken) { - String id = null; - if (samlToken != null) { - QName elName = DOMUtils.getElementQName(samlToken); - if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "AssertionID")) { - id = samlToken.getAttributeNS(null, "AssertionID"); - } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "ID")) { - id = samlToken.getAttributeNS(null, "ID"); - } - if (id == null) { - id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id"); - } - } - return id; - } - - protected String getPassword(String userName, Assertion info, int usage) { - //Then try to get the password from the given callback handler - CallbackHandler handler = getCallbackHandler(); - if (handler == null) { - // Don't unassert for signature as we might get the password from the crypto properties - if (usage == WSPasswordCallback.SIGNATURE) { - LOG.info("No CallbackHandler available to retrieve a password. We will now try the crypto " - + "properties file for a private password"); - } else { - policyNotAsserted(info, "No callback handler and no password available"); - } - return null; - } - - WSPasswordCallback[] cb = {new WSPasswordCallback(userName, usage)}; - try { - handler.handle(cb); - } catch (Exception e) { - policyNotAsserted(info, e); - } - - //get the password - return cb[0].getPassword(); - } - - protected CallbackHandler getCallbackHandler() { - return WSS4JUtils.getCallbackHandler(message); - } - - /** - * Generates a wsu:Id attribute for the provided {@code Element} and returns the attribute value - * or finds and returns the value of the attribute if it already exists. - * - * @param element the {@code Element} to check/create the attribute on - * - * @return the generated or discovered wsu:Id attribute value - */ - public String addWsuIdToElement(Element elem) { - String id; - - //first try to get the Id attr - Attr idAttr = elem.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = elem.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - - if (idAttr != null) { - id = idAttr.getValue(); - } else { - //Add an id - id = wssConfig.getIdAllocator().createId("_", elem); - String pfx = null; - try { - pfx = elem.lookupPrefix(PolicyConstants.WSU_NAMESPACE_URI); - } catch (Throwable t) { - pfx = DOMUtils.getPrefixRecursive(elem, PolicyConstants.WSU_NAMESPACE_URI); - } - boolean found = !StringUtils.isEmpty(pfx); - int cnt = 0; - while (StringUtils.isEmpty(pfx)) { - pfx = "wsu" + (cnt == 0 ? "" : cnt); - - String ns; - try { - ns = elem.lookupNamespaceURI(pfx); - } catch (Throwable t) { - ns = DOMUtils.getNamespace(elem, pfx); - } - - if (!StringUtils.isEmpty(ns)) { - pfx = null; - cnt++; - } - } - if (!found) { - idAttr = elem.getOwnerDocument().createAttributeNS(WSDLConstants.NS_XMLNS, "xmlns:" + pfx); - idAttr.setValue(PolicyConstants.WSU_NAMESPACE_URI); - elem.setAttributeNodeNS(idAttr); - } - idAttr = elem.getOwnerDocument().createAttributeNS(PolicyConstants.WSU_NAMESPACE_URI, - pfx + ":Id"); - idAttr.setValue(id); - elem.setAttributeNodeNS(idAttr); - } - - return id; - } - - public List getEncryptedParts() - throws SOAPException { - - boolean isBody = false; - - EncryptedParts parts = null; - EncryptedElements elements = null; - ContentEncryptedElements celements = null; - - Collection ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - parts = (EncryptedParts)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - elements = (EncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.CONTENT_ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - celements = (ContentEncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - if (parts == null && elements == null && celements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String encModifier = "Element"; - if (MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_ATTACHMENT_ENCRYPTION_CONTENT_ONLY_TRANSFORM, false)) { - encModifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", encModifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the encrypted list to prevent duplication / errors in encryption. - return getPartsAndElements(false, - isBody, - signedParts, - elements == null ? null : elements.getXPaths(), - celements == null ? null : celements.getXPaths()); - } - - public List getSignedParts(SupportingTokens supportingToken) - throws SOAPException { - - boolean isSignBody = false; - - SignedParts parts = null; - SignedElements elements = null; - - if (supportingToken != null && supportingToken.isEndorsing()) { - parts = supportingToken.getSignedParts(); - elements = supportingToken.getSignedElements(); - // Store them so that the main Signature doesn't sign them - if (parts != null) { - suppTokenParts.add(parts); - this.assertPolicy(parts.getName()); - } - if (elements != null) { - suppTokenParts.add(elements); - this.assertPolicy(elements.getName()); - } - } else { - Collection ais = getAllAssertionsByLocalname(SPConstants.SIGNED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedParts signedParts = (SignedParts)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedParts)) { - parts = signedParts; - } - } - } - - ais = getAllAssertionsByLocalname(SPConstants.SIGNED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedElements signedElements = (SignedElements)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedElements)) { - elements = signedElements; - } - } - } - } - - if (parts == null && elements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isSignBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String modifier = "Element"; - if (attachments.isContentSignatureTransform()) { - modifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", modifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the signed list to prevent duplication in the signature. - return getPartsAndElements(true, - isSignBody, - signedParts, - elements == null ? null : elements.getXPaths(), - null); - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param contentXpaths - * any XPath expressions to content encrypt - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - * - * @deprecated Use {@link #getSignedParts()} and {@link #getEncryptedParts()} - * instead. - */ - public List getPartsAndElements(boolean sign, - boolean includeBody, - List parts, - List xpaths, - List contentXpaths) - throws SOAPException { - - List result = new ArrayList(); - - List found = new ArrayList(); - - // Handle sign/enc parts - result.addAll(this.getParts(sign, includeBody, parts, found)); - - // Handle sign/enc elements - result.addAll(this.getElements("Header", xpaths, found, sign)); - - if (!sign) { - // Handle content encrypted elements - result.addAll(this.getElements("Content", contentXpaths, found, sign)); - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getParts(boolean sign, - boolean includeBody, List parts, - List found) throws SOAPException { - - List result = new ArrayList(); - - if (includeBody && !found.contains(SAAJUtils.getBody(this.saaj))) { - found.add(SAAJUtils.getBody(saaj)); - final String id = this.addWsuIdToElement(SAAJUtils.getBody(this.saaj)); - if (sign) { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Element"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } else { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Content"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } - } - - final SOAPHeader header = SAAJUtils.getHeader(saaj); - - // Handle sign/enc parts - for (WSEncryptionPart part : parts) { - if (part.getId() != null && part.getId().startsWith("cid:")) { - // Attachments are handled inside WSS4J via a CallbackHandler - result.add(part); - continue; - } - final List elements; - - if (StringUtils.isEmpty(part.getName())) { - // An entire namespace - elements = - DOMUtils.getChildrenWithNamespace(header, part.getNamespace()); - } else { - // All elements with a given name and namespace - elements = - DOMUtils.getChildrenWithName(header, part.getNamespace(), part.getName()); - } - - for (Element el : elements) { - if (!found.contains(el)) { - found.add(el); - // Generate an ID for the element and use this ID or else - // WSS4J will only ever sign/encrypt the first matching - // element with the same name and namespace as that in the - // WSEncryptionPart - final String id = this.addWsuIdToElement(el); - WSEncryptionPart elPart = - new WSEncryptionPart(id, part.getEncModifier()); - elPart.setElement(el); - result.add(elPart); - } - } - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param encryptionModifier - * indicates the scope of the crypto operation over matched - * elements. Either "Content" or "Element". - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @param forceId - * force adding a wsu:Id onto the elements. Recommended for signatures. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws XPathExpressionException - * if a provided XPath is invalid - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getElements(String encryptionModifier, - List xpaths, - List found, - boolean forceId) throws SOAPException { - - List result = new ArrayList(); - - if (xpaths != null && !xpaths.isEmpty()) { - XPathFactory factory = XPathFactory.newInstance(); - for (org.apache.wss4j.policy.model.XPath xPath : xpaths) { - XPath xpath = factory.newXPath(); - if (xPath.getPrefixNamespaceMap() != null) { - xpath.setNamespaceContext(new MapNamespaceContext(xPath.getPrefixNamespaceMap())); - } - - NodeList list = null; - try { - list = (NodeList)xpath.evaluate(xPath.getXPath(), saaj.getSOAPPart().getEnvelope(), - XPathConstants.NODESET); - } catch (XPathExpressionException e) { - LOG.log(Level.WARNING, "Failure in evaluating an XPath expression", e); - } - - if (list != null) { - for (int x = 0; x < list.getLength(); x++) { - Element el = (Element)list.item(x); - - if (!found.contains(el)) { - String id = setIdOnElement(el, forceId); - WSEncryptionPart part = - new WSEncryptionPart(id, encryptionModifier); - part.setElement(el); - part.setXpath(xPath.getXPath()); - - result.add(part); - } - } - } - } - } - - return result; - } - - private String setIdOnElement(Element element, boolean forceId) { - if (forceId) { - return this.addWsuIdToElement(element); - } - - //not forcing an ID on this. Use one if there is one - //there already, but don't force one - Attr idAttr = element.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = element.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - if (idAttr != null) { - return idAttr.getValue(); - } - - return null; - } - - protected WSSecEncryptedKey getEncryptedKeyBuilder(AbstractToken token) throws WSSecurityException { - WSSecEncryptedKey encrKey = new WSSecEncryptedKey(wssConfig); - encrKey.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - encrKey.setStoreBytesInAttachment(storeBytesInAttachment); - Crypto crypto = getEncryptionCrypto(); - message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - setKeyIdentifierType(encrKey, token); - - boolean alsoIncludeToken = false; - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && encrKey.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE) { - alsoIncludeToken = true; - } - - String encrUser = setEncryptionUser(encrKey, token, false, crypto); - - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - encrKey.setSymmetricEncAlgorithm(algType.getEncryption()); - encrKey.setKeyEncAlgo(algType.getAsymmetricKeyWrap()); - - encrKey.prepare(saaj.getSOAPPart(), crypto); - - if (alsoIncludeToken) { - X509Certificate encCert = getEncryptCert(crypto, encrUser); - BinarySecurity bstToken = new X509Security(saaj.getSOAPPart()); - ((X509Security) bstToken).setX509Certificate(encCert); - bstToken.addWSUNamespace(); - bstToken.setID(wssConfig.getIdAllocator().createSecureId("X509-", encCert)); - WSSecurityUtil.prependChildElement( - secHeader.getSecurityHeader(), bstToken.getElement() - ); - bstElement = bstToken.getElement(); - } - - return encrKey; - } - - private X509Certificate getEncryptCert(Crypto crypto, String encrUser) throws WSSecurityException { - // Check for prepared encryption certificate - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - return encrCert; - } - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - return certs[0]; - } - - public Crypto getSignatureCrypto() throws WSSecurityException { - return getCrypto(SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES); - } - - public Crypto getEncryptionCrypto() throws WSSecurityException { - Crypto crypto = - getCrypto(SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES); - boolean enableRevocation = MessageUtils.isTrue( - message.getContextualProperty(SecurityConstants.ENABLE_REVOCATION)); - if (enableRevocation && crypto != null) { - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - String encrUser = (String)message.getContextualProperty(SecurityConstants.ENCRYPT_USERNAME); - if (encrUser == null) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - if (certs != null && certs.length > 0) { - crypto.verifyTrust(certs, enableRevocation, null); - } - } - if (crypto != null) { - this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - } - return crypto; - - } - - protected Crypto getCrypto( - String cryptoKey, - String propKey - ) throws WSSecurityException { - Crypto crypto = (Crypto)message.getContextualProperty(cryptoKey); - if (crypto != null) { - return crypto; - } - - Object o = message.getContextualProperty(propKey); - if (o == null) { - return null; - } - - crypto = getCryptoCache().get(o); - if (crypto != null) { - return crypto; - } - - ResourceManager manager = - message.getExchange().get(Bus.class).getExtension(ResourceManager.class); - URL propsURL = WSS4JUtils.getPropertiesFileURL(o, manager, this.getClass()); - Properties properties = WSS4JUtils.getProps(o, propsURL); - - if (properties != null) { - crypto = CryptoFactory.getInstance(properties, - Loader.getClassLoader(CryptoFactory.class), - WSS4JUtils.getPasswordEncryptor(message)); - getCryptoCache().put(o, crypto); - } - return crypto; - } - - public void setKeyIdentifierType(WSSecBase secBase, AbstractToken token) { - boolean tokenTypeSet = false; - - if (token instanceof X509Token) { - X509Token x509Token = (X509Token)token; - if (x509Token.isRequireIssuerSerialReference()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - tokenTypeSet = true; - } else if (x509Token.isRequireKeyIdentifierReference()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - tokenTypeSet = true; - } else if (x509Token.isRequireThumbprintReference()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - tokenTypeSet = true; - } - } else if (token instanceof KeyValueToken) { - secBase.setKeyIdentifierType(WSConstants.KEY_VALUE); - tokenTypeSet = true; - } - - assertToken(token); - - if (!tokenTypeSet) { - boolean requestor = isRequestor(); - if (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_NEVER - || token instanceof X509Token - && ((token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_RECIPIENT - && !requestor) - || (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_INITIATOR - && requestor))) { - Wss10 wss = getWss10(); - assertPolicy(wss); - if (wss == null || wss.isMustSupportRefKeyIdentifier()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - } else if (wss.isMustSupportRefIssuerSerial()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } else if (wss instanceof Wss11 && ((Wss11) wss).isMustSupportRefThumbprint()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - } else { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } - } else { - secBase.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); - } - } - } - - public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, AbstractToken token, - boolean sign, Crypto crypto) { - // Check for prepared certificate property - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - encrKeyBuilder.setUseThisCert(encrCert); - return null; - } - - String encrUser = (String)message.getContextualProperty(sign - ? SecurityConstants.SIGNATURE_USERNAME - : SecurityConstants.ENCRYPT_USERNAME); - if (crypto != null && (encrUser == null || "".equals(encrUser))) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - if (encrUser == null || "".equals(encrUser)) { - policyNotAsserted(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared."); - } - if (WSHandlerConstants.USE_REQ_SIG_CERT.equals(encrUser)) { - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - if (results != null) { - encrKeyBuilder.setUseThisCert(WSS4JUtils.getReqSigCert(results)); - - //TODO This is a hack, this should not come under USE_REQ_SIG_CERT - if (encrKeyBuilder.isCertSet()) { - encrKeyBuilder.setUserInfo(getUsername(results)); - } - } else { - policyNotAsserted(token, "No security results in incoming message"); - } - } else { - encrKeyBuilder.setUserInfo(encrUser); - } - - return encrUser; - } - - /** - * Scan through WSHandlerResult list for a Username token and return - * the username if a Username Token found - * @param results - * @return - */ - public static String getUsername(List results) { - /* - * Scan the results for a matching actor. Use results only if the - * receiving Actor and the sending Actor match. - */ - for (WSHandlerResult rResult : results) { - List wsSecEngineResults = rResult.getResults(); - /* - * Scan the results for a username token. Use the username - * of this token to set the alias for the encryption user - */ - for (WSSecurityEngineResult wser : wsSecEngineResults) { - Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION); - if (actInt.intValue() == WSConstants.UT) { - UsernameTokenPrincipal principal - = (UsernameTokenPrincipal)wser.get(WSSecurityEngineResult.TAG_PRINCIPAL); - return principal.getName(); - } - } - } - - return null; - } - - private void checkForX509PkiPath(WSSecSignature sig, AbstractToken token) { - if (token instanceof X509Token) { - X509Token x509Token = (X509Token) token; - TokenType tokenType = x509Token.getTokenType(); - if (tokenType == TokenType.WssX509PkiPathV1Token10 - || tokenType == TokenType.WssX509PkiPathV1Token11) { - sig.setUseSingleCertificate(false); - } - } - } - - protected WSSecSignature getSignatureBuilder( - AbstractToken token, boolean attached, boolean endorse - ) throws WSSecurityException { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - sig.setStoreBytesInAttachment(storeBytesInAttachment); - checkForX509PkiPath(sig, token); - if (token instanceof IssuedToken || token instanceof SamlToken) { - assertToken(token); - SecurityToken securityToken = getSecurityToken(); - String tokenType = securityToken.getTokenType(); - - Element ref; - if (attached) { - ref = securityToken.getAttachedReference(); - } else { - ref = securityToken.getUnattachedReference(); - } - - if (ref != null) { - - // DIGST WORKAROUND START - - // old code that is replaced - // SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - - // new code - String id = securityToken.getId(); - SecurityTokenReference secRef = null; - if ((id != null) && (id.equals("encryptedassertion"))) { - Document doc = ref.getOwnerDocument(); - secRef = new SecurityTokenReference(doc); - secRef.addTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"); - Element keyId = doc.createElementNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:KeyIdentifier"); - keyId.setAttributeNS(null, "ValueType", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID"); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRef.getElement(); - elem.appendChild(keyId); - } - else { - secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - } - - // DIGST WORKAROUND END - - sig.setSecurityTokenReference(secRef); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - int type = attached ? WSConstants.CUSTOM_SYMM_SIGNING - : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT; - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - sig.setCustomTokenValueType(tokenType); - sig.setKeyIdentifierType(type); - } - } - - String sigTokId; - if (attached) { - sigTokId = securityToken.getWsuId(); - if (sigTokId == null) { - sigTokId = securityToken.getId(); - } - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - } else { - sigTokId = securityToken.getId(); - } - - sig.setCustomTokenId(sigTokId); - } else { - setKeyIdentifierType(sig, token); - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && (sig.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE - && sig.getKeyIdentifierType() != WSConstants.KEY_VALUE)) { - sig.setIncludeSignatureToken(true); - } - } - - boolean encryptCrypto = false; - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - String type = "signature"; - if (binding instanceof SymmetricBinding && !endorse) { - encryptCrypto = ((SymmetricBinding)binding).getProtectionToken() != null; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - } - - Crypto crypto = encryptCrypto ? getEncryptionCrypto() : getSignatureCrypto(); - - if (endorse && crypto == null && binding instanceof SymmetricBinding) { - type = "encryption"; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - crypto = getEncryptionCrypto(); - } - - if (!encryptCrypto) { - message.getExchange().put(SecurityConstants.SIGNATURE_CRYPTO, crypto); - } - String user = (String)message.getContextualProperty(userNameKey); - if (StringUtils.isEmpty(user)) { - if (crypto != null) { - try { - user = crypto.getDefaultX509Identifier(); - if (StringUtils.isEmpty(user)) { - policyNotAsserted(token, "No configured " + type + " username detected"); - return null; - } - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - } else { - policyNotAsserted(token, "Security configuration could not be detected. " - + "Potential cause: Make sure jaxws:client element with name " - + "attribute value matching endpoint port is defined as well as a " - + SecurityConstants.SIGNATURE_PROPERTIES + " element within it."); - return null; - } - } - - String password = getPassword(user, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(user, password); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.setWsConfig(wssConfig); - try { - sig.prepare(saaj.getSOAPPart(), crypto, secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - policyNotAsserted(token, e); - } - - return sig; - } - - protected void doEndorsedSignatures(List tokenList, - boolean isTokenProtection, - boolean isSigProtect) { - - for (SupportingToken supportingToken : tokenList) { - Object tempTok = supportingToken.getTokenImplementation(); - - List sigParts = new ArrayList(); - WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId); - sigPart.setElement(bottomUpElement); - sigParts.add(sigPart); - - if (supportingToken.getSignedParts() != null) { - for (WSEncryptionPart signedPart : supportingToken.getSignedParts()) { - sigParts.add(signedPart); - } - } - - if (tempTok instanceof WSSecSignature) { - WSSecSignature sig = (WSSecSignature)tempTok; - if (isTokenProtection && sig.getBSTTokenId() != null) { - WSEncryptionPart bstPart = - new WSEncryptionPart(sig.getBSTTokenId()); - bstPart.setElement(sig.getBinarySecurityTokenElement()); - sigParts.add(bstPart); - } - try { - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - sig.computeSignature(referenceList, false, null); - - signatures.add(sig.getSignatureValue()); - if (isSigProtect) { - WSEncryptionPart part = new WSEncryptionPart(sig.getId(), "Element"); - encryptedTokensList.add(part); - } - } catch (WSSecurityException e) { - policyNotAsserted(supportingToken.getToken(), e); - } - - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(token.getId())); - } - - try { - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), token, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), token, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken utBuilder = (WSSecUsernameToken)tempTok; - String id = utBuilder.getId(); - - Date created = new Date(); - Date expires = new Date(); - expires.setTime(created.getTime() + 300000); - SecurityToken secToken = - new SecurityToken(id, utBuilder.getUsernameTokenElement(), created, expires); - - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(secToken.getId())); - } - - try { - byte[] secret = utBuilder.getDerivedKey(); - secToken.setSecret(secret); - - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), secToken, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), secToken, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - - } - } - } - - private void doSymmSignatureDerived(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecDKSign dkSign = new WSSecDKSign(wssConfig); - - //Check whether it is security policy 1.2 and use the secure conversation accordingly - if (policyToken.getVersion() == SPConstants.SPVersion.SP11) { - dkSign.setWscVersion(ConversationConstants.VERSION_05_02); - } - - //Check for whether the token is attached in the message or not - boolean attached = false; - if (isTokenRequired(policyToken.getIncludeTokenType())) { - attached = true; - } - - // Setting the AttachedReference or the UnattachedReference according to the flag - Element ref; - if (attached) { - ref = tok.getAttachedReference(); - } else { - ref = tok.getUnattachedReference(); - } - - if (ref != null) { - ref = cloneElement(ref); - dkSign.setExternalKey(tok.getSecret(), ref); - } else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - // If the Encrypted key used to create the derived key is not - // attached use key identifier as defined in WSS1.1 section - // 7.7 Encrypted Key reference - SecurityTokenReference tokenRef - = new SecurityTokenReference(doc); - if (tok.getSHA1() != null) { - tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1()); - tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE); - } - dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement()); - - } else { - dkSign.setExternalKey(tok.getSecret(), tok.getId()); - } - - //Set the algo info - dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - dkSign.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8); - if (tok.getSHA1() != null) { - //Set the value type of the reference - dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#" - + WSConstants.ENC_KEY_VALUE_TYPE); - } else if (policyToken instanceof UsernameToken) { - dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } - - dkSign.prepare(doc, secHeader); - - if (isTokenProtection) { - //Hack to handle reference id issues - //TODO Need a better fix - String sigTokId = tok.getId(); - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - sigParts.add(new WSEncryptionPart(sigTokId)); - } - - dkSign.setParts(sigParts); - - List referenceList = dkSign.addReferencesToSign(sigParts, secHeader); - - //Add elements to header - addSupportingElement(dkSign.getdktElement()); - - //Do signature - dkSign.computeSignature(referenceList, false, null); - - signatures.add(dkSign.getSignatureValue()); - } - - private void doSymmSignature(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecSignature sig = new WSSecSignature(wssConfig); - // If a EncryptedKeyToken is used, set the correct value type to - // be used in the wsse:Reference in ds:KeyInfo - if (policyToken instanceof X509Token) { - if (isRequestor()) { - // TODO Add support for SAML2 here - sig.setCustomTokenValueType( - WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE - ); - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } else { - //the tok has to be an EncryptedKey token - sig.setEncrKeySha1value(tok.getSHA1()); - sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); - } - - } else { - String tokenType = tok.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else if (policyToken instanceof UsernameToken) { - sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } - - String sigTokId = tok.getWsuId(); - if (sigTokId == null) { - sigTokId = tok.getId(); - } - - //Hack to handle reference id issues - //TODO Need a better fix - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - - sig.setCustomTokenId(sigTokId); - sig.setSecretKey(tok.getSecret()); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.prepare(doc, getSignatureCrypto(), secHeader); - - sig.setParts(sigParts); - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - - //Do signature - sig.computeSignature(referenceList, false, null); - signatures.add(sig.getSignatureValue()); - } - - protected void addSupportingTokens(List sigs) throws WSSecurityException { - Collection sgndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_SUPPORTING_TOKENS); - List sigSuppTokList = this.handleSupportingTokens(sgndSuppTokens, false); - - Collection endSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_SUPPORTING_TOKENS); - endSuppTokList = this.handleSupportingTokens(endSuppTokens, true); - - Collection sgndEndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_SUPPORTING_TOKENS); - sgndEndSuppTokList = this.handleSupportingTokens(sgndEndSuppTokens, true); - - Collection sgndEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENCRYPTED_SUPPORTING_TOKENS); - List sgndEncSuppTokList - = this.handleSupportingTokens(sgndEncryptedSuppTokens, false); - - Collection endorsingEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - endSuppTokList.addAll(this.handleSupportingTokens(endorsingEncryptedSuppTokens, true)); - - Collection sgndEndEncSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - sgndEndSuppTokList.addAll(this.handleSupportingTokens(sgndEndEncSuppTokens, true)); - - Collection supportingToks = - getAllAssertionsByLocalname(aim, SPConstants.SUPPORTING_TOKENS); - this.handleSupportingTokens(supportingToks, false); - - Collection encryptedSupportingToks = - getAllAssertionsByLocalname(aim, SPConstants.ENCRYPTED_SUPPORTING_TOKENS); - this.handleSupportingTokens(encryptedSupportingToks, false); - - //Setup signature parts - addSignatureParts(sigSuppTokList, sigs); - addSignatureParts(sgndEncSuppTokList, sigs); - addSignatureParts(sgndEndSuppTokList, sigs); - } - - protected void doEndorse() { - boolean tokenProtect = false; - boolean sigProtect = false; - if (binding instanceof AsymmetricBinding) { - tokenProtect = ((AsymmetricBinding)binding).isProtectTokens(); - sigProtect = ((AsymmetricBinding)binding).isEncryptSignature(); - } else if (binding instanceof SymmetricBinding) { - tokenProtect = ((SymmetricBinding)binding).isProtectTokens(); - sigProtect = ((SymmetricBinding)binding).isEncryptSignature(); - } - // Do endorsed signatures - doEndorsedSignatures(endSuppTokList, tokenProtect, sigProtect); - - // Do signed endorsing signatures - doEndorsedSignatures(sgndEndSuppTokList, tokenProtect, sigProtect); - } - - protected void addSignatureConfirmation(List sigParts) { - Wss10 wss10 = getWss10(); - - if (!(wss10 instanceof Wss11) - || !((Wss11)wss10).isRequireSignatureConfirmation()) { - //If we don't require sig confirmation simply go back :-) - return; - } - - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - /* - * loop over all results gathered by all handlers in the chain. For each - * handler result get the various actions. After that loop we have all - * signature results in the signatureActions list - */ - List signatureActions = new ArrayList(); - final List signedActions = new ArrayList(2); - signedActions.add(WSConstants.SIGN); - signedActions.add(WSConstants.UT_SIGN); - for (WSHandlerResult wshResult : results) { - signatureActions.addAll( - WSSecurityUtil.fetchAllActionResults(wshResult.getResults(), signedActions) - ); - } - - sigConfList = new ArrayList(); - // prepare a SignatureConfirmation token - WSSecSignatureConfirmation wsc = new WSSecSignatureConfirmation(wssConfig); - if (signatureActions.size() > 0) { - for (WSSecurityEngineResult wsr : signatureActions) { - byte[] sigVal = (byte[]) wsr.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE); - wsc.setSignatureValue(sigVal); - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - } else { - //No Sig value - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - - assertPolicy( - new QName(wss10.getName().getNamespaceURI(), SPConstants.REQUIRE_SIGNATURE_CONFIRMATION)); - } - - /** - * Processes the parts to be signed and reconfigures those parts that have - * already been encrypted. - * - * @param encryptedParts - * the parts that have been encrypted - * @param signedParts - * the parts that are to be signed - * - * @throws IllegalArgumentException - * if an element in {@code signedParts} contains a {@code - * WSEncryptionPart} with a {@code null} {@code id} value - * and the {@code WSEncryptionPart} {@code name} value is not - * "Token" - */ - public void handleEncryptedSignedHeaders(List encryptedParts, - List signedParts) { - - final List signedEncryptedParts = new ArrayList(); - - for (WSEncryptionPart encryptedPart : encryptedParts) { - final Iterator signedPartsIt = signedParts.iterator(); - while (signedPartsIt.hasNext()) { - WSEncryptionPart signedPart = signedPartsIt.next(); - // Everything has to be ID based except for the case of a part - // indicating "Token" as the element name. This name is a flag - // for WSS4J to sign the initiator token used in the signature. - // Since the encryption happened before the signature creation, - // this element can't possibly be encrypted so we can safely ignore - // if it were ever to be set before this method is called. - if (signedPart.getId() == null && !"Token".equals(signedPart.getName())) { - throw new IllegalArgumentException( - "WSEncryptionPart must be ID based but no id was found."); - } else if (encryptedPart.getEncModifier().equals("Header") - && signedPart.getId().equals(encryptedPart.getId())) { - // We are to sign something that has already been encrypted. - // We need to preserve the original aspects of signedPart but - // change the ID to the encrypted ID. - - signedPartsIt.remove(); - WSEncryptionPart part = new WSEncryptionPart( - encryptedPart.getEncId(), - encryptedPart.getEncModifier()); - part.setElement(encryptedPart.getElement()); - signedEncryptedParts.add(part); - } - } - } - - signedParts.addAll(signedEncryptedParts); - } - - /** - * Convert a DOM Element into a WSEncryptionPart, adding a (wsu:)Id if there is not - * one already. - * @param element The DOM Element to convert - * @return The WSEncryptionPart representing the DOM Element argument - */ - public WSEncryptionPart convertToEncryptionPart(Element element) { - String id = addWsuIdToElement(element); - WSEncryptionPart part = new WSEncryptionPart(id); - part.setElement(element); - return part; - } - - static class SupportingToken { - private final AbstractToken token; - private final Object tokenImplementation; - private final List signedParts; - - public SupportingToken(AbstractToken token, Object tokenImplementation, - List signedParts) { - this.token = token; - this.tokenImplementation = tokenImplementation; - this.signedParts = signedParts; - } - - public AbstractToken getToken() { - return token; - } - - public Object getTokenImplementation() { - return tokenImplementation; - } - - public List getSignedParts() { - return signedParts; - } - - } -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java b/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java deleted file mode 100644 index 96cb070..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java +++ /dev/null @@ -1,281 +0,0 @@ -// NOTE!!! -// -// This is a copy of STRTransform.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the transformIt() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it returns an EncryptedAssertion -// element with an embedded EncryptedData element. The EncryptedData element has the ID -// referenced by the RAR in the RequestSecurityTokenResponse, but we need to dereference -// the parent element for this to work - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom.transform; - -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSDocInfo; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.message.token.PKIPathSecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; - -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignatureInput; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import java.io.ByteArrayInputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Iterator; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.NodeSetData; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; - - -/** - * Class STRTransform. - */ -public class STRTransform extends TransformService { - - public static final String TRANSFORM_URI = - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform"; - - public static final String TRANSFORM_WS_DOC_INFO = "transform_ws_doc_info"; - - private TransformParameterSpec params; - - private Element transformElement; - - private static final org.slf4j.Logger LOG = - org.slf4j.LoggerFactory.getLogger(STRTransform.class); - - public final AlgorithmParameterSpec getParameterSpec() { - return params; - } - - public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { - this.params = params; - } - - public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - transformElement = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - } - - public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - Element transformElement2 = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - appendChild(transformElement2, transformElement); - transformElement = transformElement2; - } - - - public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - return transformIt(data, xc, null); - } - - public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - if (os == null) { - throw new NullPointerException("output stream must not be null"); - } - return transformIt(data, xc, os); - } - - - private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - - // - // First step: Get the required c14n argument and get the specified - // Canonicalizer - // - String canonAlgo = null; - Element transformParams = WSSecurityUtil.getDirectChildElement( - transformElement, "TransformationParameters", WSConstants.WSSE_NS - ); - if (transformParams != null) { - Element canonElem = - WSSecurityUtil.getDirectChildElement( - transformParams, "CanonicalizationMethod", WSConstants.SIG_NS - ); - canonAlgo = canonElem.getAttributeNS(null, "Algorithm"); - } - try { - // - // Get the input (node) to transform. - // - Element str = null; - if (data instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)data; - Iterator iterator = nodeSetData.iterator(); - while (iterator.hasNext()) { - Node node = (Node)iterator.next(); - if (node instanceof Element && "SecurityTokenReference".equals(node.getLocalName())) { - str = (Element)node; - break; - } - } - } else { - try { - XMLSignatureInput xmlSignatureInput = - new XMLSignatureInput(((OctetStreamData)data).getOctetStream()); - str = (Element)xmlSignatureInput.getSubNode(); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - if (str == null) { - throw new TransformException("No SecurityTokenReference found"); - } - // - // The element to transform MUST be a SecurityTokenReference - // element. - // - SecurityTokenReference secRef = new SecurityTokenReference(str, new BSPEnforcer()); - - Canonicalizer canon = Canonicalizer.getInstance(canonAlgo); - - byte[] buf = null; - - // - // Third and fourth step are performed by dereferenceSTR() - // - Object wsDocInfoObject = xc.getProperty(TRANSFORM_WS_DOC_INFO); - WSDocInfo wsDocInfo = null; - if (wsDocInfoObject instanceof WSDocInfo) { - wsDocInfo = (WSDocInfo)wsDocInfoObject; - } - if (wsDocInfo == null) { - LOG.debug("STRTransform: no WSDocInfo found"); - } - - Document doc = str.getOwnerDocument(); - Element dereferencedToken = - STRTransformUtil.dereferenceSTR(doc, secRef, wsDocInfo); - - if (dereferencedToken != null) { - String type = dereferencedToken.getAttributeNS(null, "ValueType"); - if (X509Security.X509_V3_TYPE.equals(type) - || PKIPathSecurity.getType().equals(type)) { - // - // Add the WSSE/WSU namespaces to the element for C14n - // - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX - ); - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSU_NS, WSConstants.WSU_PREFIX - ); - } - } - - // BEGIN DIGST WORKAROUND - boolean parentNodeIsNull = (dereferencedToken.getParentNode() == null); - boolean encryptedAssertionId = (dereferencedToken.getAttribute("wsu:Id") != null && dereferencedToken.getAttribute("wsu:Id").equals("encryptedassertion")); - - if (!parentNodeIsNull && encryptedAssertionId) { - dereferencedToken = (Element) dereferencedToken.getParentNode(); - } - // END DIGST WORKAROUND - - // - // C14n with specified algorithm. According to WSS Specification. - // - buf = canon.canonicalizeSubtree(dereferencedToken, "#default", true); - if (LOG.isDebugEnabled()) { - LOG.debug("after c14n: " + new String(buf, "UTF-8")); - } - - if (os != null) { - os.write(buf); - return null; - } - return new OctetStreamData(new ByteArrayInputStream(buf)); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - - - public final boolean isFeatureSupported(String feature) { - if (feature == null) { - throw new NullPointerException(); - } else { - return false; - } - } - - private static void appendChild(Node parent, Node child) { - Document ownerDoc = null; - if (parent.getNodeType() == Node.DOCUMENT_NODE) { - ownerDoc = (Document)parent; - } else { - ownerDoc = parent.getOwnerDocument(); - } - if (child.getOwnerDocument() != ownerDoc) { - parent.appendChild(ownerDoc.importNode(child, true)); - } else { - parent.appendChild(child); - } - } - -} diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/HelloWorld-Hok.wsdl b/examples/lbsb/bootstrap-scenario/src/main/resources/HelloWorld-Hok.wsdl deleted file mode 100644 index 75b24aa..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/resources/HelloWorld-Hok.wsdl +++ /dev/null @@ -1,182 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/client.pfx b/examples/lbsb/bootstrap-scenario/src/main/resources/client.pfx deleted file mode 100644 index f6ed4ce..0000000 Binary files a/examples/lbsb/bootstrap-scenario/src/main/resources/client.pfx and /dev/null differ diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/client.properties b/examples/lbsb/bootstrap-scenario/src/main/resources/client.properties deleted file mode 100644 index 09a24f1..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/resources/client.properties +++ /dev/null @@ -1,8 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=java ref. test (funktionscertifikat) -org.apache.ws.security.crypto.merlin.file=client.pfx - -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/cxf.xml b/examples/lbsb/bootstrap-scenario/src/main/resources/cxf.xml deleted file mode 100644 index 34303e5..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/resources/cxf.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/sts.properties b/examples/lbsb/bootstrap-scenario/src/main/resources/sts.properties deleted file mode 100644 index 8af9ada..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/resources/sts.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=jks -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=sts -org.apache.ws.security.crypto.merlin.file=trust.jks diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/sts.wsdl b/examples/lbsb/bootstrap-scenario/src/main/resources/sts.wsdl deleted file mode 100644 index 367a5ec..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/resources/sts.wsdl +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/resources/trust.jks b/examples/lbsb/bootstrap-scenario/src/main/resources/trust.jks deleted file mode 100644 index 74dedb8..0000000 Binary files a/examples/lbsb/bootstrap-scenario/src/main/resources/trust.jks and /dev/null differ diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/classes/log4j.properties b/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/classes/log4j.properties deleted file mode 100644 index e5df705..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/classes/log4j.properties +++ /dev/null @@ -1,12 +0,0 @@ -log4j.rootCategory=info, CONSOLE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.ImmediateFlush=true -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-2p] %c - %m%n - -log4j.additivity.dk.itst=false -log4j.additivity.org=false - -log4j.logger.dk.itst=debug, CONSOLE -log4j.logger.org=warn, CONSOLE diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/web.xml b/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 88df26e..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - OIOSAML-J - - - oiosaml-j.home - java.lang.String - oiosaml-config - - - - dk.itst.oiosaml.sp.service.session.SessionDestroyListener - - - - SAMLDispatcherServlet - - dk.itst.oiosaml.sp.service.DispatcherServlet - - 1 - - - - SAMLDispatcherServlet - /saml/* - - - - LoginFilter - dk.itst.oiosaml.sp.service.SPFilter - - - LoginFilter - /sp/* - - - index.jsp - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/configure.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/configure.jsp deleted file mode 100644 index 901ad53..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/configure.jsp +++ /dev/null @@ -1,67 +0,0 @@ - -<%@page import="dk.itst.oiosaml.configuration.SAMLConfigurationFactory"%> -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="org.apache.commons.configuration.Configuration"%> -<%@page import="java.util.Iterator"%> - -

Runtime configuration - OIOSAML.java Service Provider Demo

-

Use this to change the OIOSAML.java runtime configuration. Changes here are lost when the server is restarted. See the documentation for configuration help.

- -<% - -CompositeConfiguration conf = (CompositeConfiguration) SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); -StringWriter sw = new StringWriter(); -PropertiesConfiguration c = null; - -for (int i = 0; i < conf.getNumberOfConfigurations(); i++){ - if (conf.getConfiguration(i) instanceof PropertiesConfiguration) { - c = (PropertiesConfiguration)conf.getConfiguration(i); - break; - } -} - -if (request.getMethod().equals("POST") && c != null) { - c.setProperty(Constants.PROP_PASSIVE, Boolean.valueOf(request.getParameter("isPassive"))); - c.setProperty(Constants.PROP_PASSIVE_USER_ID, request.getParameter("passiveUsername")); - c.setProperty(Constants.PROP_FORCE_AUTHN_URLS, request.getParameter("forceAuthn") != null ? "/.*" : null); - c.setProperty(Constants.PROP_NAMEID_POLICY_ALLOW_CREATE, Boolean.valueOf(request.getParameter("allowCreate"))); - c.setProperty(Constants.PROP_NAMEID_POLICY, request.getParameter("nameIdPolicy")); - - if (request.getParameter("property") != null && !request.getParameter("property").trim().equals("")) { - c.setProperty(request.getParameter("property"), request.getParameter("propertyValue")); - } -} - - -c.save(sw); -%> - -
- - - - - - - - -
IsPassive/>
Passive username" />
Force authn />
Allow create />
NameID Policy (blank, persistent or transient)" />
- -
- -

Current configuration - from <%= c.getFile() %>

-
-<%= sw %>
-
- - - - - - - - -<%@page import="org.apache.commons.configuration.CompositeConfiguration"%> -<%@page import="org.apache.commons.configuration.PropertiesConfiguration"%> -<%@page import="java.io.StringWriter"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Constants"%> \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/head.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/head.jsp deleted file mode 100644 index f50528c..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/head.jsp +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - OIOSAML.java demo application - - - -<%@page import="dk.itst.oiosaml.configuration.SAMLConfigurationFactory"%> -<%@page import="org.apache.commons.configuration.Configuration"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Constants"%> -<%@page import="dk.itst.oiosaml.sp.UserAssertion"%> - -Home -<% - try { - SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); - UserAssertion ua = (UserAssertion)session.getAttribute(Constants.SESSION_USER_ASSERTION); -%> -<%=ua != null && ua.isAuthenticated() ? "Log out" : "Login"%> - -Metadata - -<% } catch (RuntimeException e) { %> -

System is not configured

-Configure the system here. -<% } %> -OIOSAML.java Documentation \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/index.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/index.jsp deleted file mode 100644 index 3a1b36d..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/index.jsp +++ /dev/null @@ -1,21 +0,0 @@ - -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> - -

Front page - OIOSAML.java Service Provider Demo

-

- -
- Page requiring login · Runtime configuration

- -
-

Test form POST:

-
- - -
-
- - oiosaml.java -
- - \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/oiosaml.gif b/examples/lbsb/bootstrap-scenario/src/main/webapp/oiosaml.gif deleted file mode 100644 index ef6126c..0000000 Binary files a/examples/lbsb/bootstrap-scenario/src/main/webapp/oiosaml.gif and /dev/null differ diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/postlogin.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/postlogin.jsp deleted file mode 100644 index 896a0dc..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/postlogin.jsp +++ /dev/null @@ -1,37 +0,0 @@ - - -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> - - - - - OIOSAML.java Default login page for HTTP Post method - - - -

Default login page for HTTP Post method.

-
" method="post"> - " /> - " /> - -
-

This page is the default OIOSaml.java HTTP POST method login page.

-

Submitting the form will send the following values to the IdP:

- - - - -
action<%= (String)request.getAttribute("action") %>
SAMLRequest<%= (String)request.getAttribute("SAMLRequest") %>
RelayState<%= (String)request.getAttribute("RelayState") %>
- -
oiosaml.java
- - \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/call_service.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/call_service.jsp deleted file mode 100644 index 60881db..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/call_service.jsp +++ /dev/null @@ -1,22 +0,0 @@ -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="org.example.contract.helloworld.HelloWorldPortType"%> -<%@page import="org.example.contract.helloworld.HelloWorldService"%> - -<% - HelloWorldService service = new HelloWorldService(); - HelloWorldPortType port = service.getHelloWorldPort(); - - String serviceResponse = port.helloWorld("John"); -%> - - - -
-

Result from calling service

- - <% out.println(serviceResponse); %> - -
- - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/logout.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/logout.jsp deleted file mode 100644 index e81ded0..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/logout.jsp +++ /dev/null @@ -1,7 +0,0 @@ -<% - -session.invalidate(); - -response.sendRedirect(request.getContextPath()); - -%> \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/post.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/post.jsp deleted file mode 100644 index 505a7a0..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/post.jsp +++ /dev/null @@ -1,36 +0,0 @@ - -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="dk.itst.oiosaml.sp.UserAssertionHolder"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Utils"%> -<%@page import="dk.itst.oiosaml.sp.util.AttributeUtil"%> -<%@page import="dk.itst.oiosaml.sp.UserAssertion"%> -<%@page import="dk.itst.oiosaml.sp.UserAttribute"%> - - - -

Received request

- - - - - - -<% - -for (Iterator i = request.getParameterMap().entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = (Map.Entry)i.next(); - - for (String val : e.getValue()) { - %> - - <% - } -} -%> - -
Method:<%= request.getMethod() %>
Parameters:
<%= e.getKey() %>:<%= val %>
- - - -<%@page import="java.util.Map"%> -<%@page import="java.util.Iterator"%> diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/priv1.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/priv1.jsp deleted file mode 100644 index f471775..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/priv1.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="dk.itst.oiosaml.sp.UserAssertionHolder"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Utils"%> -<%@page import="dk.itst.oiosaml.sp.util.AttributeUtil"%> -<%@page import="dk.itst.oiosaml.sp.UserAssertion"%> -<%@page import="dk.itst.oiosaml.sp.UserAttribute"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Constants"%> - - <% UserAssertion ua = UserAssertionHolder.get(); %> - - -
-

User NameID

- <%= ua.getSubject() %> - -

Attributes on UserAssertion

-
    - <% - for (UserAttribute a : ua.getAllAttributes()) { - %>
  • <%= Utils.makeXML(a.toString()) %>
  • <% - } - %> -
- -

- Authenticated: <%= ua.isAuthenticated() %>
- Assertion signed: <%= ua.isSigned() %>
- SAML Profile: <%= ua.isOIOSAMLCompliant() %>
- OCES Attribute Profile: <%= ua.isOCESProfileCompliant() %>
- Persistent Pseudonym Profile: <%= ua.isPersistentPseudonymProfileCompliant() %>
- -

- Perform attribute query   - Local logout   Force login - - Call Service - -
- - -
-
oiosaml.java
-
 
-

Assertion:

- <%= Utils.beautifyAndHtmlXML(UserAssertionHolder.get().getXML(), "    ") %> - - -
- <% if (!UserAssertionHolder.get().isAuthenticated()) { %> - Force login
- <% } %> - - - diff --git a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/query.jsp b/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/query.jsp deleted file mode 100644 index bf2a93b..0000000 --- a/examples/lbsb/bootstrap-scenario/src/main/webapp/sp/query.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Utils"%> -<%@page import="dk.itst.oiosaml.sp.util.AttributeUtil"%> -<%@page import="dk.itst.oiosaml.sp.UserAttributeQuery"%> -<%@page import="dk.itst.oiosaml.sp.UserAttribute"%> -<%@page import="java.util.*"%> - - - -

Perform attribute query

- -
- - - - - - - -
NameID:
Attribute:Format:
Attribute:Format:
Attribute:Format:
Attribute:Format:
-
- -<% - -if (request.getParameter("nameId") != null) { - %> -

Attributes

- - <% - UserAttributeQuery aq = new UserAttributeQuery(); - - List names = new ArrayList(); - String[] reqnames = request.getParameterValues("attribute"); - for (int i = 0; i < reqnames.length; i++) { - if (reqnames[i] != null && !"".equals(reqnames[i])) { - names.add(UserAttribute.create(reqnames[i], request.getParameterValues("format")[i])); - } - } - UserAssertion ua = (UserAssertion)session.getAttribute(Constants.SESSION_USER_ASSERTION); - - Collection attrs = aq.query(request.getParameter("nameId"), ua.getNameIDFormat(), names.toArray(new UserAttribute[0])); - - for (UserAttribute attr: attrs) { - %><% - } - %>
AttributeValue
<%= attr.getName() %><%= attr.getValue() %>
<% -} - -%> - - - -<%@page import="dk.itst.oiosaml.sp.UserAssertion"%> -<%@page import="dk.itst.oiosaml.sp.service.util.Constants"%> \ No newline at end of file diff --git a/examples/lbsb/bootstrap-scenario/ssl-keystore b/examples/lbsb/bootstrap-scenario/ssl-keystore deleted file mode 100644 index 2c76af6..0000000 Binary files a/examples/lbsb/bootstrap-scenario/ssl-keystore and /dev/null differ diff --git a/examples/lbsb/pom.xml b/examples/lbsb/pom.xml deleted file mode 100644 index 80999a3..0000000 --- a/examples/lbsb/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-examples-parent - 1.0.0-SNAPSHOT - - reference-lbsb-parent - pom - LBSB Examples Parent - 1.0.0-SNAPSHOT - - - service-hok - service-bearer - system-user-scenario - bootstrap-scenario - signature-scenario - - diff --git a/examples/lbsb/service-bearer/pom.xml b/examples/lbsb/service-bearer/pom.xml deleted file mode 100644 index 0017995..0000000 --- a/examples/lbsb/service-bearer/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-lbsb-parent - 1.0.0-SNAPSHOT - - war - cxf-wsp-lbsb-bearer - CXF WS Provider for Bearer Tokens (LBSB) - - - - - org.apache.cxf - cxf-codegen-plugin - - - - - ${basedir}/target/generated-sources - - - - - ${basedir}/src/main/resources/HelloWorld-Bearer.wsdl - - classpath:HelloWorld-Bearer.wsdl - - - - - - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - - - - maven-war-plugin - - src/main/webapp/WEB-INF/web.xml - - - src/main/resources - WEB-INF/wsdl - - *.wsdl - - - - - - - - HelloWorld - - - - - org.springframework - spring-web - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - org.apache.cxf - cxf-rt-transports-http - - - - org.apache.cxf - cxf-rt-ws-security - - - - commons-io - commons-io - - - - javax.servlet - servlet-api - provided - - - diff --git a/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/WSDocInfo.java b/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/WSDocInfo.java deleted file mode 100644 index 52eefcd..0000000 --- a/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/WSDocInfo.java +++ /dev/null @@ -1,335 +0,0 @@ -// NOTE!!! -// -// This is a copy of WSDocInfo.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the getResult() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it does not return the ID -// of the actual decrypted assertion, but rather the ID of the embedded EncryptedData -// element, which does not exist on the WSP side after decryption. - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom; - -/** - * WSDocInfo holds information about the document to process. It provides a - * method to store and access document information about BinarySecurityToken, - * used Crypto, and others. - * - * Using the Document's hash a caller can identify a document and get - * the stored information that me be necessary to process the document. - * The main usage for this is (are) the transformation functions that - * are called during Signature/Verification process. - */ - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.crypto.dom.DOMCryptoContext; - -import org.apache.wss4j.common.crypto.Crypto; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.dom.message.CallbackLookup; -import org.apache.wss4j.dom.util.WSSecurityUtil; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class WSDocInfo { - private Document doc; - private Crypto crypto; - private List tokenList; - private List resultsList; - private CallbackLookup callbackLookup; - private Element securityHeader; - - public WSDocInfo(Document doc) { - // - // This is a bit of a hack. When the Document is a SAAJ SOAPPart instance, it may - // be that the "owner" document of any child elements is an internal Document, rather - // than the SOAPPart. This is the case for the SUN SAAJ implementation. - // - if (doc != null && doc.getDocumentElement() != null) { - this.doc = doc.getDocumentElement().getOwnerDocument(); - } else { - this.doc = doc; - } - } - - /** - * Clears the data stored in this object - */ - public void clear() { - crypto = null; - if (tokenList != null && tokenList.size() > 0) { - tokenList.clear(); - } - if (resultsList != null && resultsList.size() > 0) { - resultsList.clear(); - } - - tokenList = null; - resultsList = null; - } - - /** - * Store a token element for later retrieval. Before storing the token, we check for a - * previously processed token with the same (wsu/SAML) Id. - * @param element is the token element to store - */ - public void addTokenElement(Element element) throws WSSecurityException { - addTokenElement(element, true); - } - - /** - * Store a token element for later retrieval. Before storing the token, we check for a - * previously processed token with the same (wsu/SAML) Id. - * @param element is the token element to store - * @param checkMultipleElements check for a previously stored element with the same Id. - */ - public void addTokenElement(Element element, boolean checkMultipleElements) throws WSSecurityException { - if (tokenList == null) { - tokenList = new ArrayList(); - } - - if (checkMultipleElements) { - for (Element elem : tokenList) { - if (compareElementsById(element, elem)) { - throw new WSSecurityException( - WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "duplicateError" - ); - } - } - } - tokenList.add(element); - } - - private boolean compareElementsById(Element firstElement, Element secondElement) { - if (firstElement.hasAttributeNS(WSConstants.WSU_NS, "Id") - && secondElement.hasAttributeNS(WSConstants.WSU_NS, "Id")) { - String id = firstElement.getAttributeNS(WSConstants.WSU_NS, "Id"); - String id2 = secondElement.getAttributeNS(WSConstants.WSU_NS, "Id"); - if (id.equals(id2)) { - return true; - } - } - if (firstElement.hasAttributeNS(null, "AssertionID") - && secondElement.hasAttributeNS(null, "AssertionID")) { - String id = firstElement.getAttributeNS(null, "AssertionID"); - String id2 = secondElement.getAttributeNS(null, "AssertionID"); - if (id.equals(id2)) { - return true; - } - } - if (firstElement.hasAttributeNS(null, "ID") && secondElement.hasAttributeNS(null, "ID")) { - String id = firstElement.getAttributeNS(null, "ID"); - String id2 = secondElement.getAttributeNS(null, "ID"); - if (id.equals(id2)) { - return true; - } - } - return false; - } - - /** - * Get a token Element for the given Id. The Id can be either a wsu:Id or a - * SAML AssertionID/ID. - * @param uri is the (relative) uri of the id - * @return the token element or null if nothing found - */ - public Element getTokenElement(String uri) { - String id = uri; - if (id == null) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (tokenList != null) { - for (Element elem : tokenList) { - String cId = elem.getAttributeNS(WSConstants.WSU_NS, "Id"); - String samlId = elem.getAttributeNS(null, "AssertionID"); - String samlId2 = elem.getAttributeNS(null, "ID"); - if (elem.hasAttributeNS(WSConstants.WSU_NS, "Id") && id.equals(cId) - || elem.hasAttributeNS(null, "AssertionID") && id.equals(samlId) - || elem.hasAttributeNS(null, "ID") && id.equals(samlId2)) { - return elem; - } - } - } - return null; - } - - /** - * Set all stored tokens on the DOMCryptoContext argument - * @param context - */ - public void setTokensOnContext(DOMCryptoContext context) { - if (tokenList != null) { - for (Element elem : tokenList) { - WSSecurityUtil.storeElementInContext(context, elem); - } - } - } - - /** - * Store a WSSecurityEngineResult for later retrieval. - * @param result is the WSSecurityEngineResult to store - */ - public void addResult(WSSecurityEngineResult result) { - if (resultsList == null) { - resultsList = new ArrayList(); - } - resultsList.add(result); - } - - /** - * Get a WSSecurityEngineResult for the given Id. - * @param uri is the (relative) uri of the id - * @return the WSSecurityEngineResult or null if nothing found - */ - public WSSecurityEngineResult getResult(String uri) { - String id = uri; - if (id == null) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - - // START DIGST WORKAROUND - if ("encryptedassertion".equals(id)) { - Object samlAssertion = result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); - - if (samlAssertion != null) { - return result; - } - } - // END DIGST WORKAROUND - - String cId = (String)result.get(WSSecurityEngineResult.TAG_ID); - if (id.equals(cId)) { - return result; - } - } - } - } - return null; - } - - /** - * Get a list of WSSecurityEngineResults of the given Integer tag - */ - public List getResultsByTag(Integer tag) { - List foundResults = new ArrayList(); - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - Integer resultTag = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION); - if (tag.intValue() == resultTag.intValue()) { - foundResults.add(result); - } - } - } - } - return foundResults; - } - - /** - * Get a WSSecurityEngineResult of the given Integer tag for the given Id - */ - public WSSecurityEngineResult getResultByTag(Integer tag, String uri) { - String id = uri; - if (id == null || "".equals(uri)) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - Integer resultTag = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION); - String cId = (String)result.get(WSSecurityEngineResult.TAG_ID); - if (tag.intValue() == resultTag.intValue() && id.equals(cId)) { - return result; - } - } - } - } - return null; - } - - /** - * @return the signature crypto class used to process - * the signature/verify - */ - public Crypto getCrypto() { - return crypto; - } - - /** - * @return the document - */ - public Document getDocument() { - return doc; - } - - /** - * @param crypto is the signature crypto class used to - * process signature/verify - */ - public void setCrypto(Crypto crypto) { - this.crypto = crypto; - } - - /** - * @param callbackLookup The CallbackLookup object to retrieve elements - */ - public void setCallbackLookup(CallbackLookup callbackLookup) { - this.callbackLookup = callbackLookup; - } - - /** - * @return the CallbackLookup object to retrieve elements - */ - public CallbackLookup getCallbackLookup() { - return callbackLookup; - } - - /** - * @return the wsse header being processed - */ - public Element getSecurityHeader() { - return securityHeader; - } - - /** - * Sets the wsse header being processed - * - * @param securityHeader - */ - public void setSecurityHeader(Element securityHeader) { - this.securityHeader = securityHeader; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java b/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java deleted file mode 100644 index 9982d60..0000000 --- a/examples/lbsb/service-bearer/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java +++ /dev/null @@ -1,299 +0,0 @@ -// NOTE!!! -// -// This is a copy of STRTransform.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the transformIt() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it returns an EncryptedAssertion -// element with an embedded EncryptedData element. On the WSC side, the STR-Transform -// canonization will inherit the parent namespace (from the EncryptedAssertion element), -// but this does not exist on the WSP side, so the two sides will not generate the same -// digest (resulting in a failed signature validation), unless this workaround is applied. - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom.transform; - -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSDocInfo; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.message.token.PKIPathSecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; - -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignatureInput; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import java.io.ByteArrayInputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Iterator; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.NodeSetData; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - - -/** - * Class STRTransform. - */ -public class STRTransform extends TransformService { - - public static final String TRANSFORM_URI = - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform"; - - public static final String TRANSFORM_WS_DOC_INFO = "transform_ws_doc_info"; - - private TransformParameterSpec params; - - private Element transformElement; - - private static final org.slf4j.Logger LOG = - org.slf4j.LoggerFactory.getLogger(STRTransform.class); - - public final AlgorithmParameterSpec getParameterSpec() { - return params; - } - - public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { - this.params = params; - } - - public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - transformElement = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - } - - public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - Element transformElement2 = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - appendChild(transformElement2, transformElement); - transformElement = transformElement2; - } - - - public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - return transformIt(data, xc, null); - } - - public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - if (os == null) { - throw new NullPointerException("output stream must not be null"); - } - return transformIt(data, xc, os); - } - - - private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - - // - // First step: Get the required c14n argument and get the specified - // Canonicalizer - // - String canonAlgo = null; - Element transformParams = WSSecurityUtil.getDirectChildElement( - transformElement, "TransformationParameters", WSConstants.WSSE_NS - ); - if (transformParams != null) { - Element canonElem = - WSSecurityUtil.getDirectChildElement( - transformParams, "CanonicalizationMethod", WSConstants.SIG_NS - ); - canonAlgo = canonElem.getAttributeNS(null, "Algorithm"); - } - try { - // - // Get the input (node) to transform. - // - Element str = null; - if (data instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)data; - Iterator iterator = nodeSetData.iterator(); - while (iterator.hasNext()) { - Node node = (Node)iterator.next(); - if (node instanceof Element && "SecurityTokenReference".equals(node.getLocalName())) { - str = (Element)node; - break; - } - } - } else { - try { - XMLSignatureInput xmlSignatureInput = - new XMLSignatureInput(((OctetStreamData)data).getOctetStream()); - str = (Element)xmlSignatureInput.getSubNode(); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - if (str == null) { - throw new TransformException("No SecurityTokenReference found"); - } - // - // The element to transform MUST be a SecurityTokenReference - // element. - // - SecurityTokenReference secRef = new SecurityTokenReference(str, new BSPEnforcer()); - - Canonicalizer canon = Canonicalizer.getInstance(canonAlgo); - - byte[] buf = null; - - // - // Third and fourth step are performed by dereferenceSTR() - // - Object wsDocInfoObject = xc.getProperty(TRANSFORM_WS_DOC_INFO); - WSDocInfo wsDocInfo = null; - if (wsDocInfoObject instanceof WSDocInfo) { - wsDocInfo = (WSDocInfo)wsDocInfoObject; - } - if (wsDocInfo == null) { - LOG.debug("STRTransform: no WSDocInfo found"); - } - - Document doc = str.getOwnerDocument(); - Element dereferencedToken = - STRTransformUtil.dereferenceSTR(doc, secRef, wsDocInfo); - - if (dereferencedToken != null) { - String type = dereferencedToken.getAttributeNS(null, "ValueType"); - if (X509Security.X509_V3_TYPE.equals(type) - || PKIPathSecurity.getType().equals(type)) { - // - // Add the WSSE/WSU namespaces to the element for C14n - // - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX - ); - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSU_NS, WSConstants.WSU_PREFIX - ); - } - } - - // BEGIN DIGST WORKAROUND - boolean parentNodeIsNull = (dereferencedToken.getParentNode() == null); - boolean encryptedAssertionId = (dereferencedToken.getAttribute("wsu:Id") != null && dereferencedToken.getAttribute("wsu:Id").equals("encryptedassertion")); - - if (parentNodeIsNull && encryptedAssertionId) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = factory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Element encryptedAssertion = document.createElement("EncryptedAssertion"); - encryptedAssertion.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:oasis:names:tc:SAML:2.0:assertion"); - dereferencedToken = (Element) document.importNode(dereferencedToken, true); - encryptedAssertion.appendChild(dereferencedToken); - - dereferencedToken = encryptedAssertion; - - NodeList securityTokenReferences = dereferencedToken.getElementsByTagName("o:SecurityTokenReference"); - if ((securityTokenReferences.getLength() > 0) && ((securityTokenReferences.item(0) instanceof Element))) { - Element securityTokenReference = (Element) securityTokenReferences.item(0); - securityTokenReference.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); - } - } - // END DIGST WORKAROUND - - // - // C14n with specified algorithm. According to WSS Specification. - // - buf = canon.canonicalizeSubtree(dereferencedToken, "#default", true); - if (LOG.isDebugEnabled()) { - LOG.debug("after c14n: " + new String(buf, "UTF-8")); - } - - if (os != null) { - os.write(buf); - return null; - } - return new OctetStreamData(new ByteArrayInputStream(buf)); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - - - public final boolean isFeatureSupported(String feature) { - if (feature == null) { - throw new NullPointerException(); - } else { - return false; - } - } - - private static void appendChild(Node parent, Node child) { - Document ownerDoc = null; - if (parent.getNodeType() == Node.DOCUMENT_NODE) { - ownerDoc = (Document)parent; - } else { - ownerDoc = parent.getOwnerDocument(); - } - if (child.getOwnerDocument() != ownerDoc) { - parent.appendChild(ownerDoc.importNode(child, true)); - } else { - parent.appendChild(child); - } - } - -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/HelloWorldPortTypeImpl.java b/examples/lbsb/service-bearer/src/main/java/service/HelloWorldPortTypeImpl.java deleted file mode 100644 index 10f5a95..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/HelloWorldPortTypeImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package service; - -import javax.jws.WebService; - -import org.apache.cxf.annotations.EndpointProperties; -import org.apache.cxf.annotations.EndpointProperty; -import org.example.contract.helloworld.HelloWorldPortType; - -import service.bpp.PrivilegeGroupType; -import service.bpp.PrivilegeListType; -import service.saml.AssertionHolder; - -@WebService(targetNamespace = "http://www.example.org/contract/HelloWorld", - portName = "HelloWorldPort", - serviceName = "HelloWorldService", - endpointInterface = "org.example.contract.helloworld.HelloWorldPortType") -@EndpointProperties(value = { - @EndpointProperty(key = "ws-security.asymmetric.signature.algorithm", value = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") - }) -public class HelloWorldPortTypeImpl implements HelloWorldPortType { - - @Override - public String helloWorld(String name) { - // get the Privileges from the presented token - PrivilegeListType privilegeListType = AssertionHolder.get(); - - // print the privileges - if (privilegeListType != null) { - for (PrivilegeGroupType privilegeGroup : privilegeListType.getPrivilegeGroup()) { - System.out.println("scope: " + privilegeGroup.getScope()); - - for (String privilegeString : privilegeGroup.getPrivilege()) { - System.out.println("privilege: " + privilegeString); - } - } - } - - return "Hello " + name; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/bpp/ObjectFactory.java b/examples/lbsb/service-bearer/src/main/java/service/bpp/ObjectFactory.java deleted file mode 100644 index 25826d9..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/bpp/ObjectFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package service.bpp; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - -@XmlRegistry -public class ObjectFactory { - - private final static QName _PrivilegeList_QNAME = new QName("http://itst.dk/oiosaml/basic_privilege_profile", "PrivilegeList"); - - public ObjectFactory() { } - - public PrivilegeListType createPrivilegeListType() { - return new PrivilegeListType(); - } - - public PrivilegeGroupType createPrivilegeGroupType() { - return new PrivilegeGroupType(); - } - - @XmlElementDecl(namespace = "http://itst.dk/oiosaml/basic_privilege_profile", name = "PrivilegeList") - public JAXBElement createPrivilegeList(PrivilegeListType value) { - return new JAXBElement(_PrivilegeList_QNAME, PrivilegeListType.class, null, value); - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeGroupType.java b/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeGroupType.java deleted file mode 100644 index 4b4a7a7..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeGroupType.java +++ /dev/null @@ -1,37 +0,0 @@ -package service.bpp; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "PrivilegeGroupType", propOrder = { "privilege" }) -public class PrivilegeGroupType { - - @XmlElement(name = "Privilege", required = true) - protected List privilege; - - @XmlAttribute(name = "Scope", required = true) - protected String scope; - - public List getPrivilege() { - if (privilege == null) { - privilege = new ArrayList(); - } - - return this.privilege; - } - - public String getScope() { - return scope; - } - - public void setScope(String value) { - this.scope = value; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeListType.java b/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeListType.java deleted file mode 100644 index 68ebf12..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/bpp/PrivilegeListType.java +++ /dev/null @@ -1,25 +0,0 @@ -package service.bpp; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "PrivilegeListType", propOrder = { "privilegeGroup" }) -public class PrivilegeListType { - - @XmlElement(name = "PrivilegeGroup", required = true) - protected List privilegeGroup; - - public List getPrivilegeGroup() { - if (privilegeGroup == null) { - privilegeGroup = new ArrayList(); - } - - return this.privilegeGroup; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/bpp/package-info.java b/examples/lbsb/service-bearer/src/main/java/service/bpp/package-info.java deleted file mode 100644 index d0bd8ca..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/bpp/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://itst.dk/oiosaml/basic_privilege_profile") -package service.bpp; diff --git a/examples/lbsb/service-bearer/src/main/java/service/callback/KeystorePasswordCallback.java b/examples/lbsb/service-bearer/src/main/java/service/callback/KeystorePasswordCallback.java deleted file mode 100644 index b50bde1..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/callback/KeystorePasswordCallback.java +++ /dev/null @@ -1,24 +0,0 @@ -package service.callback; - -import java.io.IOException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.wss4j.common.ext.WSPasswordCallback; - -public class KeystorePasswordCallback implements CallbackHandler { - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (int i = 0; i < callbacks.length; i++) { - WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; - - int usage = pc.getUsage(); - if (usage == WSPasswordCallback.DECRYPT || usage == WSPasswordCallback.SIGNATURE) { - pc.setPassword("Test1234"); - } - } - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java b/examples/lbsb/service-bearer/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java deleted file mode 100644 index 49174c8..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package service.interceptor; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapHeader; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; - -import service.model.SbfFrameworkHeader; - -public class FrameworkHeaderInterceptor extends AbstractSoapInterceptor { - public FrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - try { - Header framework = new SoapHeader(new QName("urn:liberty:sb", "Framework", "sbf"), new SbfFrameworkHeader(), new JAXBDataBinding(SbfFrameworkHeader.class)); - headers.add(framework); - } - catch (Exception ex) { - throw new XMLFault(ex.getMessage()); - } - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java b/examples/lbsb/service-bearer/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java deleted file mode 100644 index 36d5a9c..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package service.interceptor; - -import java.util.HashSet; -import java.util.Set; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.phase.Phase; - -public class UnderstandFrameworkHeaderInterceptor extends AbstractSoapInterceptor { - private static final QName frameworkQName = new QName("urn:liberty:sb", "Framework", "sbf"); - - public UnderstandFrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - Header framework = message.getHeader(frameworkQName); - - // extremely simple validation of the headers presence - if (framework == null) { - throw new XMLFault("Missing framework header"); - } - } - - @Override - public Set getUnderstoodHeaders() { - Set set = new HashSet<>(); - - set.add(frameworkQName); - - return set; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/model/SbfFrameworkHeader.java b/examples/lbsb/service-bearer/src/main/java/service/model/SbfFrameworkHeader.java deleted file mode 100644 index 343533f..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/model/SbfFrameworkHeader.java +++ /dev/null @@ -1,22 +0,0 @@ -package service.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; - -@XmlAccessorType(XmlAccessType.FIELD) -public class SbfFrameworkHeader { - @XmlAttribute(name="version") - private final String version = "2.0"; - - @XmlAttribute(name="profile", namespace="urn:liberty:sb:profile") - private final String profile = "urn:liberty:sb:profile:basic"; - - public String getVersion() { - return version; - } - - public String getProfile() { - return profile; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/saml/AssertionHolder.java b/examples/lbsb/service-bearer/src/main/java/service/saml/AssertionHolder.java deleted file mode 100644 index 79a32f9..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/saml/AssertionHolder.java +++ /dev/null @@ -1,19 +0,0 @@ -package service.saml; - -import service.bpp.PrivilegeListType; - -public class AssertionHolder { - private static final ThreadLocal privileges = new ThreadLocal<>(); - - public static void set(PrivilegeListType privilege) { - privileges.set(privilege); - } - - public static PrivilegeListType get() { - return privileges.get(); - } - - public static void clear() { - privileges.remove(); - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/saml/DigstSamlAssertionValidator.java b/examples/lbsb/service-bearer/src/main/java/service/saml/DigstSamlAssertionValidator.java deleted file mode 100644 index 26297cf..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/saml/DigstSamlAssertionValidator.java +++ /dev/null @@ -1,77 +0,0 @@ -package service.saml; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Unmarshaller; - -import org.apache.commons.codec.binary.Base64; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.common.saml.SamlAssertionWrapper; -import org.apache.wss4j.dom.handler.RequestData; -import org.apache.wss4j.dom.validate.Credential; -import org.apache.wss4j.dom.validate.SamlAssertionValidator; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.xml.XMLObject; - -import service.bpp.ObjectFactory; -import service.bpp.PrivilegeListType; - -public class DigstSamlAssertionValidator extends SamlAssertionValidator { - // Hard-coded expected audience in token. Multiple values can be added if needed - private List audienceRestrictions = new ArrayList() { - private static final long serialVersionUID = 1L; - - { - add("https://wsp.itcrew.dk"); - } - }; - - @SuppressWarnings("unchecked") - @Override - public Credential validate(Credential credential, RequestData data) throws WSSecurityException { - // Set the valid audiences for this request - data.setAudienceRestrictions(audienceRestrictions); - - // Perform the actual validation - Credential validatedCredential = super.validate(credential, data); - - // Extract the Basic Privilege Profile attribute and place it on a ThreadLocal for later use - SamlAssertionWrapper samlAssertion = credential.getSamlAssertion(); - - if (samlAssertion.getSaml2() != null) { - Assertion saml2 = samlAssertion.getSaml2(); - - for (AttributeStatement attributeStatement : saml2.getAttributeStatements()) { - for (Attribute attribute : attributeStatement.getAttributes()) { - if ("Privileges".equals(attribute.getFriendlyName())) { - for (XMLObject attributeValue : attribute.getAttributeValues()) { - if (!attributeValue.isNil()) { - String privilege = attributeValue.getDOM().getTextContent(); - byte[] privilegeBytes = Base64.decodeBase64(privilege); - - try { - JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); - Unmarshaller unmarsheller = context.createUnmarshaller(); - JAXBElement privilegeList = (JAXBElement) unmarsheller.unmarshal(new ByteArrayInputStream(privilegeBytes)); - - AssertionHolder.set(privilegeList.getValue()); - } - catch (Exception ex) { - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); - } - } - } - } - } - } - } - - return validatedCredential; - } -} diff --git a/examples/lbsb/service-bearer/src/main/java/service/saml/SamlFilter.java b/examples/lbsb/service-bearer/src/main/java/service/saml/SamlFilter.java deleted file mode 100644 index 15691d4..0000000 --- a/examples/lbsb/service-bearer/src/main/java/service/saml/SamlFilter.java +++ /dev/null @@ -1,29 +0,0 @@ -package service.saml; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -public class SamlFilter implements Filter { - - @Override - public void init(FilterConfig filterConfig) throws ServletException { } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - try { - chain.doFilter(request, response); - } - finally { - AssertionHolder.clear(); - } - } - - @Override - public void destroy() { } -} diff --git a/examples/lbsb/service-bearer/src/main/resources/HelloWorld-Bearer.wsdl b/examples/lbsb/service-bearer/src/main/resources/HelloWorld-Bearer.wsdl deleted file mode 100644 index 7577cfe..0000000 --- a/examples/lbsb/service-bearer/src/main/resources/HelloWorld-Bearer.wsdl +++ /dev/null @@ -1,164 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/service-bearer/src/main/resources/service.pfx b/examples/lbsb/service-bearer/src/main/resources/service.pfx deleted file mode 100644 index 2e6309e..0000000 Binary files a/examples/lbsb/service-bearer/src/main/resources/service.pfx and /dev/null differ diff --git a/examples/lbsb/service-bearer/src/main/resources/serviceKeystore.properties b/examples/lbsb/service-bearer/src/main/resources/serviceKeystore.properties deleted file mode 100644 index 80931df..0000000 --- a/examples/lbsb/service-bearer/src/main/resources/serviceKeystore.properties +++ /dev/null @@ -1,8 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=eid java test (funktionscertifikat) -org.apache.ws.security.crypto.merlin.file=service.pfx - -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/service-bearer/src/main/resources/trust.jks b/examples/lbsb/service-bearer/src/main/resources/trust.jks deleted file mode 100644 index fa6d9a6..0000000 Binary files a/examples/lbsb/service-bearer/src/main/resources/trust.jks and /dev/null differ diff --git a/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/cxf-servlet.xml b/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 3d4dfe7..0000000 --- a/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/web.xml b/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index e4521c0..0000000 --- a/examples/lbsb/service-bearer/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - Apache CXF WebService Provider - - - - org.springframework.web.context.ContextLoaderListener - - - - - contextConfigLocation - - classpath:META-INF/cxf/cxf.xml - - - - - SamlFilter - service.saml.SamlFilter - - - - SamlFilter - * - - - - WebServicePort - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - - WebServicePort - /services/* - - - - 60 - - diff --git a/examples/lbsb/service-hok/pom.xml b/examples/lbsb/service-hok/pom.xml deleted file mode 100644 index 70ecb72..0000000 --- a/examples/lbsb/service-hok/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-lbsb-parent - 1.0.0-SNAPSHOT - - war - cxf-wsp-lbsb-hok - CXF WS Provider for Holder of Key Tokens (LBSB) - - - - - org.apache.cxf - cxf-codegen-plugin - - - - - ${basedir}/target/generated-sources - - - - - ${basedir}/src/main/resources/HelloWorld-Hok.wsdl - - classpath:HelloWorld-Hok.wsdl - - - - - - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - - - - maven-war-plugin - - src/main/webapp/WEB-INF/web.xml - - - src/main/resources - WEB-INF/wsdl - - *.wsdl - - - - - - - - HelloWorld - - - - - org.springframework - spring-web - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - org.apache.cxf - cxf-rt-transports-http - - - - org.apache.cxf - cxf-rt-ws-security - - - - commons-io - commons-io - - - - javax.servlet - servlet-api - provided - - - diff --git a/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/WSDocInfo.java b/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/WSDocInfo.java deleted file mode 100644 index 52eefcd..0000000 --- a/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/WSDocInfo.java +++ /dev/null @@ -1,335 +0,0 @@ -// NOTE!!! -// -// This is a copy of WSDocInfo.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the getResult() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it does not return the ID -// of the actual decrypted assertion, but rather the ID of the embedded EncryptedData -// element, which does not exist on the WSP side after decryption. - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom; - -/** - * WSDocInfo holds information about the document to process. It provides a - * method to store and access document information about BinarySecurityToken, - * used Crypto, and others. - * - * Using the Document's hash a caller can identify a document and get - * the stored information that me be necessary to process the document. - * The main usage for this is (are) the transformation functions that - * are called during Signature/Verification process. - */ - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.crypto.dom.DOMCryptoContext; - -import org.apache.wss4j.common.crypto.Crypto; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.dom.message.CallbackLookup; -import org.apache.wss4j.dom.util.WSSecurityUtil; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class WSDocInfo { - private Document doc; - private Crypto crypto; - private List tokenList; - private List resultsList; - private CallbackLookup callbackLookup; - private Element securityHeader; - - public WSDocInfo(Document doc) { - // - // This is a bit of a hack. When the Document is a SAAJ SOAPPart instance, it may - // be that the "owner" document of any child elements is an internal Document, rather - // than the SOAPPart. This is the case for the SUN SAAJ implementation. - // - if (doc != null && doc.getDocumentElement() != null) { - this.doc = doc.getDocumentElement().getOwnerDocument(); - } else { - this.doc = doc; - } - } - - /** - * Clears the data stored in this object - */ - public void clear() { - crypto = null; - if (tokenList != null && tokenList.size() > 0) { - tokenList.clear(); - } - if (resultsList != null && resultsList.size() > 0) { - resultsList.clear(); - } - - tokenList = null; - resultsList = null; - } - - /** - * Store a token element for later retrieval. Before storing the token, we check for a - * previously processed token with the same (wsu/SAML) Id. - * @param element is the token element to store - */ - public void addTokenElement(Element element) throws WSSecurityException { - addTokenElement(element, true); - } - - /** - * Store a token element for later retrieval. Before storing the token, we check for a - * previously processed token with the same (wsu/SAML) Id. - * @param element is the token element to store - * @param checkMultipleElements check for a previously stored element with the same Id. - */ - public void addTokenElement(Element element, boolean checkMultipleElements) throws WSSecurityException { - if (tokenList == null) { - tokenList = new ArrayList(); - } - - if (checkMultipleElements) { - for (Element elem : tokenList) { - if (compareElementsById(element, elem)) { - throw new WSSecurityException( - WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "duplicateError" - ); - } - } - } - tokenList.add(element); - } - - private boolean compareElementsById(Element firstElement, Element secondElement) { - if (firstElement.hasAttributeNS(WSConstants.WSU_NS, "Id") - && secondElement.hasAttributeNS(WSConstants.WSU_NS, "Id")) { - String id = firstElement.getAttributeNS(WSConstants.WSU_NS, "Id"); - String id2 = secondElement.getAttributeNS(WSConstants.WSU_NS, "Id"); - if (id.equals(id2)) { - return true; - } - } - if (firstElement.hasAttributeNS(null, "AssertionID") - && secondElement.hasAttributeNS(null, "AssertionID")) { - String id = firstElement.getAttributeNS(null, "AssertionID"); - String id2 = secondElement.getAttributeNS(null, "AssertionID"); - if (id.equals(id2)) { - return true; - } - } - if (firstElement.hasAttributeNS(null, "ID") && secondElement.hasAttributeNS(null, "ID")) { - String id = firstElement.getAttributeNS(null, "ID"); - String id2 = secondElement.getAttributeNS(null, "ID"); - if (id.equals(id2)) { - return true; - } - } - return false; - } - - /** - * Get a token Element for the given Id. The Id can be either a wsu:Id or a - * SAML AssertionID/ID. - * @param uri is the (relative) uri of the id - * @return the token element or null if nothing found - */ - public Element getTokenElement(String uri) { - String id = uri; - if (id == null) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (tokenList != null) { - for (Element elem : tokenList) { - String cId = elem.getAttributeNS(WSConstants.WSU_NS, "Id"); - String samlId = elem.getAttributeNS(null, "AssertionID"); - String samlId2 = elem.getAttributeNS(null, "ID"); - if (elem.hasAttributeNS(WSConstants.WSU_NS, "Id") && id.equals(cId) - || elem.hasAttributeNS(null, "AssertionID") && id.equals(samlId) - || elem.hasAttributeNS(null, "ID") && id.equals(samlId2)) { - return elem; - } - } - } - return null; - } - - /** - * Set all stored tokens on the DOMCryptoContext argument - * @param context - */ - public void setTokensOnContext(DOMCryptoContext context) { - if (tokenList != null) { - for (Element elem : tokenList) { - WSSecurityUtil.storeElementInContext(context, elem); - } - } - } - - /** - * Store a WSSecurityEngineResult for later retrieval. - * @param result is the WSSecurityEngineResult to store - */ - public void addResult(WSSecurityEngineResult result) { - if (resultsList == null) { - resultsList = new ArrayList(); - } - resultsList.add(result); - } - - /** - * Get a WSSecurityEngineResult for the given Id. - * @param uri is the (relative) uri of the id - * @return the WSSecurityEngineResult or null if nothing found - */ - public WSSecurityEngineResult getResult(String uri) { - String id = uri; - if (id == null) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - - // START DIGST WORKAROUND - if ("encryptedassertion".equals(id)) { - Object samlAssertion = result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); - - if (samlAssertion != null) { - return result; - } - } - // END DIGST WORKAROUND - - String cId = (String)result.get(WSSecurityEngineResult.TAG_ID); - if (id.equals(cId)) { - return result; - } - } - } - } - return null; - } - - /** - * Get a list of WSSecurityEngineResults of the given Integer tag - */ - public List getResultsByTag(Integer tag) { - List foundResults = new ArrayList(); - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - Integer resultTag = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION); - if (tag.intValue() == resultTag.intValue()) { - foundResults.add(result); - } - } - } - } - return foundResults; - } - - /** - * Get a WSSecurityEngineResult of the given Integer tag for the given Id - */ - public WSSecurityEngineResult getResultByTag(Integer tag, String uri) { - String id = uri; - if (id == null || "".equals(uri)) { - return null; - } else if (id.charAt(0) == '#') { - id = id.substring(1); - } - if (resultsList != null) { - for (WSSecurityEngineResult result : resultsList) { - if (result != null) { - Integer resultTag = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION); - String cId = (String)result.get(WSSecurityEngineResult.TAG_ID); - if (tag.intValue() == resultTag.intValue() && id.equals(cId)) { - return result; - } - } - } - } - return null; - } - - /** - * @return the signature crypto class used to process - * the signature/verify - */ - public Crypto getCrypto() { - return crypto; - } - - /** - * @return the document - */ - public Document getDocument() { - return doc; - } - - /** - * @param crypto is the signature crypto class used to - * process signature/verify - */ - public void setCrypto(Crypto crypto) { - this.crypto = crypto; - } - - /** - * @param callbackLookup The CallbackLookup object to retrieve elements - */ - public void setCallbackLookup(CallbackLookup callbackLookup) { - this.callbackLookup = callbackLookup; - } - - /** - * @return the CallbackLookup object to retrieve elements - */ - public CallbackLookup getCallbackLookup() { - return callbackLookup; - } - - /** - * @return the wsse header being processed - */ - public Element getSecurityHeader() { - return securityHeader; - } - - /** - * Sets the wsse header being processed - * - * @param securityHeader - */ - public void setSecurityHeader(Element securityHeader) { - this.securityHeader = securityHeader; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java b/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java deleted file mode 100644 index 9982d60..0000000 --- a/examples/lbsb/service-hok/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java +++ /dev/null @@ -1,299 +0,0 @@ -// NOTE!!! -// -// This is a copy of STRTransform.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the transformIt() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it returns an EncryptedAssertion -// element with an embedded EncryptedData element. On the WSC side, the STR-Transform -// canonization will inherit the parent namespace (from the EncryptedAssertion element), -// but this does not exist on the WSP side, so the two sides will not generate the same -// digest (resulting in a failed signature validation), unless this workaround is applied. - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom.transform; - -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSDocInfo; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.message.token.PKIPathSecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; - -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignatureInput; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import java.io.ByteArrayInputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Iterator; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.NodeSetData; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - - -/** - * Class STRTransform. - */ -public class STRTransform extends TransformService { - - public static final String TRANSFORM_URI = - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform"; - - public static final String TRANSFORM_WS_DOC_INFO = "transform_ws_doc_info"; - - private TransformParameterSpec params; - - private Element transformElement; - - private static final org.slf4j.Logger LOG = - org.slf4j.LoggerFactory.getLogger(STRTransform.class); - - public final AlgorithmParameterSpec getParameterSpec() { - return params; - } - - public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { - this.params = params; - } - - public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - transformElement = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - } - - public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - Element transformElement2 = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - appendChild(transformElement2, transformElement); - transformElement = transformElement2; - } - - - public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - return transformIt(data, xc, null); - } - - public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - if (os == null) { - throw new NullPointerException("output stream must not be null"); - } - return transformIt(data, xc, os); - } - - - private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - - // - // First step: Get the required c14n argument and get the specified - // Canonicalizer - // - String canonAlgo = null; - Element transformParams = WSSecurityUtil.getDirectChildElement( - transformElement, "TransformationParameters", WSConstants.WSSE_NS - ); - if (transformParams != null) { - Element canonElem = - WSSecurityUtil.getDirectChildElement( - transformParams, "CanonicalizationMethod", WSConstants.SIG_NS - ); - canonAlgo = canonElem.getAttributeNS(null, "Algorithm"); - } - try { - // - // Get the input (node) to transform. - // - Element str = null; - if (data instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)data; - Iterator iterator = nodeSetData.iterator(); - while (iterator.hasNext()) { - Node node = (Node)iterator.next(); - if (node instanceof Element && "SecurityTokenReference".equals(node.getLocalName())) { - str = (Element)node; - break; - } - } - } else { - try { - XMLSignatureInput xmlSignatureInput = - new XMLSignatureInput(((OctetStreamData)data).getOctetStream()); - str = (Element)xmlSignatureInput.getSubNode(); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - if (str == null) { - throw new TransformException("No SecurityTokenReference found"); - } - // - // The element to transform MUST be a SecurityTokenReference - // element. - // - SecurityTokenReference secRef = new SecurityTokenReference(str, new BSPEnforcer()); - - Canonicalizer canon = Canonicalizer.getInstance(canonAlgo); - - byte[] buf = null; - - // - // Third and fourth step are performed by dereferenceSTR() - // - Object wsDocInfoObject = xc.getProperty(TRANSFORM_WS_DOC_INFO); - WSDocInfo wsDocInfo = null; - if (wsDocInfoObject instanceof WSDocInfo) { - wsDocInfo = (WSDocInfo)wsDocInfoObject; - } - if (wsDocInfo == null) { - LOG.debug("STRTransform: no WSDocInfo found"); - } - - Document doc = str.getOwnerDocument(); - Element dereferencedToken = - STRTransformUtil.dereferenceSTR(doc, secRef, wsDocInfo); - - if (dereferencedToken != null) { - String type = dereferencedToken.getAttributeNS(null, "ValueType"); - if (X509Security.X509_V3_TYPE.equals(type) - || PKIPathSecurity.getType().equals(type)) { - // - // Add the WSSE/WSU namespaces to the element for C14n - // - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX - ); - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSU_NS, WSConstants.WSU_PREFIX - ); - } - } - - // BEGIN DIGST WORKAROUND - boolean parentNodeIsNull = (dereferencedToken.getParentNode() == null); - boolean encryptedAssertionId = (dereferencedToken.getAttribute("wsu:Id") != null && dereferencedToken.getAttribute("wsu:Id").equals("encryptedassertion")); - - if (parentNodeIsNull && encryptedAssertionId) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = factory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Element encryptedAssertion = document.createElement("EncryptedAssertion"); - encryptedAssertion.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:oasis:names:tc:SAML:2.0:assertion"); - dereferencedToken = (Element) document.importNode(dereferencedToken, true); - encryptedAssertion.appendChild(dereferencedToken); - - dereferencedToken = encryptedAssertion; - - NodeList securityTokenReferences = dereferencedToken.getElementsByTagName("o:SecurityTokenReference"); - if ((securityTokenReferences.getLength() > 0) && ((securityTokenReferences.item(0) instanceof Element))) { - Element securityTokenReference = (Element) securityTokenReferences.item(0); - securityTokenReference.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); - } - } - // END DIGST WORKAROUND - - // - // C14n with specified algorithm. According to WSS Specification. - // - buf = canon.canonicalizeSubtree(dereferencedToken, "#default", true); - if (LOG.isDebugEnabled()) { - LOG.debug("after c14n: " + new String(buf, "UTF-8")); - } - - if (os != null) { - os.write(buf); - return null; - } - return new OctetStreamData(new ByteArrayInputStream(buf)); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - - - public final boolean isFeatureSupported(String feature) { - if (feature == null) { - throw new NullPointerException(); - } else { - return false; - } - } - - private static void appendChild(Node parent, Node child) { - Document ownerDoc = null; - if (parent.getNodeType() == Node.DOCUMENT_NODE) { - ownerDoc = (Document)parent; - } else { - ownerDoc = parent.getOwnerDocument(); - } - if (child.getOwnerDocument() != ownerDoc) { - parent.appendChild(ownerDoc.importNode(child, true)); - } else { - parent.appendChild(child); - } - } - -} diff --git a/examples/lbsb/service-hok/src/main/java/service/HelloWorldPortTypeImpl.java b/examples/lbsb/service-hok/src/main/java/service/HelloWorldPortTypeImpl.java deleted file mode 100644 index 72dadd6..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/HelloWorldPortTypeImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -package service; - -import javax.jws.WebService; - -import org.apache.cxf.annotations.EndpointProperties; -import org.apache.cxf.annotations.EndpointProperty; -import org.example.contract.helloworld.HelloWorldPortType; -import org.example.contract.helloworld.MissingName; - -import service.bpp.PrivilegeGroupType; -import service.bpp.PrivilegeListType; -import service.saml.AssertionHolder; - -@WebService(targetNamespace = "http://www.example.org/contract/HelloWorld", - portName = "HelloWorldPort", - serviceName = "HelloWorldService", - endpointInterface = "org.example.contract.helloworld.HelloWorldPortType") -@EndpointProperties(value = { - @EndpointProperty(key = "ws-security.asymmetric.signature.algorithm", value = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") - }) -public class HelloWorldPortTypeImpl implements HelloWorldPortType { - - @Override - public String helloWorld(String name) throws MissingName { - if (name == null || name.length() == 0) { - throw new MissingName("No name supplied"); - } - - // get the Privileges from the presented token - PrivilegeListType privilegeListType = AssertionHolder.get(); - - // print the privileges - if (privilegeListType != null) { - for (PrivilegeGroupType privilegeGroup : privilegeListType.getPrivilegeGroup()) { - System.out.println("scope: " + privilegeGroup.getScope()); - - for (String privilegeString : privilegeGroup.getPrivilege()) { - System.out.println("privilege: " + privilegeString); - } - } - } - - return "Hello " + name; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/bpp/ObjectFactory.java b/examples/lbsb/service-hok/src/main/java/service/bpp/ObjectFactory.java deleted file mode 100644 index 25826d9..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/bpp/ObjectFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package service.bpp; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - -@XmlRegistry -public class ObjectFactory { - - private final static QName _PrivilegeList_QNAME = new QName("http://itst.dk/oiosaml/basic_privilege_profile", "PrivilegeList"); - - public ObjectFactory() { } - - public PrivilegeListType createPrivilegeListType() { - return new PrivilegeListType(); - } - - public PrivilegeGroupType createPrivilegeGroupType() { - return new PrivilegeGroupType(); - } - - @XmlElementDecl(namespace = "http://itst.dk/oiosaml/basic_privilege_profile", name = "PrivilegeList") - public JAXBElement createPrivilegeList(PrivilegeListType value) { - return new JAXBElement(_PrivilegeList_QNAME, PrivilegeListType.class, null, value); - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeGroupType.java b/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeGroupType.java deleted file mode 100644 index 4b4a7a7..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeGroupType.java +++ /dev/null @@ -1,37 +0,0 @@ -package service.bpp; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "PrivilegeGroupType", propOrder = { "privilege" }) -public class PrivilegeGroupType { - - @XmlElement(name = "Privilege", required = true) - protected List privilege; - - @XmlAttribute(name = "Scope", required = true) - protected String scope; - - public List getPrivilege() { - if (privilege == null) { - privilege = new ArrayList(); - } - - return this.privilege; - } - - public String getScope() { - return scope; - } - - public void setScope(String value) { - this.scope = value; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeListType.java b/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeListType.java deleted file mode 100644 index 68ebf12..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/bpp/PrivilegeListType.java +++ /dev/null @@ -1,25 +0,0 @@ -package service.bpp; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "PrivilegeListType", propOrder = { "privilegeGroup" }) -public class PrivilegeListType { - - @XmlElement(name = "PrivilegeGroup", required = true) - protected List privilegeGroup; - - public List getPrivilegeGroup() { - if (privilegeGroup == null) { - privilegeGroup = new ArrayList(); - } - - return this.privilegeGroup; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/bpp/package-info.java b/examples/lbsb/service-hok/src/main/java/service/bpp/package-info.java deleted file mode 100644 index d0bd8ca..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/bpp/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://itst.dk/oiosaml/basic_privilege_profile") -package service.bpp; diff --git a/examples/lbsb/service-hok/src/main/java/service/callback/KeystorePasswordCallback.java b/examples/lbsb/service-hok/src/main/java/service/callback/KeystorePasswordCallback.java deleted file mode 100644 index b50bde1..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/callback/KeystorePasswordCallback.java +++ /dev/null @@ -1,24 +0,0 @@ -package service.callback; - -import java.io.IOException; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.wss4j.common.ext.WSPasswordCallback; - -public class KeystorePasswordCallback implements CallbackHandler { - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (int i = 0; i < callbacks.length; i++) { - WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; - - int usage = pc.getUsage(); - if (usage == WSPasswordCallback.DECRYPT || usage == WSPasswordCallback.SIGNATURE) { - pc.setPassword("Test1234"); - } - } - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java b/examples/lbsb/service-hok/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java deleted file mode 100644 index 49174c8..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/interceptor/FrameworkHeaderInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package service.interceptor; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapHeader; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; - -import service.model.SbfFrameworkHeader; - -public class FrameworkHeaderInterceptor extends AbstractSoapInterceptor { - public FrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - try { - Header framework = new SoapHeader(new QName("urn:liberty:sb", "Framework", "sbf"), new SbfFrameworkHeader(), new JAXBDataBinding(SbfFrameworkHeader.class)); - headers.add(framework); - } - catch (Exception ex) { - throw new XMLFault(ex.getMessage()); - } - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java b/examples/lbsb/service-hok/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java deleted file mode 100644 index 36d5a9c..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/interceptor/UnderstandFrameworkHeaderInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package service.interceptor; - -import java.util.HashSet; -import java.util.Set; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.phase.Phase; - -public class UnderstandFrameworkHeaderInterceptor extends AbstractSoapInterceptor { - private static final QName frameworkQName = new QName("urn:liberty:sb", "Framework", "sbf"); - - public UnderstandFrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - Header framework = message.getHeader(frameworkQName); - - // extremely simple validation of the headers presence - if (framework == null) { - throw new XMLFault("Missing framework header"); - } - } - - @Override - public Set getUnderstoodHeaders() { - Set set = new HashSet<>(); - - set.add(frameworkQName); - - return set; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/model/SbfFrameworkHeader.java b/examples/lbsb/service-hok/src/main/java/service/model/SbfFrameworkHeader.java deleted file mode 100644 index eb73af5..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/model/SbfFrameworkHeader.java +++ /dev/null @@ -1,23 +0,0 @@ -package service.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; - -@XmlAccessorType(XmlAccessType.FIELD) -public class SbfFrameworkHeader { - - @XmlAttribute(name="version") - private final String version = "2.0"; - - @XmlAttribute(name="profile", namespace="urn:liberty:sb:profile") - private final String profile = "urn:liberty:sb:profile:basic"; - - public String getVersion() { - return version; - } - - public String getProfile() { - return profile; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/saml/AssertionHolder.java b/examples/lbsb/service-hok/src/main/java/service/saml/AssertionHolder.java deleted file mode 100644 index 79a32f9..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/saml/AssertionHolder.java +++ /dev/null @@ -1,19 +0,0 @@ -package service.saml; - -import service.bpp.PrivilegeListType; - -public class AssertionHolder { - private static final ThreadLocal privileges = new ThreadLocal<>(); - - public static void set(PrivilegeListType privilege) { - privileges.set(privilege); - } - - public static PrivilegeListType get() { - return privileges.get(); - } - - public static void clear() { - privileges.remove(); - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/saml/DigstSamlAssertionValidator.java b/examples/lbsb/service-hok/src/main/java/service/saml/DigstSamlAssertionValidator.java deleted file mode 100644 index 5f9724c..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/saml/DigstSamlAssertionValidator.java +++ /dev/null @@ -1,76 +0,0 @@ -package service.saml; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Unmarshaller; - -import org.apache.commons.codec.binary.Base64; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.common.saml.SamlAssertionWrapper; -import org.apache.wss4j.dom.handler.RequestData; -import org.apache.wss4j.dom.validate.Credential; -import org.apache.wss4j.dom.validate.SamlAssertionValidator; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.xml.XMLObject; - -import service.bpp.ObjectFactory; -import service.bpp.PrivilegeListType; - -public class DigstSamlAssertionValidator extends SamlAssertionValidator { - // Hard-coded expected audience in token. Multiple values can be added if needed - private List audienceRestrictions = new ArrayList() { - private static final long serialVersionUID = 1L; - - { - add("https://wsp.itcrew.dk"); - } - }; - - @SuppressWarnings("unchecked") - @Override - public Credential validate(Credential credential, RequestData data) throws WSSecurityException { - // Set the valid audiences for this request - data.setAudienceRestrictions(audienceRestrictions); - - // Perform the actual validation - Credential validatedCredential = super.validate(credential, data); - - // Extract the Basic Privilege Profile attribute and place it on a ThreadLocal for later use - SamlAssertionWrapper samlAssertion = credential.getSamlAssertion(); - if (samlAssertion.getSaml2() != null) { - Assertion saml2 = samlAssertion.getSaml2(); - - for (AttributeStatement attributeStatement : saml2.getAttributeStatements()) { - for (Attribute attribute : attributeStatement.getAttributes()) { - if ("Privileges".equals(attribute.getFriendlyName())) { - for (XMLObject attributeValue : attribute.getAttributeValues()) { - if (!attributeValue.isNil()) { - String privilege = attributeValue.getDOM().getTextContent(); - byte[] privilegeBytes = Base64.decodeBase64(privilege); - - try { - JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); - Unmarshaller unmarsheller = context.createUnmarshaller(); - JAXBElement privilegeList = (JAXBElement) unmarsheller.unmarshal(new ByteArrayInputStream(privilegeBytes)); - - AssertionHolder.set(privilegeList.getValue()); - } - catch (Exception ex) { - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); - } - } - } - } - } - } - } - - return validatedCredential; - } -} diff --git a/examples/lbsb/service-hok/src/main/java/service/saml/SamlFilter.java b/examples/lbsb/service-hok/src/main/java/service/saml/SamlFilter.java deleted file mode 100644 index 15691d4..0000000 --- a/examples/lbsb/service-hok/src/main/java/service/saml/SamlFilter.java +++ /dev/null @@ -1,29 +0,0 @@ -package service.saml; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -public class SamlFilter implements Filter { - - @Override - public void init(FilterConfig filterConfig) throws ServletException { } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - try { - chain.doFilter(request, response); - } - finally { - AssertionHolder.clear(); - } - } - - @Override - public void destroy() { } -} diff --git a/examples/lbsb/service-hok/src/main/resources/HelloWorld-Hok.wsdl b/examples/lbsb/service-hok/src/main/resources/HelloWorld-Hok.wsdl deleted file mode 100644 index 75b24aa..0000000 --- a/examples/lbsb/service-hok/src/main/resources/HelloWorld-Hok.wsdl +++ /dev/null @@ -1,182 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/service-hok/src/main/resources/service.pfx b/examples/lbsb/service-hok/src/main/resources/service.pfx deleted file mode 100644 index 2e6309e..0000000 Binary files a/examples/lbsb/service-hok/src/main/resources/service.pfx and /dev/null differ diff --git a/examples/lbsb/service-hok/src/main/resources/serviceKeystore.properties b/examples/lbsb/service-hok/src/main/resources/serviceKeystore.properties deleted file mode 100644 index 80931df..0000000 --- a/examples/lbsb/service-hok/src/main/resources/serviceKeystore.properties +++ /dev/null @@ -1,8 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=eid java test (funktionscertifikat) -org.apache.ws.security.crypto.merlin.file=service.pfx - -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/service-hok/src/main/resources/trust.jks b/examples/lbsb/service-hok/src/main/resources/trust.jks deleted file mode 100644 index cddcce8..0000000 Binary files a/examples/lbsb/service-hok/src/main/resources/trust.jks and /dev/null differ diff --git a/examples/lbsb/service-hok/src/main/webapp/WEB-INF/cxf-servlet.xml b/examples/lbsb/service-hok/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 49026f0..0000000 --- a/examples/lbsb/service-hok/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/service-hok/src/main/webapp/WEB-INF/web.xml b/examples/lbsb/service-hok/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index e4521c0..0000000 --- a/examples/lbsb/service-hok/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - Apache CXF WebService Provider - - - - org.springframework.web.context.ContextLoaderListener - - - - - contextConfigLocation - - classpath:META-INF/cxf/cxf.xml - - - - - SamlFilter - service.saml.SamlFilter - - - - SamlFilter - * - - - - WebServicePort - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - - WebServicePort - /services/* - - - - 60 - - diff --git a/examples/lbsb/signature-scenario/pom.xml b/examples/lbsb/signature-scenario/pom.xml deleted file mode 100644 index 330c165..0000000 --- a/examples/lbsb/signature-scenario/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-lbsb-parent - 1.0.0-SNAPSHOT - - cxf-wsc-lbsb-signature - CXF WS Consumer for Signature Scenario (LBSB) - jar - - - - - org.codehaus.mojo - exec-maven-plugin - - - - exec - - - - - java - - -classpath - - - client.Application - - - - - - - org.apache.cxf - cxf-codegen-plugin - - - commons-logging - commons-logging - 1.1.1 - - - - - - - ${basedir}/target/generated-sources - - - - - ${basedir}/src/main/resources/HelloWorld-Bearer.wsdl - - classpath:HelloWorld-Bearer.wsdl - - - - - - - - - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - org.apache.cxf - cxf-rt-transports-http - - - - org.apache.cxf - cxf-rt-ws-security - - - - commons-io - commons-io - - - - org.springframework - spring-context - - - - org.slf4j - slf4j-jdk14 - - - diff --git a/examples/lbsb/signature-scenario/src/main/java/client/Application.java b/examples/lbsb/signature-scenario/src/main/java/client/Application.java deleted file mode 100644 index 99a818a..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package client; - -import javax.swing.SwingUtilities; -import javax.swing.UIManager; - -import client.ui.UI; - -public class Application { - - public static void main(String[] args) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - UIManager.put("swing.boldMetal", Boolean.FALSE); - - UI.createAndShowGUI(); - } - }); - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/callback/ClientCallbackHandler.java b/examples/lbsb/signature-scenario/src/main/java/client/callback/ClientCallbackHandler.java deleted file mode 100644 index d5a3a30..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/callback/ClientCallbackHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -package client.callback; - -import java.io.IOException; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.wss4j.common.ext.WSPasswordCallback; - -public class ClientCallbackHandler implements CallbackHandler { - private static String password; - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - - for (int i = 0; i < callbacks.length; i++) { - if (callbacks[i] instanceof WSPasswordCallback) { - WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; - if (pc.getUsage() == WSPasswordCallback.DECRYPT || pc.getUsage() == WSPasswordCallback.SIGNATURE) { - pc.setPassword(password); - } - } - } - } - - public static void setPassword(String password) { - ClientCallbackHandler.password = password; - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/crypto/UserCertificateStore.java b/examples/lbsb/signature-scenario/src/main/java/client/crypto/UserCertificateStore.java deleted file mode 100644 index d8188bc..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/crypto/UserCertificateStore.java +++ /dev/null @@ -1,25 +0,0 @@ -package client.crypto; - -import java.io.IOException; -import java.security.KeyStore; -import java.util.Properties; - -import org.apache.wss4j.common.crypto.Merlin; -import org.apache.wss4j.common.crypto.PasswordEncryptor; -import org.apache.wss4j.common.ext.WSSecurityException; - -public class UserCertificateStore extends Merlin { - private static KeyStore ks; - - public UserCertificateStore(Properties properties, ClassLoader loader, PasswordEncryptor passwordEncryptor) throws WSSecurityException, IOException { - super(properties, loader, passwordEncryptor); - - // the UserCertificateStore instance is created on-demand by the CXF framework, meaning when it is about to call the STS, - // so as long as we ensure that a user-supplied keystore is configured before calling the STS, this will work as intended - this.setKeyStore(UserCertificateStore.ks); - } - - public static void setKs(KeyStore keyStore) { - ks = keyStore; - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java b/examples/lbsb/signature-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java deleted file mode 100644 index 4e20eaf..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package client.interceptor; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapHeader; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; - -import client.model.SbfFrameworkHeader; - -public class FrameworkHeaderInterceptor extends AbstractSoapInterceptor { - public FrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - try { - Header framework = new SoapHeader(new QName("urn:liberty:sb", "Framework", "sbf"), new SbfFrameworkHeader(), new JAXBDataBinding(SbfFrameworkHeader.class)); - headers.add(framework); - } - catch (Exception ex) { - throw new XMLFault(ex.getMessage()); - } - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java b/examples/lbsb/signature-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java deleted file mode 100644 index 4a67698..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java +++ /dev/null @@ -1,61 +0,0 @@ -package client.interceptor; - -import java.util.List; -import java.util.UUID; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; -import org.apache.cxf.ws.addressing.AttributedURIType; -import org.apache.cxf.ws.addressing.ObjectFactory; - -public class STSAddressingInterceptor extends AbstractSoapInterceptor { - public STSAddressingInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - ObjectFactory wsAddressingFactory = new ObjectFactory(); - - AttributedURIType to = new AttributedURIType(); - AttributedURIType messageId = new AttributedURIType(); - AttributedURIType action = new AttributedURIType(); - - to.setValue("https://signature.sts.nemlog-in.dk/"); - action.setValue("http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); - messageId.setValue("uuid:" + UUID.randomUUID().toString()); - - JAXBElement createTo = wsAddressingFactory.createTo(to); - JAXBElement msgId = wsAddressingFactory.createMessageID(messageId); - JAXBElement newAction = wsAddressingFactory.createAction(action); - - JAXBDataBinding jaxbDataBinding = null; - try { - jaxbDataBinding = new JAXBDataBinding(AttributedURIType.class); - } - catch (JAXBException ex) { - throw new XMLFault(ex.getMessage()); - } - - Header toHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), createTo, jaxbDataBinding); - Header msgIdHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), msgId, jaxbDataBinding); - Header actionHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), newAction, jaxbDataBinding); - - headers.add(actionHeader); - headers.add(msgIdHeader); - headers.add(toHeader); - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/model/SbfFrameworkHeader.java b/examples/lbsb/signature-scenario/src/main/java/client/model/SbfFrameworkHeader.java deleted file mode 100644 index 0784fba..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/model/SbfFrameworkHeader.java +++ /dev/null @@ -1,23 +0,0 @@ -package client.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; - -@XmlAccessorType(XmlAccessType.FIELD) -public class SbfFrameworkHeader { - - @XmlAttribute(name="version") - private final String version = "2.0"; - - @XmlAttribute(name="profile", namespace="urn:liberty:sb:profile") - private final String profile = "urn:liberty:sb:profile:basic"; - - public String getVersion() { - return version; - } - - public String getProfile() { - return profile; - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/spring/ApplicationContextProvider.java b/examples/lbsb/signature-scenario/src/main/java/client/spring/ApplicationContextProvider.java deleted file mode 100644 index 2f993d1..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/spring/ApplicationContextProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package client.spring; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public class ApplicationContextProvider implements ApplicationContextAware { - private static ApplicationContext ctx; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextProvider.ctx = applicationContext; - } - - public static ApplicationContext getApplicationContext() { - return ctx; - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/sts/DigstSTSClient.java b/examples/lbsb/signature-scenario/src/main/java/client/sts/DigstSTSClient.java deleted file mode 100644 index ca0a9b9..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/sts/DigstSTSClient.java +++ /dev/null @@ -1,50 +0,0 @@ -package client.sts; - -import java.util.UUID; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import org.apache.cxf.Bus; -import org.apache.cxf.ws.security.SecurityConstants; -import org.apache.cxf.ws.security.trust.STSClient; - -import client.interceptor.STSAddressingInterceptor; - -public class DigstSTSClient extends STSClient { - - public DigstSTSClient(Bus b) { - super(b); - - this.out.add(new STSAddressingInterceptor()); - - createUniqueContextAttribute(); - } - - public void setAlias(String alias) { - ctx.put(SecurityConstants.SIGNATURE_USERNAME, alias); - } - - @Override - protected void addAppliesTo(XMLStreamWriter writer, String appliesTo) throws XMLStreamException { - createUniqueContextAttribute(); - - if (appliesTo != null && addressingNamespace != null) { - // modified the namespace so it uses ws-policy 1.1 namespace (not supported by CXF, so we have to do this hacky thing) - writer.writeStartElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeNamespace("wsp", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeStartElement("wsa", "EndpointReference", addressingNamespace); - writer.writeNamespace("wsa", addressingNamespace); - writer.writeStartElement("wsa", "Address", addressingNamespace); - writer.writeCharacters(appliesTo); - writer.writeEndElement(); - writer.writeEndElement(); - writer.writeEndElement(); - } - } - - // we are required to set a unique @Context attribute on the request - private void createUniqueContextAttribute() { - this.context = "urn:uuid:" + UUID.randomUUID().toString(); - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/ui/KeystoreButtonHandler.java b/examples/lbsb/signature-scenario/src/main/java/client/ui/KeystoreButtonHandler.java deleted file mode 100644 index ede9fd4..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/ui/KeystoreButtonHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -package client.ui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.JPasswordField; - -public class KeystoreButtonHandler implements ActionListener { - private JFileChooser fc = new JFileChooser(); - private UI ui; - - public KeystoreButtonHandler(UI ui) { - this.ui = ui; - } - - @Override - public void actionPerformed(ActionEvent e) { - int returnVal = fc.showOpenDialog(ui); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - ui.setFile(fc.getSelectedFile()); - - JPasswordField passwordField = new JPasswordField(); - int ok = JOptionPane.showConfirmDialog(ui, passwordField, "Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); - - if (ok == JOptionPane.OK_OPTION) { - ui.setPassword(new String(passwordField.getPassword())); - ui.writeLog("Loaded keystore"); - } - else { - ui.writeLog("Please enter a password for the keystore"); - } - } - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/ui/RunButtonHandler.java b/examples/lbsb/signature-scenario/src/main/java/client/ui/RunButtonHandler.java deleted file mode 100644 index a59a944..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/ui/RunButtonHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package client.ui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.KeyStoreException; - -import client.callback.ClientCallbackHandler; -import client.crypto.UserCertificateStore; -import client.spring.ApplicationContextProvider; -import client.sts.DigstSTSClient; - -public class RunButtonHandler implements ActionListener { - private UI ui; - - public RunButtonHandler(UI ui) { - this.ui = ui; - } - - @Override - public void actionPerformed(ActionEvent e) { - ui.writeLog("Invoked service"); - - KeyStore keystore = getKeystore(); - if (keystore != null) { - try { - // set the password on the callback handler - ClientCallbackHandler.setPassword(ui.getPassword()); - - // set the alias on the STSClient - String alias = keystore.aliases().nextElement(); - DigstSTSClient stsClient = ApplicationContextProvider.getApplicationContext().getBean(DigstSTSClient.class); - stsClient.setAlias(alias); - - // set the keystore on the custom Merlin class - UserCertificateStore.setKs(keystore); - - // first call will also call the STS - hello("John"); - - // second call will reuse the cached token we got from the first call - hello("Jane"); - } - catch (KeyStoreException ex) { - ui.writeLog("Failed to retrieve key from keystore: ", ex); - } - } - } - - private KeyStore getKeystore() { - KeyStore ks = null; - - try { - ks = KeyStore.getInstance("PKCS12"); - ks.load(new FileInputStream(ui.getFile()), ui.getPassword().toCharArray()); - } - catch (GeneralSecurityException | IOException ex) { - ui.writeLog("Could not load keystore with provided password", ex); - } - - return ks; - } - - private void hello(String name) { - String resp = ui.getPort().helloWorld(name); - - ui.writeLog("Response from service: " + resp); - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/client/ui/UI.java b/examples/lbsb/signature-scenario/src/main/java/client/ui/UI.java deleted file mode 100644 index 0c24a46..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/client/ui/UI.java +++ /dev/null @@ -1,101 +0,0 @@ -package client.ui; - -import java.awt.BorderLayout; -import java.awt.GridLayout; -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import org.example.contract.helloworld.HelloWorldPortType; -import org.example.contract.helloworld.HelloWorldService; - -public class UI extends JPanel { - private static final long serialVersionUID = 1L; - private String password; - private JTextArea log; - private File file; - private HelloWorldPortType port; - - public static void createAndShowGUI() { - JFrame frame = new JFrame("UI"); - - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setSize(600, 300); - frame.add(new UI(), BorderLayout.CENTER); - frame.setVisible(true); - } - - public UI() { - super(new BorderLayout(0,0)); - - add(getButtonPanel(), BorderLayout.NORTH); - add(getLogPanel(), BorderLayout.CENTER); - - // instantiate CXF (TODO: explain why this has to be done first) - HelloWorldService service = new HelloWorldService(); - port = service.getHelloWorldPort(); - } - - public void writeLog(String message) { - log.append(message + "\n"); - log.setCaretPosition(log.getDocument().getLength()); - } - - public void writeLog(String message, Exception ex) { - writeLog(message); - - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - ex.printStackTrace(pw); - writeLog(sw.toString()); - } - - public void setFile(File file) { - this.file = file; - } - - public File getFile() { - return file; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPassword() { - return password; - } - - public HelloWorldPortType getPort() { - return port; - } - - private JPanel getButtonPanel() { - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new GridLayout(1, 2)); - - JButton keystoreButton = new JButton("Open Keystore"); - keystoreButton.addActionListener(new KeystoreButtonHandler(this)); - - JButton runButton = new JButton("Run"); - runButton.addActionListener(new RunButtonHandler(this)); - - buttonPanel.add(keystoreButton); - buttonPanel.add(runButton); - - return buttonPanel; - } - - private JScrollPane getLogPanel() { - log = new JTextArea(5, 30); - log.setEditable(false); - - return new JScrollPane(log); - } -} \ No newline at end of file diff --git a/examples/lbsb/signature-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java b/examples/lbsb/signature-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java deleted file mode 100644 index 3c4724a..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java +++ /dev/null @@ -1,2273 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.cxf.ws.security.wss4j.policyhandlers; - -import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.callback.CallbackHandler; -import javax.xml.crypto.dsig.Reference; -import javax.xml.namespace.QName; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPHeader; -import javax.xml.soap.SOAPMessage; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.apache.cxf.Bus; -import org.apache.cxf.attachment.AttachmentUtil; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.saaj.SAAJUtils; -import org.apache.cxf.common.classloader.ClassLoaderUtils; -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.endpoint.Endpoint; -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.helpers.DOMUtils; -import org.apache.cxf.helpers.MapNamespaceContext; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.message.MessageUtils; -import org.apache.cxf.resource.ResourceManager; -import org.apache.cxf.service.model.EndpointInfo; -import org.apache.cxf.staxutils.StaxUtils; -import org.apache.cxf.staxutils.W3CDOMStreamWriter; -import org.apache.cxf.ws.policy.AssertionInfo; -import org.apache.cxf.ws.policy.AssertionInfoMap; -import org.apache.cxf.ws.policy.PolicyConstants; -import org.apache.cxf.ws.security.SecurityConstants; -import org.apache.cxf.ws.security.tokenstore.SecurityToken; -import org.apache.cxf.ws.security.tokenstore.TokenStore; -import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler; -import org.apache.cxf.ws.security.wss4j.WSS4JUtils; -import org.apache.cxf.wsdl.WSDLConstants; -import org.apache.neethi.Assertion; -import org.apache.wss4j.common.WSEncryptionPart; -import org.apache.wss4j.common.crypto.Crypto; -import org.apache.wss4j.common.crypto.CryptoFactory; -import org.apache.wss4j.common.crypto.CryptoType; -import org.apache.wss4j.common.derivedKey.ConversationConstants; -import org.apache.wss4j.common.ext.WSPasswordCallback; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.common.principal.UsernameTokenPrincipal; -import org.apache.wss4j.common.saml.SAMLCallback; -import org.apache.wss4j.common.saml.SAMLUtil; -import org.apache.wss4j.common.saml.SamlAssertionWrapper; -import org.apache.wss4j.common.util.Loader; -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSSConfig; -import org.apache.wss4j.dom.WSSecurityEngineResult; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.handler.WSHandlerConstants; -import org.apache.wss4j.dom.handler.WSHandlerResult; -import org.apache.wss4j.dom.message.WSSecBase; -import org.apache.wss4j.dom.message.WSSecDKSign; -import org.apache.wss4j.dom.message.WSSecEncryptedKey; -import org.apache.wss4j.dom.message.WSSecHeader; -import org.apache.wss4j.dom.message.WSSecSignature; -import org.apache.wss4j.dom.message.WSSecSignatureConfirmation; -import org.apache.wss4j.dom.message.WSSecTimestamp; -import org.apache.wss4j.dom.message.WSSecUsernameToken; -import org.apache.wss4j.dom.message.token.BinarySecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; -import org.apache.wss4j.policy.SPConstants; -import org.apache.wss4j.policy.SPConstants.IncludeTokenType; -import org.apache.wss4j.policy.model.AbstractBinding; -import org.apache.wss4j.policy.model.AbstractSecurityAssertion; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding.ProtectionOrder; -import org.apache.wss4j.policy.model.AbstractToken; -import org.apache.wss4j.policy.model.AbstractToken.DerivedKeys; -import org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType; -import org.apache.wss4j.policy.model.AsymmetricBinding; -import org.apache.wss4j.policy.model.Attachments; -import org.apache.wss4j.policy.model.ContentEncryptedElements; -import org.apache.wss4j.policy.model.EncryptedElements; -import org.apache.wss4j.policy.model.EncryptedParts; -import org.apache.wss4j.policy.model.Header; -import org.apache.wss4j.policy.model.IssuedToken; -import org.apache.wss4j.policy.model.KerberosToken; -import org.apache.wss4j.policy.model.KeyValueToken; -import org.apache.wss4j.policy.model.Layout.LayoutType; -import org.apache.wss4j.policy.model.SamlToken; -import org.apache.wss4j.policy.model.SamlToken.SamlTokenType; -import org.apache.wss4j.policy.model.SecureConversationToken; -import org.apache.wss4j.policy.model.SecurityContextToken; -import org.apache.wss4j.policy.model.SignedElements; -import org.apache.wss4j.policy.model.SignedParts; -import org.apache.wss4j.policy.model.SpnegoContextToken; -import org.apache.wss4j.policy.model.SupportingTokens; -import org.apache.wss4j.policy.model.SymmetricBinding; -import org.apache.wss4j.policy.model.UsernameToken; -import org.apache.wss4j.policy.model.Wss10; -import org.apache.wss4j.policy.model.Wss11; -import org.apache.wss4j.policy.model.X509Token; -import org.apache.wss4j.policy.model.X509Token.TokenType; -import org.opensaml.common.SAMLVersion; - -/** - * - */ -public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandler { - public static final String CRYPTO_CACHE = "ws-security.crypto.cache"; - protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBindingBuilder.class); - - protected AbstractSymmetricAsymmetricBinding.ProtectionOrder protectionOrder = - AbstractSymmetricAsymmetricBinding.ProtectionOrder.SignBeforeEncrypting; - - protected final WSSConfig wssConfig; - protected SOAPMessage saaj; - protected WSSecHeader secHeader; - protected AssertionInfoMap aim; - protected AbstractBinding binding; - protected WSSecTimestamp timestampEl; - protected String mainSigId; - protected List sigConfList; - - protected Set encryptedTokensList = new HashSet(); - - protected List signatures = new ArrayList(); - - protected Element bottomUpElement; - protected Element topDownElement; - protected Element bstElement; - protected Element lastEncryptedKeyElement; - protected boolean storeBytesInAttachment; - - private Element lastSupportingTokenElement; - private Element lastDerivedKeyElement; - - private List suppTokenParts = new ArrayList(); - private List endSuppTokList; - private List sgndEndSuppTokList; - - public AbstractBindingBuilder( - WSSConfig config, - AbstractBinding binding, - SOAPMessage saaj, - WSSecHeader secHeader, - AssertionInfoMap aim, - SoapMessage message) { - super(message); - this.wssConfig = config; - this.binding = binding; - this.aim = aim; - this.secHeader = secHeader; - this.saaj = saaj; - message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures); - - boolean storeBytes = - MessageUtils.getContextualBoolean( - message, SecurityConstants.STORE_BYTES_IN_ATTACHMENT, false - ); - if (storeBytes && AttachmentUtil.isMtomEnabled(message)) { - storeBytesInAttachment = true; - if (binding instanceof AbstractSymmetricAsymmetricBinding - && (ProtectionOrder.EncryptBeforeSigning - == ((AbstractSymmetricAsymmetricBinding)binding).getProtectionOrder() - || ((AbstractSymmetricAsymmetricBinding)binding).isProtectTokens())) { - LOG.fine("Disabling SecurityConstants.STORE_BYTES_IN_ATTACHMENT due to " - + "EncryptBeforeSigning or ProtectTokens policy."); - storeBytesInAttachment = false; - } - } - - } - - protected void insertAfter(Element child, Element sib) { - if (sib.getNextSibling() == null) { - secHeader.getSecurityHeader().appendChild(child); - } else { - secHeader.getSecurityHeader().insertBefore(child, sib.getNextSibling()); - } - } - - protected void addDerivedKeyElement(Element el) { - if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addEncryptedKeyElement(Element el) { - if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (lastDerivedKeyElement != null) { - secHeader.getSecurityHeader().insertBefore(el, lastDerivedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addSupportingElement(Element el) { - if (lastSupportingTokenElement != null) { - insertAfter(el, lastSupportingTokenElement); - } else if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (bottomUpElement != null) { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastSupportingTokenElement = el; - } - - protected void insertBeforeBottomUp(Element el) { - if (bottomUpElement == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } - bottomUpElement = el; - } - - protected void addTopDownElement(Element el) { - if (topDownElement == null) { - if (secHeader.getSecurityHeader().getFirstChild() == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } - } else { - insertAfter(el, topDownElement); - } - topDownElement = el; - } - - protected final Map getCryptoCache() { - EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo(); - synchronized (info) { - Map o = - CastUtils.cast((Map)message.getContextualProperty(CRYPTO_CACHE)); - if (o == null) { - o = CastUtils.cast((Map)info.getProperty(CRYPTO_CACHE)); - } - if (o == null) { - o = new ConcurrentHashMap(); - info.setProperty(CRYPTO_CACHE, o); - } - return o; - } - } - - protected final TokenStore getTokenStore() { - return WSS4JUtils.getTokenStore(message); - } - - protected WSSecTimestamp createTimestamp() { - if (binding.isIncludeTimestamp()) { - Object o = message.getContextualProperty(SecurityConstants.TIMESTAMP_TTL); - int ttl = 300; //default is 300 seconds - if (o instanceof Number) { - ttl = ((Number)o).intValue(); - } else if (o instanceof String) { - ttl = Integer.parseInt((String)o); - } - if (ttl <= 0) { - ttl = 300; - } - timestampEl = new WSSecTimestamp(wssConfig); - timestampEl.setTimeToLive(ttl); - timestampEl.prepare(saaj.getSOAPPart()); - - Collection ais = getAllAssertionsByLocalname(SPConstants.INCLUDE_TIMESTAMP); - for (AssertionInfo ai : ais) { - ai.setAsserted(true); - } - } - return timestampEl; - } - - protected WSSecTimestamp handleLayout(WSSecTimestamp timestamp) { - if (binding.getLayout() != null) { - Collection ais = getAllAssertionsByLocalname(SPConstants.LAYOUT); - AssertionInfo ai = null; - for (AssertionInfo layoutAi : ais) { - layoutAi.setAsserted(true); - ai = layoutAi; - } - - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_LAST + " requires a timestamp"); - } else { - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_LAST)); - Element el = timestamp.getElement(); - secHeader.getSecurityHeader().appendChild(el); - if (bottomUpElement == null) { - bottomUpElement = el; - } - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST + " requires a timestamp"); - } else { - addTopDownElement(timestampEl.getElement()); - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST)); - } - } else if (timestampEl != null) { - if (ai != null) { - ai.setAsserted(true); - } - addTopDownElement(timestampEl.getElement()); - } else if (ai != null) { - ai.setAsserted(true); - } - - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_LAX)); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_STRICT)); - } else if (timestampEl != null) { - addTopDownElement(timestampEl.getElement()); - } - return timestamp; - } - - protected void reshuffleTimestamp() { - // Make sure that the Timestamp is in first place, if that is what the policy requires - if (binding.getLayout() != null && timestampEl != null) { - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst - && secHeader.getSecurityHeader().getFirstChild() != timestampEl.getElement()) { - Node firstChild = secHeader.getSecurityHeader().getFirstChild(); - while (firstChild != null && firstChild.getNodeType() != Node.ELEMENT_NODE) { - firstChild = firstChild.getNextSibling(); - } - if (firstChild != null && firstChild != timestampEl.getElement()) { - secHeader.getSecurityHeader().insertBefore(timestampEl.getElement(), firstChild); - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast - && secHeader.getSecurityHeader().getLastChild() != timestampEl.getElement()) { - secHeader.getSecurityHeader().appendChild(timestampEl.getElement()); - } - } - } - - private List handleSupportingTokens( - Collection tokensInfos, - boolean endorse - ) throws WSSecurityException { - List ret = new ArrayList(); - if (tokensInfos != null) { - for (AssertionInfo assertionInfo : tokensInfos) { - if (assertionInfo.getAssertion() instanceof SupportingTokens) { - assertionInfo.setAsserted(true); - try { - handleSupportingTokens((SupportingTokens)assertionInfo.getAssertion(), endorse, ret); - } catch (SOAPException ex) { - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); - } - } - } - } - return ret; - } - - protected List handleSupportingTokens( - SupportingTokens suppTokens, - boolean endorse, - List ret - ) throws WSSecurityException, SOAPException { - if (suppTokens == null) { - return ret; - } - for (AbstractToken token : suppTokens.getTokens()) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - // Check for any SignedParts so as *not* to sign them - getSignedParts(suppTokens); - continue; - } - if (token instanceof UsernameToken) { - handleUsernameTokenSupportingToken( - (UsernameToken)token, endorse, suppTokens.isEncryptedToken(), ret - ); - } else if (token instanceof IssuedToken - || token instanceof SecureConversationToken - || token instanceof SecurityContextToken - || token instanceof KerberosToken - || token instanceof SpnegoContextToken) { - //ws-trust/ws-sc stuff....... - SecurityToken secToken = getSecurityToken(); - if (secToken == null) { - policyNotAsserted(token, "Could not find IssuedToken"); - } - Element clone = cloneElement(secToken.getToken()); - secToken.setToken(clone); - addSupportingElement(clone); - - String id = secToken.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(id, "Element"); - part.setElement(clone); - encryptedTokensList.add(part); - } - - if (secToken.getX509Certificate() == null) { - ret.add( - new SupportingToken(token, new WSSecurityTokenHolder(wssConfig, secToken), - getSignedParts(suppTokens)) - ); - } else { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setX509Certificate(secToken.getX509Certificate()); - sig.setCustomTokenId(id); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - String tokenType = secToken.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - - Crypto crypto = secToken.getCrypto(); - String uname = null; - try { - uname = crypto.getX509Identifier(secToken.getX509Certificate()); - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - - String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(uname, password); - try { - sig.prepare(saaj.getSOAPPart(), secToken.getCrypto(), secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - throw new Fault(e); - } - - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } - - } else if (token instanceof X509Token) { - //We have to use a cert. Prepare X509 signature - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - Element bstElem = sig.getBinarySecurityTokenElement(); - if (bstElem != null) { - if (lastEncryptedKeyElement != null) { - if (lastEncryptedKeyElement.getNextSibling() != null) { - secHeader.getSecurityHeader().insertBefore(bstElem, - lastEncryptedKeyElement.getNextSibling()); - } else { - secHeader.getSecurityHeader().appendChild(bstElem); - } - } else { - sig.prependBSTElementToHeader(secHeader); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - part.setElement(bstElem); - encryptedTokensList.add(part); - } - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof KeyValueToken) { - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - encryptedTokensList.add(part); - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof SamlToken) { - SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken)token); - if (assertionWrapper != null) { - Element assertionElement = assertionWrapper.toDOM(saaj.getSOAPPart()); - addSupportingElement(assertionElement); - ret.add(new SupportingToken(token, assertionWrapper, getSignedParts(suppTokens))); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(assertionWrapper.getId(), "Element"); - part.setElement(assertionElement); - encryptedTokensList.add(part); - } - } - } - } - - return ret; - } - - protected void handleUsernameTokenSupportingToken( - UsernameToken token, boolean endorse, boolean encryptedToken, List ret - ) throws WSSecurityException { - if (endorse) { - WSSecUsernameToken utBuilder = addDKUsernameToken(token, true); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - if (encryptedToken) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } else { - WSSecUsernameToken utBuilder = addUsernameToken(token); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - //WebLogic and WCF always encrypt these - //See: http://e-docs.bea.com/wls/docs103/webserv_intro/interop.html - //encryptedTokensIdList.add(utBuilder.getId()); - if (encryptedToken - || MessageUtils.getContextualBoolean(message, - SecurityConstants.ALWAYS_ENCRYPT_UT, - true)) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } - } - - protected Element cloneElement(Element el) { - Document doc = secHeader.getSecurityHeader().getOwnerDocument(); - if (!doc.equals(el.getOwnerDocument())) { - - XMLStreamReader reader = StaxUtils.createXMLStreamReader(el); - DocumentFragment fragment = doc.createDocumentFragment(); - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(fragment); - try { - StaxUtils.copy(reader, writer); - return (Element)fragment.getFirstChild(); - } catch (XMLStreamException ex) { - LOG.log(Level.FINE, "Error cloning security element", ex); - } - } - return el; - } - - protected void addSignatureParts(List tokenList, - List sigParts) { - - boolean useSTRTransform = - MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_STR_TRANSFORM, true - ); - - for (SupportingToken supportingToken : tokenList) { - - Object tempTok = supportingToken.getTokenImplementation(); - WSEncryptionPart part = null; - - if (tempTok instanceof WSSecSignature) { - WSSecSignature tempSig = (WSSecSignature) tempTok; - SecurityTokenReference secRef = tempSig.getSecurityTokenReference(); - - if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType()) - || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { - - Element secRefElement = cloneElement(secRef.getElement()); - addSupportingElement(secRefElement); - - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(tempSig.getSecurityTokenReferenceURI()); - part.setElement(secRefElement); - } else { - if (tempSig.getBSTTokenId() != null) { - part = new WSEncryptionPart(tempSig.getBSTTokenId()); - part.setElement(tempSig.getBinarySecurityTokenElement()); - } - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken unt = (WSSecUsernameToken)tempTok; - part = new WSEncryptionPart(unt.getId()); - part.setElement(unt.getUsernameTokenElement()); - } else if (tempTok instanceof BinarySecurity) { - BinarySecurity bst = (BinarySecurity)tempTok; - part = new WSEncryptionPart(bst.getID()); - part.setElement(bst.getElement()); - } else if (tempTok instanceof SamlAssertionWrapper) { - SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper)tempTok; - - Document doc = assertionWrapper.getElement().getOwnerDocument(); - boolean saml1 = assertionWrapper.getSaml1() != null; - if (useSTRTransform) { - // TODO We only support using a KeyIdentifier for the moment - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, assertionWrapper.getId(), saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(assertionWrapper.getId()); - part.setElement(assertionWrapper.getElement()); - } - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - String tokenType = token.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType) - || WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - Document doc = token.getToken().getOwnerDocument(); - boolean saml1 = WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType); - String id = token.getId(); - if (id == null || "".equals(id)) { - if (saml1) { - id = token.getToken().getAttributeNS(null, "AssertionID"); - } else { - id = token.getToken().getAttributeNS(null, "ID"); - } - } - if (useSTRTransform) { - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, id, saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - String id = token.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - policyNotAsserted(supportingToken.getToken(), - "UnsupportedTokenInSupportingToken: " + tempTok); - } - if (part != null) { - sigParts.add(part); - } - } - } - - /** - * Create a SecurityTokenReference to point to a SAML Assertion - * @param doc The owner Document instance - * @param id The Assertion ID - * @param saml1 Whether the Assertion is a SAML1 or SAML2 Assertion - * @param useDirectReferenceToAssertion whether to refer directly to the assertion or not - * @return a SecurityTokenReference to a SAML Assertion - */ - private SecurityTokenReference createSTRForSamlAssertion( - Document doc, - String id, - boolean saml1, - boolean useDirectReferenceToAssertion - ) { - SecurityTokenReference secRefSaml = new SecurityTokenReference(doc); - String secRefID = wssConfig.getIdAllocator().createSecureId("STR-", secRefSaml); - secRefSaml.setID(secRefID); - - if (useDirectReferenceToAssertion) { - org.apache.wss4j.dom.message.token.Reference ref = - new org.apache.wss4j.dom.message.token.Reference(doc); - ref.setURI("#" + id); - if (saml1) { - ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - secRefSaml.setReference(ref); - } else { - Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); - String valueType = null; - if (saml1) { - valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - keyId.setAttributeNS( - null, "ValueType", valueType - ); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRefSaml.getElement(); - elem.appendChild(keyId); - } - return secRefSaml; - } - - protected WSSecUsernameToken addUsernameToken(UsernameToken token) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - // If NoPassword property is set we don't need to set the password - if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) { - utBuilder.setUserInfo(userName, null); - utBuilder.setPasswordType(null); - } else { - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) { - utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST); - } else { - utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT); - } - utBuilder.setUserInfo(userName, password); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - } - - if (token.isCreated() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addCreated(); - } - if (token.isNonce() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addNonce(); - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected WSSecUsernameToken addDKUsernameToken(UsernameToken token, boolean useMac) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - utBuilder.setUserInfo(userName, password); - utBuilder.addDerivedKey(useMac, null, 1000); - utBuilder.prepare(saaj.getSOAPPart()); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - // - // Get the SAML CallbackHandler - // - Object o = message.getContextualProperty(SecurityConstants.SAML_CALLBACK_HANDLER); - - if (o == null) { - SecurityToken securityToken = getSecurityToken(); - if (securityToken != null) { - Element tokenElement = (Element)securityToken.getToken(); - String namespace = tokenElement.getNamespaceURI(); - String localname = tokenElement.getLocalName(); - SamlTokenType tokenType = token.getSamlTokenType(); - if ((tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) - && WSConstants.SAML_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } else if (tokenType == SamlTokenType.WssSamlV20Token11 - && WSConstants.SAML2_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } - } - } - - CallbackHandler handler = null; - if (o instanceof CallbackHandler) { - handler = (CallbackHandler)o; - } else if (o instanceof String) { - try { - handler = (CallbackHandler)ClassLoaderUtils - .loadClass((String)o, this.getClass()).newInstance(); - } catch (Exception e) { - handler = null; - } - } - if (handler == null) { - policyNotAsserted(token, "No SAML CallbackHandler available"); - return null; - } - - SAMLCallback samlCallback = new SAMLCallback(); - SamlTokenType tokenType = token.getSamlTokenType(); - if (tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_11); - } else if (tokenType == SamlTokenType.WssSamlV20Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_20); - } - SAMLUtil.doSAMLCallback(handler, samlCallback); - SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback); - - if (samlCallback.isSignAssertion()) { - String issuerName = samlCallback.getIssuerKeyName(); - if (issuerName == null) { - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - issuerName = (String)message.getContextualProperty(userNameKey); - } - String password = samlCallback.getIssuerKeyPassword(); - if (password == null) { - password = getPassword(issuerName, token, WSPasswordCallback.SIGNATURE); - } - Crypto crypto = samlCallback.getIssuerCrypto(); - if (crypto == null) { - crypto = getSignatureCrypto(); - } - - assertion.signAssertion( - issuerName, - password, - crypto, - samlCallback.isSendKeyValue(), - samlCallback.getCanonicalizationAlgorithm(), - samlCallback.getSignatureAlgorithm(), - samlCallback.getSignatureDigestAlgorithm() - ); - } - - return assertion; - } - - /** - * Store a SAML Assertion as a SecurityToken - */ - protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) { - String id = findIDFromSamlToken(assertion.getElement()); - if (id == null) { - return; - } - SecurityToken secToken = new SecurityToken(id); - if (assertion.getSaml2() != null) { - secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } else { - secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } - secToken.setToken(assertion.getElement()); - getTokenStore().add(secToken); - message.put(SecurityConstants.TOKEN_ID, secToken.getId()); - } - - protected String findIDFromSamlToken(Element samlToken) { - String id = null; - if (samlToken != null) { - QName elName = DOMUtils.getElementQName(samlToken); - if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "AssertionID")) { - id = samlToken.getAttributeNS(null, "AssertionID"); - } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "ID")) { - id = samlToken.getAttributeNS(null, "ID"); - } - if (id == null) { - id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id"); - } - } - return id; - } - - protected String getPassword(String userName, Assertion info, int usage) { - //Then try to get the password from the given callback handler - CallbackHandler handler = getCallbackHandler(); - if (handler == null) { - // Don't unassert for signature as we might get the password from the crypto properties - if (usage == WSPasswordCallback.SIGNATURE) { - LOG.info("No CallbackHandler available to retrieve a password. We will now try the crypto " - + "properties file for a private password"); - } else { - policyNotAsserted(info, "No callback handler and no password available"); - } - return null; - } - - WSPasswordCallback[] cb = {new WSPasswordCallback(userName, usage)}; - try { - handler.handle(cb); - } catch (Exception e) { - policyNotAsserted(info, e); - } - - //get the password - return cb[0].getPassword(); - } - - protected CallbackHandler getCallbackHandler() { - return WSS4JUtils.getCallbackHandler(message); - } - - /** - * Generates a wsu:Id attribute for the provided {@code Element} and returns the attribute value - * or finds and returns the value of the attribute if it already exists. - * - * @param element the {@code Element} to check/create the attribute on - * - * @return the generated or discovered wsu:Id attribute value - */ - public String addWsuIdToElement(Element elem) { - String id; - - //first try to get the Id attr - Attr idAttr = elem.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = elem.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - - if (idAttr != null) { - id = idAttr.getValue(); - } else { - //Add an id - id = wssConfig.getIdAllocator().createId("_", elem); - String pfx = null; - try { - pfx = elem.lookupPrefix(PolicyConstants.WSU_NAMESPACE_URI); - } catch (Throwable t) { - pfx = DOMUtils.getPrefixRecursive(elem, PolicyConstants.WSU_NAMESPACE_URI); - } - boolean found = !StringUtils.isEmpty(pfx); - int cnt = 0; - while (StringUtils.isEmpty(pfx)) { - pfx = "wsu" + (cnt == 0 ? "" : cnt); - - String ns; - try { - ns = elem.lookupNamespaceURI(pfx); - } catch (Throwable t) { - ns = DOMUtils.getNamespace(elem, pfx); - } - - if (!StringUtils.isEmpty(ns)) { - pfx = null; - cnt++; - } - } - if (!found) { - idAttr = elem.getOwnerDocument().createAttributeNS(WSDLConstants.NS_XMLNS, "xmlns:" + pfx); - idAttr.setValue(PolicyConstants.WSU_NAMESPACE_URI); - elem.setAttributeNodeNS(idAttr); - } - idAttr = elem.getOwnerDocument().createAttributeNS(PolicyConstants.WSU_NAMESPACE_URI, - pfx + ":Id"); - idAttr.setValue(id); - elem.setAttributeNodeNS(idAttr); - } - - return id; - } - - public List getEncryptedParts() - throws SOAPException { - - boolean isBody = false; - - EncryptedParts parts = null; - EncryptedElements elements = null; - ContentEncryptedElements celements = null; - - Collection ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - parts = (EncryptedParts)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - elements = (EncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.CONTENT_ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - celements = (ContentEncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - if (parts == null && elements == null && celements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String encModifier = "Element"; - if (MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_ATTACHMENT_ENCRYPTION_CONTENT_ONLY_TRANSFORM, false)) { - encModifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", encModifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the encrypted list to prevent duplication / errors in encryption. - return getPartsAndElements(false, - isBody, - signedParts, - elements == null ? null : elements.getXPaths(), - celements == null ? null : celements.getXPaths()); - } - - public List getSignedParts(SupportingTokens supportingToken) - throws SOAPException { - - boolean isSignBody = false; - - SignedParts parts = null; - SignedElements elements = null; - - if (supportingToken != null && supportingToken.isEndorsing()) { - parts = supportingToken.getSignedParts(); - elements = supportingToken.getSignedElements(); - // Store them so that the main Signature doesn't sign them - if (parts != null) { - suppTokenParts.add(parts); - this.assertPolicy(parts.getName()); - } - if (elements != null) { - suppTokenParts.add(elements); - this.assertPolicy(elements.getName()); - } - } else { - Collection ais = getAllAssertionsByLocalname(SPConstants.SIGNED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedParts signedParts = (SignedParts)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedParts)) { - parts = signedParts; - } - } - } - - ais = getAllAssertionsByLocalname(SPConstants.SIGNED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedElements signedElements = (SignedElements)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedElements)) { - elements = signedElements; - } - } - } - } - - if (parts == null && elements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isSignBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String modifier = "Element"; - if (attachments.isContentSignatureTransform()) { - modifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", modifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the signed list to prevent duplication in the signature. - return getPartsAndElements(true, - isSignBody, - signedParts, - elements == null ? null : elements.getXPaths(), - null); - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param contentXpaths - * any XPath expressions to content encrypt - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - * - * @deprecated Use {@link #getSignedParts()} and {@link #getEncryptedParts()} - * instead. - */ - public List getPartsAndElements(boolean sign, - boolean includeBody, - List parts, - List xpaths, - List contentXpaths) - throws SOAPException { - - List result = new ArrayList(); - - List found = new ArrayList(); - - // Handle sign/enc parts - result.addAll(this.getParts(sign, includeBody, parts, found)); - - // Handle sign/enc elements - result.addAll(this.getElements("Header", xpaths, found, sign)); - - if (!sign) { - // Handle content encrypted elements - result.addAll(this.getElements("Content", contentXpaths, found, sign)); - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getParts(boolean sign, - boolean includeBody, List parts, - List found) throws SOAPException { - - List result = new ArrayList(); - - if (includeBody && !found.contains(SAAJUtils.getBody(this.saaj))) { - found.add(SAAJUtils.getBody(saaj)); - final String id = this.addWsuIdToElement(SAAJUtils.getBody(this.saaj)); - if (sign) { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Element"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } else { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Content"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } - } - - final SOAPHeader header = SAAJUtils.getHeader(saaj); - - // Handle sign/enc parts - for (WSEncryptionPart part : parts) { - if (part.getId() != null && part.getId().startsWith("cid:")) { - // Attachments are handled inside WSS4J via a CallbackHandler - result.add(part); - continue; - } - final List elements; - - if (StringUtils.isEmpty(part.getName())) { - // An entire namespace - elements = - DOMUtils.getChildrenWithNamespace(header, part.getNamespace()); - } else { - // All elements with a given name and namespace - elements = - DOMUtils.getChildrenWithName(header, part.getNamespace(), part.getName()); - } - - for (Element el : elements) { - if (!found.contains(el)) { - found.add(el); - // Generate an ID for the element and use this ID or else - // WSS4J will only ever sign/encrypt the first matching - // element with the same name and namespace as that in the - // WSEncryptionPart - final String id = this.addWsuIdToElement(el); - WSEncryptionPart elPart = - new WSEncryptionPart(id, part.getEncModifier()); - elPart.setElement(el); - result.add(elPart); - } - } - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param encryptionModifier - * indicates the scope of the crypto operation over matched - * elements. Either "Content" or "Element". - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @param forceId - * force adding a wsu:Id onto the elements. Recommended for signatures. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws XPathExpressionException - * if a provided XPath is invalid - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getElements(String encryptionModifier, - List xpaths, - List found, - boolean forceId) throws SOAPException { - - List result = new ArrayList(); - - if (xpaths != null && !xpaths.isEmpty()) { - XPathFactory factory = XPathFactory.newInstance(); - for (org.apache.wss4j.policy.model.XPath xPath : xpaths) { - XPath xpath = factory.newXPath(); - if (xPath.getPrefixNamespaceMap() != null) { - xpath.setNamespaceContext(new MapNamespaceContext(xPath.getPrefixNamespaceMap())); - } - - NodeList list = null; - try { - list = (NodeList)xpath.evaluate(xPath.getXPath(), saaj.getSOAPPart().getEnvelope(), - XPathConstants.NODESET); - } catch (XPathExpressionException e) { - LOG.log(Level.WARNING, "Failure in evaluating an XPath expression", e); - } - - if (list != null) { - for (int x = 0; x < list.getLength(); x++) { - Element el = (Element)list.item(x); - - if (!found.contains(el)) { - String id = setIdOnElement(el, forceId); - WSEncryptionPart part = - new WSEncryptionPart(id, encryptionModifier); - part.setElement(el); - part.setXpath(xPath.getXPath()); - - result.add(part); - } - } - } - } - } - - return result; - } - - private String setIdOnElement(Element element, boolean forceId) { - if (forceId) { - return this.addWsuIdToElement(element); - } - - //not forcing an ID on this. Use one if there is one - //there already, but don't force one - Attr idAttr = element.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = element.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - if (idAttr != null) { - return idAttr.getValue(); - } - - return null; - } - - protected WSSecEncryptedKey getEncryptedKeyBuilder(AbstractToken token) throws WSSecurityException { - WSSecEncryptedKey encrKey = new WSSecEncryptedKey(wssConfig); - encrKey.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - encrKey.setStoreBytesInAttachment(storeBytesInAttachment); - Crypto crypto = getEncryptionCrypto(); - message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - setKeyIdentifierType(encrKey, token); - - boolean alsoIncludeToken = false; - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && encrKey.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE) { - alsoIncludeToken = true; - } - - String encrUser = setEncryptionUser(encrKey, token, false, crypto); - - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - encrKey.setSymmetricEncAlgorithm(algType.getEncryption()); - encrKey.setKeyEncAlgo(algType.getAsymmetricKeyWrap()); - - encrKey.prepare(saaj.getSOAPPart(), crypto); - - if (alsoIncludeToken) { - X509Certificate encCert = getEncryptCert(crypto, encrUser); - BinarySecurity bstToken = new X509Security(saaj.getSOAPPart()); - ((X509Security) bstToken).setX509Certificate(encCert); - bstToken.addWSUNamespace(); - bstToken.setID(wssConfig.getIdAllocator().createSecureId("X509-", encCert)); - WSSecurityUtil.prependChildElement( - secHeader.getSecurityHeader(), bstToken.getElement() - ); - bstElement = bstToken.getElement(); - } - - return encrKey; - } - - private X509Certificate getEncryptCert(Crypto crypto, String encrUser) throws WSSecurityException { - // Check for prepared encryption certificate - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - return encrCert; - } - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - return certs[0]; - } - - public Crypto getSignatureCrypto() throws WSSecurityException { - return getCrypto(SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES); - } - - public Crypto getEncryptionCrypto() throws WSSecurityException { - Crypto crypto = - getCrypto(SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES); - boolean enableRevocation = MessageUtils.isTrue( - message.getContextualProperty(SecurityConstants.ENABLE_REVOCATION)); - if (enableRevocation && crypto != null) { - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - String encrUser = (String)message.getContextualProperty(SecurityConstants.ENCRYPT_USERNAME); - if (encrUser == null) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - if (certs != null && certs.length > 0) { - crypto.verifyTrust(certs, enableRevocation, null); - } - } - if (crypto != null) { - this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - } - return crypto; - - } - - protected Crypto getCrypto( - String cryptoKey, - String propKey - ) throws WSSecurityException { - Crypto crypto = (Crypto)message.getContextualProperty(cryptoKey); - if (crypto != null) { - return crypto; - } - - Object o = message.getContextualProperty(propKey); - if (o == null) { - return null; - } - - crypto = getCryptoCache().get(o); - if (crypto != null) { - return crypto; - } - - ResourceManager manager = - message.getExchange().get(Bus.class).getExtension(ResourceManager.class); - URL propsURL = WSS4JUtils.getPropertiesFileURL(o, manager, this.getClass()); - Properties properties = WSS4JUtils.getProps(o, propsURL); - - if (properties != null) { - crypto = CryptoFactory.getInstance(properties, - Loader.getClassLoader(CryptoFactory.class), - WSS4JUtils.getPasswordEncryptor(message)); - getCryptoCache().put(o, crypto); - } - return crypto; - } - - public void setKeyIdentifierType(WSSecBase secBase, AbstractToken token) { - boolean tokenTypeSet = false; - - if (token instanceof X509Token) { - X509Token x509Token = (X509Token)token; - if (x509Token.isRequireIssuerSerialReference()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - tokenTypeSet = true; - } else if (x509Token.isRequireKeyIdentifierReference()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - tokenTypeSet = true; - } else if (x509Token.isRequireThumbprintReference()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - tokenTypeSet = true; - } - } else if (token instanceof KeyValueToken) { - secBase.setKeyIdentifierType(WSConstants.KEY_VALUE); - tokenTypeSet = true; - } - - assertToken(token); - - if (!tokenTypeSet) { - boolean requestor = isRequestor(); - if (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_NEVER - || token instanceof X509Token - && ((token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_RECIPIENT - && !requestor) - || (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_INITIATOR - && requestor))) { - Wss10 wss = getWss10(); - assertPolicy(wss); - if (wss == null || wss.isMustSupportRefKeyIdentifier()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - } else if (wss.isMustSupportRefIssuerSerial()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } else if (wss instanceof Wss11 && ((Wss11) wss).isMustSupportRefThumbprint()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - } else { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } - } else { - secBase.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); - } - } - } - - public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, AbstractToken token, - boolean sign, Crypto crypto) { - // Check for prepared certificate property - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - encrKeyBuilder.setUseThisCert(encrCert); - return null; - } - - String encrUser = (String)message.getContextualProperty(sign - ? SecurityConstants.SIGNATURE_USERNAME - : SecurityConstants.ENCRYPT_USERNAME); - if (crypto != null && (encrUser == null || "".equals(encrUser))) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - if (encrUser == null || "".equals(encrUser)) { - policyNotAsserted(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared."); - } - if (WSHandlerConstants.USE_REQ_SIG_CERT.equals(encrUser)) { - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - if (results != null) { - encrKeyBuilder.setUseThisCert(WSS4JUtils.getReqSigCert(results)); - - //TODO This is a hack, this should not come under USE_REQ_SIG_CERT - if (encrKeyBuilder.isCertSet()) { - encrKeyBuilder.setUserInfo(getUsername(results)); - } - } else { - policyNotAsserted(token, "No security results in incoming message"); - } - } else { - encrKeyBuilder.setUserInfo(encrUser); - } - - return encrUser; - } - - /** - * Scan through WSHandlerResult list for a Username token and return - * the username if a Username Token found - * @param results - * @return - */ - public static String getUsername(List results) { - /* - * Scan the results for a matching actor. Use results only if the - * receiving Actor and the sending Actor match. - */ - for (WSHandlerResult rResult : results) { - List wsSecEngineResults = rResult.getResults(); - /* - * Scan the results for a username token. Use the username - * of this token to set the alias for the encryption user - */ - for (WSSecurityEngineResult wser : wsSecEngineResults) { - Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION); - if (actInt.intValue() == WSConstants.UT) { - UsernameTokenPrincipal principal - = (UsernameTokenPrincipal)wser.get(WSSecurityEngineResult.TAG_PRINCIPAL); - return principal.getName(); - } - } - } - - return null; - } - - private void checkForX509PkiPath(WSSecSignature sig, AbstractToken token) { - if (token instanceof X509Token) { - X509Token x509Token = (X509Token) token; - TokenType tokenType = x509Token.getTokenType(); - if (tokenType == TokenType.WssX509PkiPathV1Token10 - || tokenType == TokenType.WssX509PkiPathV1Token11) { - sig.setUseSingleCertificate(false); - } - } - } - - protected WSSecSignature getSignatureBuilder( - AbstractToken token, boolean attached, boolean endorse - ) throws WSSecurityException { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - sig.setStoreBytesInAttachment(storeBytesInAttachment); - checkForX509PkiPath(sig, token); - if (token instanceof IssuedToken || token instanceof SamlToken) { - assertToken(token); - SecurityToken securityToken = getSecurityToken(); - String tokenType = securityToken.getTokenType(); - - Element ref; - if (attached) { - ref = securityToken.getAttachedReference(); - } else { - ref = securityToken.getUnattachedReference(); - } - - if (ref != null) { - - // DIGST WORKAROUND START - - // old code that is replaced - // SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - - // new code - String id = securityToken.getId(); - SecurityTokenReference secRef = null; - if ((id != null) && (id.equals("encryptedassertion"))) { - Document doc = ref.getOwnerDocument(); - secRef = new SecurityTokenReference(doc); - secRef.addTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"); - Element keyId = doc.createElementNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:KeyIdentifier"); - keyId.setAttributeNS(null, "ValueType", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID"); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRef.getElement(); - elem.appendChild(keyId); - } - else { - secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - } - - // DIGST WORKAROUND END - - sig.setSecurityTokenReference(secRef); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - int type = attached ? WSConstants.CUSTOM_SYMM_SIGNING - : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT; - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - sig.setCustomTokenValueType(tokenType); - sig.setKeyIdentifierType(type); - } - } - - String sigTokId; - if (attached) { - sigTokId = securityToken.getWsuId(); - if (sigTokId == null) { - sigTokId = securityToken.getId(); - } - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - } else { - sigTokId = securityToken.getId(); - } - - sig.setCustomTokenId(sigTokId); - } else { - setKeyIdentifierType(sig, token); - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && (sig.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE - && sig.getKeyIdentifierType() != WSConstants.KEY_VALUE)) { - sig.setIncludeSignatureToken(true); - } - } - - boolean encryptCrypto = false; - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - String type = "signature"; - if (binding instanceof SymmetricBinding && !endorse) { - encryptCrypto = ((SymmetricBinding)binding).getProtectionToken() != null; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - } - - Crypto crypto = encryptCrypto ? getEncryptionCrypto() : getSignatureCrypto(); - - if (endorse && crypto == null && binding instanceof SymmetricBinding) { - type = "encryption"; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - crypto = getEncryptionCrypto(); - } - - if (!encryptCrypto) { - message.getExchange().put(SecurityConstants.SIGNATURE_CRYPTO, crypto); - } - String user = (String)message.getContextualProperty(userNameKey); - if (StringUtils.isEmpty(user)) { - if (crypto != null) { - try { - user = crypto.getDefaultX509Identifier(); - if (StringUtils.isEmpty(user)) { - policyNotAsserted(token, "No configured " + type + " username detected"); - return null; - } - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - } else { - policyNotAsserted(token, "Security configuration could not be detected. " - + "Potential cause: Make sure jaxws:client element with name " - + "attribute value matching endpoint port is defined as well as a " - + SecurityConstants.SIGNATURE_PROPERTIES + " element within it."); - return null; - } - } - - String password = getPassword(user, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(user, password); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.setWsConfig(wssConfig); - try { - sig.prepare(saaj.getSOAPPart(), crypto, secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - policyNotAsserted(token, e); - } - - return sig; - } - - protected void doEndorsedSignatures(List tokenList, - boolean isTokenProtection, - boolean isSigProtect) { - - for (SupportingToken supportingToken : tokenList) { - Object tempTok = supportingToken.getTokenImplementation(); - - List sigParts = new ArrayList(); - WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId); - sigPart.setElement(bottomUpElement); - sigParts.add(sigPart); - - if (supportingToken.getSignedParts() != null) { - for (WSEncryptionPart signedPart : supportingToken.getSignedParts()) { - sigParts.add(signedPart); - } - } - - if (tempTok instanceof WSSecSignature) { - WSSecSignature sig = (WSSecSignature)tempTok; - if (isTokenProtection && sig.getBSTTokenId() != null) { - WSEncryptionPart bstPart = - new WSEncryptionPart(sig.getBSTTokenId()); - bstPart.setElement(sig.getBinarySecurityTokenElement()); - sigParts.add(bstPart); - } - try { - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - sig.computeSignature(referenceList, false, null); - - signatures.add(sig.getSignatureValue()); - if (isSigProtect) { - WSEncryptionPart part = new WSEncryptionPart(sig.getId(), "Element"); - encryptedTokensList.add(part); - } - } catch (WSSecurityException e) { - policyNotAsserted(supportingToken.getToken(), e); - } - - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(token.getId())); - } - - try { - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), token, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), token, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken utBuilder = (WSSecUsernameToken)tempTok; - String id = utBuilder.getId(); - - Date created = new Date(); - Date expires = new Date(); - expires.setTime(created.getTime() + 300000); - SecurityToken secToken = - new SecurityToken(id, utBuilder.getUsernameTokenElement(), created, expires); - - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(secToken.getId())); - } - - try { - byte[] secret = utBuilder.getDerivedKey(); - secToken.setSecret(secret); - - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), secToken, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), secToken, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - - } - } - } - - private void doSymmSignatureDerived(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecDKSign dkSign = new WSSecDKSign(wssConfig); - - //Check whether it is security policy 1.2 and use the secure conversation accordingly - if (policyToken.getVersion() == SPConstants.SPVersion.SP11) { - dkSign.setWscVersion(ConversationConstants.VERSION_05_02); - } - - //Check for whether the token is attached in the message or not - boolean attached = false; - if (isTokenRequired(policyToken.getIncludeTokenType())) { - attached = true; - } - - // Setting the AttachedReference or the UnattachedReference according to the flag - Element ref; - if (attached) { - ref = tok.getAttachedReference(); - } else { - ref = tok.getUnattachedReference(); - } - - if (ref != null) { - ref = cloneElement(ref); - dkSign.setExternalKey(tok.getSecret(), ref); - } else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - // If the Encrypted key used to create the derived key is not - // attached use key identifier as defined in WSS1.1 section - // 7.7 Encrypted Key reference - SecurityTokenReference tokenRef - = new SecurityTokenReference(doc); - if (tok.getSHA1() != null) { - tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1()); - tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE); - } - dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement()); - - } else { - dkSign.setExternalKey(tok.getSecret(), tok.getId()); - } - - //Set the algo info - dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - dkSign.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8); - if (tok.getSHA1() != null) { - //Set the value type of the reference - dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#" - + WSConstants.ENC_KEY_VALUE_TYPE); - } else if (policyToken instanceof UsernameToken) { - dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } - - dkSign.prepare(doc, secHeader); - - if (isTokenProtection) { - //Hack to handle reference id issues - //TODO Need a better fix - String sigTokId = tok.getId(); - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - sigParts.add(new WSEncryptionPart(sigTokId)); - } - - dkSign.setParts(sigParts); - - List referenceList = dkSign.addReferencesToSign(sigParts, secHeader); - - //Add elements to header - addSupportingElement(dkSign.getdktElement()); - - //Do signature - dkSign.computeSignature(referenceList, false, null); - - signatures.add(dkSign.getSignatureValue()); - } - - private void doSymmSignature(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecSignature sig = new WSSecSignature(wssConfig); - // If a EncryptedKeyToken is used, set the correct value type to - // be used in the wsse:Reference in ds:KeyInfo - if (policyToken instanceof X509Token) { - if (isRequestor()) { - // TODO Add support for SAML2 here - sig.setCustomTokenValueType( - WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE - ); - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } else { - //the tok has to be an EncryptedKey token - sig.setEncrKeySha1value(tok.getSHA1()); - sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); - } - - } else { - String tokenType = tok.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else if (policyToken instanceof UsernameToken) { - sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } - - String sigTokId = tok.getWsuId(); - if (sigTokId == null) { - sigTokId = tok.getId(); - } - - //Hack to handle reference id issues - //TODO Need a better fix - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - - sig.setCustomTokenId(sigTokId); - sig.setSecretKey(tok.getSecret()); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.prepare(doc, getSignatureCrypto(), secHeader); - - sig.setParts(sigParts); - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - - //Do signature - sig.computeSignature(referenceList, false, null); - signatures.add(sig.getSignatureValue()); - } - - protected void addSupportingTokens(List sigs) throws WSSecurityException { - Collection sgndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_SUPPORTING_TOKENS); - List sigSuppTokList = this.handleSupportingTokens(sgndSuppTokens, false); - - Collection endSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_SUPPORTING_TOKENS); - endSuppTokList = this.handleSupportingTokens(endSuppTokens, true); - - Collection sgndEndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_SUPPORTING_TOKENS); - sgndEndSuppTokList = this.handleSupportingTokens(sgndEndSuppTokens, true); - - Collection sgndEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENCRYPTED_SUPPORTING_TOKENS); - List sgndEncSuppTokList - = this.handleSupportingTokens(sgndEncryptedSuppTokens, false); - - Collection endorsingEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - endSuppTokList.addAll(this.handleSupportingTokens(endorsingEncryptedSuppTokens, true)); - - Collection sgndEndEncSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - sgndEndSuppTokList.addAll(this.handleSupportingTokens(sgndEndEncSuppTokens, true)); - - Collection supportingToks = - getAllAssertionsByLocalname(aim, SPConstants.SUPPORTING_TOKENS); - this.handleSupportingTokens(supportingToks, false); - - Collection encryptedSupportingToks = - getAllAssertionsByLocalname(aim, SPConstants.ENCRYPTED_SUPPORTING_TOKENS); - this.handleSupportingTokens(encryptedSupportingToks, false); - - //Setup signature parts - addSignatureParts(sigSuppTokList, sigs); - addSignatureParts(sgndEncSuppTokList, sigs); - addSignatureParts(sgndEndSuppTokList, sigs); - } - - protected void doEndorse() { - boolean tokenProtect = false; - boolean sigProtect = false; - if (binding instanceof AsymmetricBinding) { - tokenProtect = ((AsymmetricBinding)binding).isProtectTokens(); - sigProtect = ((AsymmetricBinding)binding).isEncryptSignature(); - } else if (binding instanceof SymmetricBinding) { - tokenProtect = ((SymmetricBinding)binding).isProtectTokens(); - sigProtect = ((SymmetricBinding)binding).isEncryptSignature(); - } - // Do endorsed signatures - doEndorsedSignatures(endSuppTokList, tokenProtect, sigProtect); - - // Do signed endorsing signatures - doEndorsedSignatures(sgndEndSuppTokList, tokenProtect, sigProtect); - } - - protected void addSignatureConfirmation(List sigParts) { - Wss10 wss10 = getWss10(); - - if (!(wss10 instanceof Wss11) - || !((Wss11)wss10).isRequireSignatureConfirmation()) { - //If we don't require sig confirmation simply go back :-) - return; - } - - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - /* - * loop over all results gathered by all handlers in the chain. For each - * handler result get the various actions. After that loop we have all - * signature results in the signatureActions list - */ - List signatureActions = new ArrayList(); - final List signedActions = new ArrayList(2); - signedActions.add(WSConstants.SIGN); - signedActions.add(WSConstants.UT_SIGN); - for (WSHandlerResult wshResult : results) { - signatureActions.addAll( - WSSecurityUtil.fetchAllActionResults(wshResult.getResults(), signedActions) - ); - } - - sigConfList = new ArrayList(); - // prepare a SignatureConfirmation token - WSSecSignatureConfirmation wsc = new WSSecSignatureConfirmation(wssConfig); - if (signatureActions.size() > 0) { - for (WSSecurityEngineResult wsr : signatureActions) { - byte[] sigVal = (byte[]) wsr.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE); - wsc.setSignatureValue(sigVal); - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - } else { - //No Sig value - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - - assertPolicy( - new QName(wss10.getName().getNamespaceURI(), SPConstants.REQUIRE_SIGNATURE_CONFIRMATION)); - } - - /** - * Processes the parts to be signed and reconfigures those parts that have - * already been encrypted. - * - * @param encryptedParts - * the parts that have been encrypted - * @param signedParts - * the parts that are to be signed - * - * @throws IllegalArgumentException - * if an element in {@code signedParts} contains a {@code - * WSEncryptionPart} with a {@code null} {@code id} value - * and the {@code WSEncryptionPart} {@code name} value is not - * "Token" - */ - public void handleEncryptedSignedHeaders(List encryptedParts, - List signedParts) { - - final List signedEncryptedParts = new ArrayList(); - - for (WSEncryptionPart encryptedPart : encryptedParts) { - final Iterator signedPartsIt = signedParts.iterator(); - while (signedPartsIt.hasNext()) { - WSEncryptionPart signedPart = signedPartsIt.next(); - // Everything has to be ID based except for the case of a part - // indicating "Token" as the element name. This name is a flag - // for WSS4J to sign the initiator token used in the signature. - // Since the encryption happened before the signature creation, - // this element can't possibly be encrypted so we can safely ignore - // if it were ever to be set before this method is called. - if (signedPart.getId() == null && !"Token".equals(signedPart.getName())) { - throw new IllegalArgumentException( - "WSEncryptionPart must be ID based but no id was found."); - } else if (encryptedPart.getEncModifier().equals("Header") - && signedPart.getId().equals(encryptedPart.getId())) { - // We are to sign something that has already been encrypted. - // We need to preserve the original aspects of signedPart but - // change the ID to the encrypted ID. - - signedPartsIt.remove(); - WSEncryptionPart part = new WSEncryptionPart( - encryptedPart.getEncId(), - encryptedPart.getEncModifier()); - part.setElement(encryptedPart.getElement()); - signedEncryptedParts.add(part); - } - } - } - - signedParts.addAll(signedEncryptedParts); - } - - /** - * Convert a DOM Element into a WSEncryptionPart, adding a (wsu:)Id if there is not - * one already. - * @param element The DOM Element to convert - * @return The WSEncryptionPart representing the DOM Element argument - */ - public WSEncryptionPart convertToEncryptionPart(Element element) { - String id = addWsuIdToElement(element); - WSEncryptionPart part = new WSEncryptionPart(id); - part.setElement(element); - return part; - } - - static class SupportingToken { - private final AbstractToken token; - private final Object tokenImplementation; - private final List signedParts; - - public SupportingToken(AbstractToken token, Object tokenImplementation, - List signedParts) { - this.token = token; - this.tokenImplementation = tokenImplementation; - this.signedParts = signedParts; - } - - public AbstractToken getToken() { - return token; - } - - public Object getTokenImplementation() { - return tokenImplementation; - } - - public List getSignedParts() { - return signedParts; - } - - } -} diff --git a/examples/lbsb/signature-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java b/examples/lbsb/signature-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java deleted file mode 100644 index 96cb070..0000000 --- a/examples/lbsb/signature-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java +++ /dev/null @@ -1,281 +0,0 @@ -// NOTE!!! -// -// This is a copy of STRTransform.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the transformIt() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it returns an EncryptedAssertion -// element with an embedded EncryptedData element. The EncryptedData element has the ID -// referenced by the RAR in the RequestSecurityTokenResponse, but we need to dereference -// the parent element for this to work - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom.transform; - -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSDocInfo; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.message.token.PKIPathSecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; - -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignatureInput; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import java.io.ByteArrayInputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Iterator; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.NodeSetData; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; - - -/** - * Class STRTransform. - */ -public class STRTransform extends TransformService { - - public static final String TRANSFORM_URI = - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform"; - - public static final String TRANSFORM_WS_DOC_INFO = "transform_ws_doc_info"; - - private TransformParameterSpec params; - - private Element transformElement; - - private static final org.slf4j.Logger LOG = - org.slf4j.LoggerFactory.getLogger(STRTransform.class); - - public final AlgorithmParameterSpec getParameterSpec() { - return params; - } - - public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { - this.params = params; - } - - public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - transformElement = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - } - - public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - Element transformElement2 = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - appendChild(transformElement2, transformElement); - transformElement = transformElement2; - } - - - public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - return transformIt(data, xc, null); - } - - public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - if (os == null) { - throw new NullPointerException("output stream must not be null"); - } - return transformIt(data, xc, os); - } - - - private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - - // - // First step: Get the required c14n argument and get the specified - // Canonicalizer - // - String canonAlgo = null; - Element transformParams = WSSecurityUtil.getDirectChildElement( - transformElement, "TransformationParameters", WSConstants.WSSE_NS - ); - if (transformParams != null) { - Element canonElem = - WSSecurityUtil.getDirectChildElement( - transformParams, "CanonicalizationMethod", WSConstants.SIG_NS - ); - canonAlgo = canonElem.getAttributeNS(null, "Algorithm"); - } - try { - // - // Get the input (node) to transform. - // - Element str = null; - if (data instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)data; - Iterator iterator = nodeSetData.iterator(); - while (iterator.hasNext()) { - Node node = (Node)iterator.next(); - if (node instanceof Element && "SecurityTokenReference".equals(node.getLocalName())) { - str = (Element)node; - break; - } - } - } else { - try { - XMLSignatureInput xmlSignatureInput = - new XMLSignatureInput(((OctetStreamData)data).getOctetStream()); - str = (Element)xmlSignatureInput.getSubNode(); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - if (str == null) { - throw new TransformException("No SecurityTokenReference found"); - } - // - // The element to transform MUST be a SecurityTokenReference - // element. - // - SecurityTokenReference secRef = new SecurityTokenReference(str, new BSPEnforcer()); - - Canonicalizer canon = Canonicalizer.getInstance(canonAlgo); - - byte[] buf = null; - - // - // Third and fourth step are performed by dereferenceSTR() - // - Object wsDocInfoObject = xc.getProperty(TRANSFORM_WS_DOC_INFO); - WSDocInfo wsDocInfo = null; - if (wsDocInfoObject instanceof WSDocInfo) { - wsDocInfo = (WSDocInfo)wsDocInfoObject; - } - if (wsDocInfo == null) { - LOG.debug("STRTransform: no WSDocInfo found"); - } - - Document doc = str.getOwnerDocument(); - Element dereferencedToken = - STRTransformUtil.dereferenceSTR(doc, secRef, wsDocInfo); - - if (dereferencedToken != null) { - String type = dereferencedToken.getAttributeNS(null, "ValueType"); - if (X509Security.X509_V3_TYPE.equals(type) - || PKIPathSecurity.getType().equals(type)) { - // - // Add the WSSE/WSU namespaces to the element for C14n - // - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX - ); - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSU_NS, WSConstants.WSU_PREFIX - ); - } - } - - // BEGIN DIGST WORKAROUND - boolean parentNodeIsNull = (dereferencedToken.getParentNode() == null); - boolean encryptedAssertionId = (dereferencedToken.getAttribute("wsu:Id") != null && dereferencedToken.getAttribute("wsu:Id").equals("encryptedassertion")); - - if (!parentNodeIsNull && encryptedAssertionId) { - dereferencedToken = (Element) dereferencedToken.getParentNode(); - } - // END DIGST WORKAROUND - - // - // C14n with specified algorithm. According to WSS Specification. - // - buf = canon.canonicalizeSubtree(dereferencedToken, "#default", true); - if (LOG.isDebugEnabled()) { - LOG.debug("after c14n: " + new String(buf, "UTF-8")); - } - - if (os != null) { - os.write(buf); - return null; - } - return new OctetStreamData(new ByteArrayInputStream(buf)); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - - - public final boolean isFeatureSupported(String feature) { - if (feature == null) { - throw new NullPointerException(); - } else { - return false; - } - } - - private static void appendChild(Node parent, Node child) { - Document ownerDoc = null; - if (parent.getNodeType() == Node.DOCUMENT_NODE) { - ownerDoc = (Document)parent; - } else { - ownerDoc = parent.getOwnerDocument(); - } - if (child.getOwnerDocument() != ownerDoc) { - parent.appendChild(ownerDoc.importNode(child, true)); - } else { - parent.appendChild(child); - } - } - -} diff --git a/examples/lbsb/signature-scenario/src/main/resources/HelloWorld-Bearer.wsdl b/examples/lbsb/signature-scenario/src/main/resources/HelloWorld-Bearer.wsdl deleted file mode 100644 index 7577cfe..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/HelloWorld-Bearer.wsdl +++ /dev/null @@ -1,164 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/signature-scenario/src/main/resources/client.pfx b/examples/lbsb/signature-scenario/src/main/resources/client.pfx deleted file mode 100644 index f6ed4ce..0000000 Binary files a/examples/lbsb/signature-scenario/src/main/resources/client.pfx and /dev/null differ diff --git a/examples/lbsb/signature-scenario/src/main/resources/client.properties b/examples/lbsb/signature-scenario/src/main/resources/client.properties deleted file mode 100644 index 12c9d5e..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/client.properties +++ /dev/null @@ -1,10 +0,0 @@ -# the keystore contains the FOCES that we use to sign the request to the service -org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=java ref. test (funktionscertifikat) -org.apache.ws.security.crypto.merlin.file=client.pfx - -# the trust store contains the certificate used by the service to sign the response -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/signature-scenario/src/main/resources/cxf.xml b/examples/lbsb/signature-scenario/src/main/resources/cxf.xml deleted file mode 100644 index f14d064..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/cxf.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/signature-scenario/src/main/resources/sts.properties b/examples/lbsb/signature-scenario/src/main/resources/sts.properties deleted file mode 100644 index 8af9ada..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/sts.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=jks -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=sts -org.apache.ws.security.crypto.merlin.file=trust.jks diff --git a/examples/lbsb/signature-scenario/src/main/resources/sts.wsdl b/examples/lbsb/signature-scenario/src/main/resources/sts.wsdl deleted file mode 100644 index 367a5ec..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/sts.wsdl +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/signature-scenario/src/main/resources/trust.jks b/examples/lbsb/signature-scenario/src/main/resources/trust.jks deleted file mode 100644 index 74dedb8..0000000 Binary files a/examples/lbsb/signature-scenario/src/main/resources/trust.jks and /dev/null differ diff --git a/examples/lbsb/signature-scenario/src/main/resources/user.properties b/examples/lbsb/signature-scenario/src/main/resources/user.properties deleted file mode 100644 index 080e3fb..0000000 --- a/examples/lbsb/signature-scenario/src/main/resources/user.properties +++ /dev/null @@ -1,7 +0,0 @@ -# the users keystore is supplied at runtime by the user, which this class handles -org.apache.ws.security.crypto.provider=client.crypto.UserCertificateStore - -# the trust store contains the certificate of the sts -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/system-user-scenario/pom.xml b/examples/lbsb/system-user-scenario/pom.xml deleted file mode 100644 index 5c8d07d..0000000 --- a/examples/lbsb/system-user-scenario/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - 4.0.0 - - dk.gov.oio.idws - reference-lbsb-parent - 1.0.0-SNAPSHOT - - cxf-wsc-lbsb-system - CXF WS Consumer for System User Scenario (LBSB) - jar - - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.apache.cxf - cxf-codegen-plugin - - - commons-logging - commons-logging - 1.1.1 - - - - - - - ${basedir}/target/generated-sources - - - - - ${basedir}/src/main/resources/HelloWorld-Hok.wsdl - - classpath:HelloWorld-Hok.wsdl - - - - - - - - - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - org.apache.cxf - cxf-rt-transports-http - - - - org.apache.cxf - cxf-rt-ws-security - - - - commons-io - commons-io - - - - org.springframework - spring-context - - - - org.slf4j - slf4j-jdk14 - - - diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/WSClient.java b/examples/lbsb/system-user-scenario/src/main/java/client/WSClient.java deleted file mode 100644 index f2cb32e..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/WSClient.java +++ /dev/null @@ -1,41 +0,0 @@ -package client; - -import javax.xml.ws.soap.SOAPFaultException; - -import org.example.contract.helloworld.HelloWorldPortType; -import org.example.contract.helloworld.HelloWorldService; -import org.example.contract.helloworld.MissingName; - -public class WSClient { - public static void main (String[] args) { - HelloWorldService service = new HelloWorldService(); - HelloWorldPortType port = service.getHelloWorldPort(); - - try { - // first call will also call the STS - hello(port, "John"); - - // second call will reuse the cached token we got from the first call - hello(port, "Jane"); - - // third call will trigger a SOAPFault - try { - hello(port, ""); - System.out.println("Call did not fail as expected!"); - } - catch (SOAPFaultException ex) { - System.out.println("Expected SOAPFault caught: " + ex.getMessage()); - } - } - catch (Exception ex) { - // unexpected - ex.printStackTrace(); - } - } - - public static void hello(HelloWorldPortType port, String name) throws MissingName { - String resp = port.helloWorld(name); - - System.out.println(resp); - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/callback/ClientCallbackHandler.java b/examples/lbsb/system-user-scenario/src/main/java/client/callback/ClientCallbackHandler.java deleted file mode 100644 index 58fbb49..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/callback/ClientCallbackHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package client.callback; - -import java.io.IOException; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.apache.wss4j.common.ext.WSPasswordCallback; - -public class ClientCallbackHandler implements CallbackHandler { - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (int i = 0; i < callbacks.length; i++) { - if (callbacks[i] instanceof WSPasswordCallback) { - WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; - - if (pc.getUsage() == WSPasswordCallback.DECRYPT || pc.getUsage() == WSPasswordCallback.SIGNATURE) { - pc.setPassword("Test1234"); - } - } - } - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java b/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java deleted file mode 100644 index 4e20eaf..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/FrameworkHeaderInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package client.interceptor; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapHeader; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; - -import client.model.SbfFrameworkHeader; - -public class FrameworkHeaderInterceptor extends AbstractSoapInterceptor { - public FrameworkHeaderInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - try { - Header framework = new SoapHeader(new QName("urn:liberty:sb", "Framework", "sbf"), new SbfFrameworkHeader(), new JAXBDataBinding(SbfFrameworkHeader.class)); - headers.add(framework); - } - catch (Exception ex) { - throw new XMLFault(ex.getMessage()); - } - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java b/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java deleted file mode 100644 index 4a67698..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/interceptor/STSAddressingInterceptor.java +++ /dev/null @@ -1,61 +0,0 @@ -package client.interceptor; - -import java.util.List; -import java.util.UUID; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; - -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; -import org.apache.cxf.binding.xml.XMLFault; -import org.apache.cxf.headers.Header; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.jaxb.JAXBDataBinding; -import org.apache.cxf.phase.Phase; -import org.apache.cxf.ws.addressing.AttributedURIType; -import org.apache.cxf.ws.addressing.ObjectFactory; - -public class STSAddressingInterceptor extends AbstractSoapInterceptor { - public STSAddressingInterceptor() { - super(Phase.PRE_PROTOCOL); - } - - @Override - public void handleMessage(SoapMessage message) throws Fault { - List
headers = message.getHeaders(); - - ObjectFactory wsAddressingFactory = new ObjectFactory(); - - AttributedURIType to = new AttributedURIType(); - AttributedURIType messageId = new AttributedURIType(); - AttributedURIType action = new AttributedURIType(); - - to.setValue("https://signature.sts.nemlog-in.dk/"); - action.setValue("http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); - messageId.setValue("uuid:" + UUID.randomUUID().toString()); - - JAXBElement createTo = wsAddressingFactory.createTo(to); - JAXBElement msgId = wsAddressingFactory.createMessageID(messageId); - JAXBElement newAction = wsAddressingFactory.createAction(action); - - JAXBDataBinding jaxbDataBinding = null; - try { - jaxbDataBinding = new JAXBDataBinding(AttributedURIType.class); - } - catch (JAXBException ex) { - throw new XMLFault(ex.getMessage()); - } - - Header toHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), createTo, jaxbDataBinding); - Header msgIdHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), msgId, jaxbDataBinding); - Header actionHeader = new Header(new QName("http://www.w3.org/2005/08/addressing"), newAction, jaxbDataBinding); - - headers.add(actionHeader); - headers.add(msgIdHeader); - headers.add(toHeader); - - message.put(Header.HEADER_LIST, headers); - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/model/SbfFrameworkHeader.java b/examples/lbsb/system-user-scenario/src/main/java/client/model/SbfFrameworkHeader.java deleted file mode 100644 index 0784fba..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/model/SbfFrameworkHeader.java +++ /dev/null @@ -1,23 +0,0 @@ -package client.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; - -@XmlAccessorType(XmlAccessType.FIELD) -public class SbfFrameworkHeader { - - @XmlAttribute(name="version") - private final String version = "2.0"; - - @XmlAttribute(name="profile", namespace="urn:liberty:sb:profile") - private final String profile = "urn:liberty:sb:profile:basic"; - - public String getVersion() { - return version; - } - - public String getProfile() { - return profile; - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/client/sts/DigstSTSClient.java b/examples/lbsb/system-user-scenario/src/main/java/client/sts/DigstSTSClient.java deleted file mode 100644 index 8912cce..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/client/sts/DigstSTSClient.java +++ /dev/null @@ -1,44 +0,0 @@ -package client.sts; - -import java.util.UUID; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import org.apache.cxf.Bus; -import org.apache.cxf.ws.security.trust.STSClient; - -import client.interceptor.STSAddressingInterceptor; - -public class DigstSTSClient extends STSClient { - public DigstSTSClient(Bus b) { - super(b); - - this.out.add(new STSAddressingInterceptor()); - - createUniqueContextAttribute(); - } - - @Override - protected void addAppliesTo(XMLStreamWriter writer, String appliesTo) throws XMLStreamException { - createUniqueContextAttribute(); - - if (appliesTo != null && addressingNamespace != null) { - // modified the namespace so it uses ws-policy 1.1 namespace (not supported by CXF, so we have to do this hacky thing) - writer.writeStartElement("wsp", "AppliesTo", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeNamespace("wsp", "http://schemas.xmlsoap.org/ws/2002/12/policy"); - writer.writeStartElement("wsa", "EndpointReference", addressingNamespace); - writer.writeNamespace("wsa", addressingNamespace); - writer.writeStartElement("wsa", "Address", addressingNamespace); - writer.writeCharacters(appliesTo); - writer.writeEndElement(); - writer.writeEndElement(); - writer.writeEndElement(); - } - } - - // we are required to set a unique @Context attribute on the request - private void createUniqueContextAttribute() { - this.context = "urn:uuid:" + UUID.randomUUID().toString(); - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java b/examples/lbsb/system-user-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java deleted file mode 100644 index 3c4724a..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java +++ /dev/null @@ -1,2273 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.cxf.ws.security.wss4j.policyhandlers; - -import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.callback.CallbackHandler; -import javax.xml.crypto.dsig.Reference; -import javax.xml.namespace.QName; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPHeader; -import javax.xml.soap.SOAPMessage; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.apache.cxf.Bus; -import org.apache.cxf.attachment.AttachmentUtil; -import org.apache.cxf.binding.soap.SoapMessage; -import org.apache.cxf.binding.soap.saaj.SAAJUtils; -import org.apache.cxf.common.classloader.ClassLoaderUtils; -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.endpoint.Endpoint; -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.helpers.DOMUtils; -import org.apache.cxf.helpers.MapNamespaceContext; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.message.MessageUtils; -import org.apache.cxf.resource.ResourceManager; -import org.apache.cxf.service.model.EndpointInfo; -import org.apache.cxf.staxutils.StaxUtils; -import org.apache.cxf.staxutils.W3CDOMStreamWriter; -import org.apache.cxf.ws.policy.AssertionInfo; -import org.apache.cxf.ws.policy.AssertionInfoMap; -import org.apache.cxf.ws.policy.PolicyConstants; -import org.apache.cxf.ws.security.SecurityConstants; -import org.apache.cxf.ws.security.tokenstore.SecurityToken; -import org.apache.cxf.ws.security.tokenstore.TokenStore; -import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler; -import org.apache.cxf.ws.security.wss4j.WSS4JUtils; -import org.apache.cxf.wsdl.WSDLConstants; -import org.apache.neethi.Assertion; -import org.apache.wss4j.common.WSEncryptionPart; -import org.apache.wss4j.common.crypto.Crypto; -import org.apache.wss4j.common.crypto.CryptoFactory; -import org.apache.wss4j.common.crypto.CryptoType; -import org.apache.wss4j.common.derivedKey.ConversationConstants; -import org.apache.wss4j.common.ext.WSPasswordCallback; -import org.apache.wss4j.common.ext.WSSecurityException; -import org.apache.wss4j.common.principal.UsernameTokenPrincipal; -import org.apache.wss4j.common.saml.SAMLCallback; -import org.apache.wss4j.common.saml.SAMLUtil; -import org.apache.wss4j.common.saml.SamlAssertionWrapper; -import org.apache.wss4j.common.util.Loader; -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSSConfig; -import org.apache.wss4j.dom.WSSecurityEngineResult; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.handler.WSHandlerConstants; -import org.apache.wss4j.dom.handler.WSHandlerResult; -import org.apache.wss4j.dom.message.WSSecBase; -import org.apache.wss4j.dom.message.WSSecDKSign; -import org.apache.wss4j.dom.message.WSSecEncryptedKey; -import org.apache.wss4j.dom.message.WSSecHeader; -import org.apache.wss4j.dom.message.WSSecSignature; -import org.apache.wss4j.dom.message.WSSecSignatureConfirmation; -import org.apache.wss4j.dom.message.WSSecTimestamp; -import org.apache.wss4j.dom.message.WSSecUsernameToken; -import org.apache.wss4j.dom.message.token.BinarySecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; -import org.apache.wss4j.policy.SPConstants; -import org.apache.wss4j.policy.SPConstants.IncludeTokenType; -import org.apache.wss4j.policy.model.AbstractBinding; -import org.apache.wss4j.policy.model.AbstractSecurityAssertion; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding; -import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding.ProtectionOrder; -import org.apache.wss4j.policy.model.AbstractToken; -import org.apache.wss4j.policy.model.AbstractToken.DerivedKeys; -import org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType; -import org.apache.wss4j.policy.model.AsymmetricBinding; -import org.apache.wss4j.policy.model.Attachments; -import org.apache.wss4j.policy.model.ContentEncryptedElements; -import org.apache.wss4j.policy.model.EncryptedElements; -import org.apache.wss4j.policy.model.EncryptedParts; -import org.apache.wss4j.policy.model.Header; -import org.apache.wss4j.policy.model.IssuedToken; -import org.apache.wss4j.policy.model.KerberosToken; -import org.apache.wss4j.policy.model.KeyValueToken; -import org.apache.wss4j.policy.model.Layout.LayoutType; -import org.apache.wss4j.policy.model.SamlToken; -import org.apache.wss4j.policy.model.SamlToken.SamlTokenType; -import org.apache.wss4j.policy.model.SecureConversationToken; -import org.apache.wss4j.policy.model.SecurityContextToken; -import org.apache.wss4j.policy.model.SignedElements; -import org.apache.wss4j.policy.model.SignedParts; -import org.apache.wss4j.policy.model.SpnegoContextToken; -import org.apache.wss4j.policy.model.SupportingTokens; -import org.apache.wss4j.policy.model.SymmetricBinding; -import org.apache.wss4j.policy.model.UsernameToken; -import org.apache.wss4j.policy.model.Wss10; -import org.apache.wss4j.policy.model.Wss11; -import org.apache.wss4j.policy.model.X509Token; -import org.apache.wss4j.policy.model.X509Token.TokenType; -import org.opensaml.common.SAMLVersion; - -/** - * - */ -public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandler { - public static final String CRYPTO_CACHE = "ws-security.crypto.cache"; - protected static final Logger LOG = LogUtils.getL7dLogger(AbstractBindingBuilder.class); - - protected AbstractSymmetricAsymmetricBinding.ProtectionOrder protectionOrder = - AbstractSymmetricAsymmetricBinding.ProtectionOrder.SignBeforeEncrypting; - - protected final WSSConfig wssConfig; - protected SOAPMessage saaj; - protected WSSecHeader secHeader; - protected AssertionInfoMap aim; - protected AbstractBinding binding; - protected WSSecTimestamp timestampEl; - protected String mainSigId; - protected List sigConfList; - - protected Set encryptedTokensList = new HashSet(); - - protected List signatures = new ArrayList(); - - protected Element bottomUpElement; - protected Element topDownElement; - protected Element bstElement; - protected Element lastEncryptedKeyElement; - protected boolean storeBytesInAttachment; - - private Element lastSupportingTokenElement; - private Element lastDerivedKeyElement; - - private List suppTokenParts = new ArrayList(); - private List endSuppTokList; - private List sgndEndSuppTokList; - - public AbstractBindingBuilder( - WSSConfig config, - AbstractBinding binding, - SOAPMessage saaj, - WSSecHeader secHeader, - AssertionInfoMap aim, - SoapMessage message) { - super(message); - this.wssConfig = config; - this.binding = binding; - this.aim = aim; - this.secHeader = secHeader; - this.saaj = saaj; - message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures); - - boolean storeBytes = - MessageUtils.getContextualBoolean( - message, SecurityConstants.STORE_BYTES_IN_ATTACHMENT, false - ); - if (storeBytes && AttachmentUtil.isMtomEnabled(message)) { - storeBytesInAttachment = true; - if (binding instanceof AbstractSymmetricAsymmetricBinding - && (ProtectionOrder.EncryptBeforeSigning - == ((AbstractSymmetricAsymmetricBinding)binding).getProtectionOrder() - || ((AbstractSymmetricAsymmetricBinding)binding).isProtectTokens())) { - LOG.fine("Disabling SecurityConstants.STORE_BYTES_IN_ATTACHMENT due to " - + "EncryptBeforeSigning or ProtectTokens policy."); - storeBytesInAttachment = false; - } - } - - } - - protected void insertAfter(Element child, Element sib) { - if (sib.getNextSibling() == null) { - secHeader.getSecurityHeader().appendChild(child); - } else { - secHeader.getSecurityHeader().insertBefore(child, sib.getNextSibling()); - } - } - - protected void addDerivedKeyElement(Element el) { - if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addEncryptedKeyElement(Element el) { - if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (lastDerivedKeyElement != null) { - secHeader.getSecurityHeader().insertBefore(el, lastDerivedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (secHeader.getSecurityHeader().getFirstChild() != null) { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastEncryptedKeyElement = el; - } - - protected void addSupportingElement(Element el) { - if (lastSupportingTokenElement != null) { - insertAfter(el, lastSupportingTokenElement); - } else if (lastDerivedKeyElement != null) { - insertAfter(el, lastDerivedKeyElement); - } else if (lastEncryptedKeyElement != null) { - insertAfter(el, lastEncryptedKeyElement); - } else if (topDownElement != null) { - insertAfter(el, topDownElement); - } else if (bottomUpElement != null) { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } else { - secHeader.getSecurityHeader().appendChild(el); - } - lastSupportingTokenElement = el; - } - - protected void insertBeforeBottomUp(Element el) { - if (bottomUpElement == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore(el, bottomUpElement); - } - bottomUpElement = el; - } - - protected void addTopDownElement(Element el) { - if (topDownElement == null) { - if (secHeader.getSecurityHeader().getFirstChild() == null) { - secHeader.getSecurityHeader().appendChild(el); - } else { - secHeader.getSecurityHeader().insertBefore( - el, secHeader.getSecurityHeader().getFirstChild() - ); - } - } else { - insertAfter(el, topDownElement); - } - topDownElement = el; - } - - protected final Map getCryptoCache() { - EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo(); - synchronized (info) { - Map o = - CastUtils.cast((Map)message.getContextualProperty(CRYPTO_CACHE)); - if (o == null) { - o = CastUtils.cast((Map)info.getProperty(CRYPTO_CACHE)); - } - if (o == null) { - o = new ConcurrentHashMap(); - info.setProperty(CRYPTO_CACHE, o); - } - return o; - } - } - - protected final TokenStore getTokenStore() { - return WSS4JUtils.getTokenStore(message); - } - - protected WSSecTimestamp createTimestamp() { - if (binding.isIncludeTimestamp()) { - Object o = message.getContextualProperty(SecurityConstants.TIMESTAMP_TTL); - int ttl = 300; //default is 300 seconds - if (o instanceof Number) { - ttl = ((Number)o).intValue(); - } else if (o instanceof String) { - ttl = Integer.parseInt((String)o); - } - if (ttl <= 0) { - ttl = 300; - } - timestampEl = new WSSecTimestamp(wssConfig); - timestampEl.setTimeToLive(ttl); - timestampEl.prepare(saaj.getSOAPPart()); - - Collection ais = getAllAssertionsByLocalname(SPConstants.INCLUDE_TIMESTAMP); - for (AssertionInfo ai : ais) { - ai.setAsserted(true); - } - } - return timestampEl; - } - - protected WSSecTimestamp handleLayout(WSSecTimestamp timestamp) { - if (binding.getLayout() != null) { - Collection ais = getAllAssertionsByLocalname(SPConstants.LAYOUT); - AssertionInfo ai = null; - for (AssertionInfo layoutAi : ais) { - layoutAi.setAsserted(true); - ai = layoutAi; - } - - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_LAST + " requires a timestamp"); - } else { - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_LAST)); - Element el = timestamp.getElement(); - secHeader.getSecurityHeader().appendChild(el); - if (bottomUpElement == null) { - bottomUpElement = el; - } - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst) { - if (timestamp == null) { - ai.setNotAsserted(SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST + " requires a timestamp"); - } else { - addTopDownElement(timestampEl.getElement()); - ai.setAsserted(true); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), - SPConstants.LAYOUT_LAX_TIMESTAMP_FIRST)); - } - } else if (timestampEl != null) { - if (ai != null) { - ai.setAsserted(true); - } - addTopDownElement(timestampEl.getElement()); - } else if (ai != null) { - ai.setAsserted(true); - } - - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_LAX)); - assertPolicy( - new QName(binding.getLayout().getName().getNamespaceURI(), SPConstants.LAYOUT_STRICT)); - } else if (timestampEl != null) { - addTopDownElement(timestampEl.getElement()); - } - return timestamp; - } - - protected void reshuffleTimestamp() { - // Make sure that the Timestamp is in first place, if that is what the policy requires - if (binding.getLayout() != null && timestampEl != null) { - if (binding.getLayout().getLayoutType() == LayoutType.LaxTsFirst - && secHeader.getSecurityHeader().getFirstChild() != timestampEl.getElement()) { - Node firstChild = secHeader.getSecurityHeader().getFirstChild(); - while (firstChild != null && firstChild.getNodeType() != Node.ELEMENT_NODE) { - firstChild = firstChild.getNextSibling(); - } - if (firstChild != null && firstChild != timestampEl.getElement()) { - secHeader.getSecurityHeader().insertBefore(timestampEl.getElement(), firstChild); - } - } else if (binding.getLayout().getLayoutType() == LayoutType.LaxTsLast - && secHeader.getSecurityHeader().getLastChild() != timestampEl.getElement()) { - secHeader.getSecurityHeader().appendChild(timestampEl.getElement()); - } - } - } - - private List handleSupportingTokens( - Collection tokensInfos, - boolean endorse - ) throws WSSecurityException { - List ret = new ArrayList(); - if (tokensInfos != null) { - for (AssertionInfo assertionInfo : tokensInfos) { - if (assertionInfo.getAssertion() instanceof SupportingTokens) { - assertionInfo.setAsserted(true); - try { - handleSupportingTokens((SupportingTokens)assertionInfo.getAssertion(), endorse, ret); - } catch (SOAPException ex) { - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); - } - } - } - } - return ret; - } - - protected List handleSupportingTokens( - SupportingTokens suppTokens, - boolean endorse, - List ret - ) throws WSSecurityException, SOAPException { - if (suppTokens == null) { - return ret; - } - for (AbstractToken token : suppTokens.getTokens()) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - // Check for any SignedParts so as *not* to sign them - getSignedParts(suppTokens); - continue; - } - if (token instanceof UsernameToken) { - handleUsernameTokenSupportingToken( - (UsernameToken)token, endorse, suppTokens.isEncryptedToken(), ret - ); - } else if (token instanceof IssuedToken - || token instanceof SecureConversationToken - || token instanceof SecurityContextToken - || token instanceof KerberosToken - || token instanceof SpnegoContextToken) { - //ws-trust/ws-sc stuff....... - SecurityToken secToken = getSecurityToken(); - if (secToken == null) { - policyNotAsserted(token, "Could not find IssuedToken"); - } - Element clone = cloneElement(secToken.getToken()); - secToken.setToken(clone); - addSupportingElement(clone); - - String id = secToken.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(id, "Element"); - part.setElement(clone); - encryptedTokensList.add(part); - } - - if (secToken.getX509Certificate() == null) { - ret.add( - new SupportingToken(token, new WSSecurityTokenHolder(wssConfig, secToken), - getSignedParts(suppTokens)) - ); - } else { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setX509Certificate(secToken.getX509Certificate()); - sig.setCustomTokenId(id); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - String tokenType = secToken.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - - Crypto crypto = secToken.getCrypto(); - String uname = null; - try { - uname = crypto.getX509Identifier(secToken.getX509Certificate()); - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - - String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(uname, password); - try { - sig.prepare(saaj.getSOAPPart(), secToken.getCrypto(), secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - throw new Fault(e); - } - - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } - - } else if (token instanceof X509Token) { - //We have to use a cert. Prepare X509 signature - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - Element bstElem = sig.getBinarySecurityTokenElement(); - if (bstElem != null) { - if (lastEncryptedKeyElement != null) { - if (lastEncryptedKeyElement.getNextSibling() != null) { - secHeader.getSecurityHeader().insertBefore(bstElem, - lastEncryptedKeyElement.getNextSibling()); - } else { - secHeader.getSecurityHeader().appendChild(bstElem); - } - } else { - sig.prependBSTElementToHeader(secHeader); - } - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - part.setElement(bstElem); - encryptedTokensList.add(part); - } - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof KeyValueToken) { - WSSecSignature sig = getSignatureBuilder(token, false, endorse); - assertPolicy(suppTokens); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(sig.getBSTTokenId(), "Element"); - encryptedTokensList.add(part); - } - ret.add(new SupportingToken(token, sig, getSignedParts(suppTokens))); - } else if (token instanceof SamlToken) { - SamlAssertionWrapper assertionWrapper = addSamlToken((SamlToken)token); - if (assertionWrapper != null) { - Element assertionElement = assertionWrapper.toDOM(saaj.getSOAPPart()); - addSupportingElement(assertionElement); - ret.add(new SupportingToken(token, assertionWrapper, getSignedParts(suppTokens))); - if (suppTokens.isEncryptedToken()) { - WSEncryptionPart part = new WSEncryptionPart(assertionWrapper.getId(), "Element"); - part.setElement(assertionElement); - encryptedTokensList.add(part); - } - } - } - } - - return ret; - } - - protected void handleUsernameTokenSupportingToken( - UsernameToken token, boolean endorse, boolean encryptedToken, List ret - ) throws WSSecurityException { - if (endorse) { - WSSecUsernameToken utBuilder = addDKUsernameToken(token, true); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - if (encryptedToken) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } else { - WSSecUsernameToken utBuilder = addUsernameToken(token); - if (utBuilder != null) { - utBuilder.prepare(saaj.getSOAPPart()); - addSupportingElement(utBuilder.getUsernameTokenElement()); - ret.add(new SupportingToken(token, utBuilder, null)); - //WebLogic and WCF always encrypt these - //See: http://e-docs.bea.com/wls/docs103/webserv_intro/interop.html - //encryptedTokensIdList.add(utBuilder.getId()); - if (encryptedToken - || MessageUtils.getContextualBoolean(message, - SecurityConstants.ALWAYS_ENCRYPT_UT, - true)) { - WSEncryptionPart part = new WSEncryptionPart(utBuilder.getId(), "Element"); - part.setElement(utBuilder.getUsernameTokenElement()); - encryptedTokensList.add(part); - } - } - } - } - - protected Element cloneElement(Element el) { - Document doc = secHeader.getSecurityHeader().getOwnerDocument(); - if (!doc.equals(el.getOwnerDocument())) { - - XMLStreamReader reader = StaxUtils.createXMLStreamReader(el); - DocumentFragment fragment = doc.createDocumentFragment(); - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(fragment); - try { - StaxUtils.copy(reader, writer); - return (Element)fragment.getFirstChild(); - } catch (XMLStreamException ex) { - LOG.log(Level.FINE, "Error cloning security element", ex); - } - } - return el; - } - - protected void addSignatureParts(List tokenList, - List sigParts) { - - boolean useSTRTransform = - MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_STR_TRANSFORM, true - ); - - for (SupportingToken supportingToken : tokenList) { - - Object tempTok = supportingToken.getTokenImplementation(); - WSEncryptionPart part = null; - - if (tempTok instanceof WSSecSignature) { - WSSecSignature tempSig = (WSSecSignature) tempTok; - SecurityTokenReference secRef = tempSig.getSecurityTokenReference(); - - if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType()) - || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { - - Element secRefElement = cloneElement(secRef.getElement()); - addSupportingElement(secRefElement); - - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(tempSig.getSecurityTokenReferenceURI()); - part.setElement(secRefElement); - } else { - if (tempSig.getBSTTokenId() != null) { - part = new WSEncryptionPart(tempSig.getBSTTokenId()); - part.setElement(tempSig.getBinarySecurityTokenElement()); - } - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken unt = (WSSecUsernameToken)tempTok; - part = new WSEncryptionPart(unt.getId()); - part.setElement(unt.getUsernameTokenElement()); - } else if (tempTok instanceof BinarySecurity) { - BinarySecurity bst = (BinarySecurity)tempTok; - part = new WSEncryptionPart(bst.getID()); - part.setElement(bst.getElement()); - } else if (tempTok instanceof SamlAssertionWrapper) { - SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper)tempTok; - - Document doc = assertionWrapper.getElement().getOwnerDocument(); - boolean saml1 = assertionWrapper.getSaml1() != null; - if (useSTRTransform) { - // TODO We only support using a KeyIdentifier for the moment - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, assertionWrapper.getId(), saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(assertionWrapper.getId()); - part.setElement(assertionWrapper.getElement()); - } - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - String tokenType = token.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType) - || WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - Document doc = token.getToken().getOwnerDocument(); - boolean saml1 = WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType); - String id = token.getId(); - if (id == null || "".equals(id)) { - if (saml1) { - id = token.getToken().getAttributeNS(null, "AssertionID"); - } else { - id = token.getToken().getAttributeNS(null, "ID"); - } - } - if (useSTRTransform) { - SecurityTokenReference secRef = - createSTRForSamlAssertion(doc, id, saml1, false); - Element clone = cloneElement(secRef.getElement()); - addSupportingElement(clone); - part = new WSEncryptionPart("STRTransform", null, "Element"); - part.setId(secRef.getID()); - part.setElement(clone); - } else { - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - String id = token.getId(); - if (id != null && id.charAt(0) == '#') { - id = id.substring(1); - } - part = new WSEncryptionPart(id); - part.setElement(token.getToken()); - } - } else { - policyNotAsserted(supportingToken.getToken(), - "UnsupportedTokenInSupportingToken: " + tempTok); - } - if (part != null) { - sigParts.add(part); - } - } - } - - /** - * Create a SecurityTokenReference to point to a SAML Assertion - * @param doc The owner Document instance - * @param id The Assertion ID - * @param saml1 Whether the Assertion is a SAML1 or SAML2 Assertion - * @param useDirectReferenceToAssertion whether to refer directly to the assertion or not - * @return a SecurityTokenReference to a SAML Assertion - */ - private SecurityTokenReference createSTRForSamlAssertion( - Document doc, - String id, - boolean saml1, - boolean useDirectReferenceToAssertion - ) { - SecurityTokenReference secRefSaml = new SecurityTokenReference(doc); - String secRefID = wssConfig.getIdAllocator().createSecureId("STR-", secRefSaml); - secRefSaml.setID(secRefID); - - if (useDirectReferenceToAssertion) { - org.apache.wss4j.dom.message.token.Reference ref = - new org.apache.wss4j.dom.message.token.Reference(doc); - ref.setURI("#" + id); - if (saml1) { - ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - secRefSaml.setReference(ref); - } else { - Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); - String valueType = null; - if (saml1) { - valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } else { - valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE; - secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } - keyId.setAttributeNS( - null, "ValueType", valueType - ); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRefSaml.getElement(); - elem.appendChild(keyId); - } - return secRefSaml; - } - - protected WSSecUsernameToken addUsernameToken(UsernameToken token) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - // If NoPassword property is set we don't need to set the password - if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) { - utBuilder.setUserInfo(userName, null); - utBuilder.setPasswordType(null); - } else { - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) { - utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST); - } else { - utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT); - } - utBuilder.setUserInfo(userName, password); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - } - - if (token.isCreated() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addCreated(); - } - if (token.isNonce() && token.getPasswordType() != UsernameToken.PasswordType.HashPassword) { - utBuilder.addNonce(); - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected WSSecUsernameToken addDKUsernameToken(UsernameToken token, boolean useMac) { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - String userName = (String)message.getContextualProperty(SecurityConstants.USERNAME); - if (!StringUtils.isEmpty(userName)) { - WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); - - String password = (String)message.getContextualProperty(SecurityConstants.PASSWORD); - if (StringUtils.isEmpty(password)) { - password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN); - } - - if (!StringUtils.isEmpty(password)) { - // If the password is available then build the token - utBuilder.setUserInfo(userName, password); - utBuilder.addDerivedKey(useMac, null, 1000); - utBuilder.prepare(saaj.getSOAPPart()); - } else { - policyNotAsserted(token, "No password available"); - return null; - } - - return utBuilder; - } else { - policyNotAsserted(token, "No username available"); - return null; - } - } - - protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException { - assertToken(token); - if (!isTokenRequired(token.getIncludeTokenType())) { - return null; - } - - // - // Get the SAML CallbackHandler - // - Object o = message.getContextualProperty(SecurityConstants.SAML_CALLBACK_HANDLER); - - if (o == null) { - SecurityToken securityToken = getSecurityToken(); - if (securityToken != null) { - Element tokenElement = (Element)securityToken.getToken(); - String namespace = tokenElement.getNamespaceURI(); - String localname = tokenElement.getLocalName(); - SamlTokenType tokenType = token.getSamlTokenType(); - if ((tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) - && WSConstants.SAML_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } else if (tokenType == SamlTokenType.WssSamlV20Token11 - && WSConstants.SAML2_NS.equals(namespace) && "Assertion".equals(localname)) { - return new SamlAssertionWrapper(tokenElement); - } - } - } - - CallbackHandler handler = null; - if (o instanceof CallbackHandler) { - handler = (CallbackHandler)o; - } else if (o instanceof String) { - try { - handler = (CallbackHandler)ClassLoaderUtils - .loadClass((String)o, this.getClass()).newInstance(); - } catch (Exception e) { - handler = null; - } - } - if (handler == null) { - policyNotAsserted(token, "No SAML CallbackHandler available"); - return null; - } - - SAMLCallback samlCallback = new SAMLCallback(); - SamlTokenType tokenType = token.getSamlTokenType(); - if (tokenType == SamlTokenType.WssSamlV11Token10 || tokenType == SamlTokenType.WssSamlV11Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_11); - } else if (tokenType == SamlTokenType.WssSamlV20Token11) { - samlCallback.setSamlVersion(SAMLVersion.VERSION_20); - } - SAMLUtil.doSAMLCallback(handler, samlCallback); - SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback); - - if (samlCallback.isSignAssertion()) { - String issuerName = samlCallback.getIssuerKeyName(); - if (issuerName == null) { - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - issuerName = (String)message.getContextualProperty(userNameKey); - } - String password = samlCallback.getIssuerKeyPassword(); - if (password == null) { - password = getPassword(issuerName, token, WSPasswordCallback.SIGNATURE); - } - Crypto crypto = samlCallback.getIssuerCrypto(); - if (crypto == null) { - crypto = getSignatureCrypto(); - } - - assertion.signAssertion( - issuerName, - password, - crypto, - samlCallback.isSendKeyValue(), - samlCallback.getCanonicalizationAlgorithm(), - samlCallback.getSignatureAlgorithm(), - samlCallback.getSignatureDigestAlgorithm() - ); - } - - return assertion; - } - - /** - * Store a SAML Assertion as a SecurityToken - */ - protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) { - String id = findIDFromSamlToken(assertion.getElement()); - if (id == null) { - return; - } - SecurityToken secToken = new SecurityToken(id); - if (assertion.getSaml2() != null) { - secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); - } else { - secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); - } - secToken.setToken(assertion.getElement()); - getTokenStore().add(secToken); - message.put(SecurityConstants.TOKEN_ID, secToken.getId()); - } - - protected String findIDFromSamlToken(Element samlToken) { - String id = null; - if (samlToken != null) { - QName elName = DOMUtils.getElementQName(samlToken); - if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "AssertionID")) { - id = samlToken.getAttributeNS(null, "AssertionID"); - } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion")) - && samlToken.hasAttributeNS(null, "ID")) { - id = samlToken.getAttributeNS(null, "ID"); - } - if (id == null) { - id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id"); - } - } - return id; - } - - protected String getPassword(String userName, Assertion info, int usage) { - //Then try to get the password from the given callback handler - CallbackHandler handler = getCallbackHandler(); - if (handler == null) { - // Don't unassert for signature as we might get the password from the crypto properties - if (usage == WSPasswordCallback.SIGNATURE) { - LOG.info("No CallbackHandler available to retrieve a password. We will now try the crypto " - + "properties file for a private password"); - } else { - policyNotAsserted(info, "No callback handler and no password available"); - } - return null; - } - - WSPasswordCallback[] cb = {new WSPasswordCallback(userName, usage)}; - try { - handler.handle(cb); - } catch (Exception e) { - policyNotAsserted(info, e); - } - - //get the password - return cb[0].getPassword(); - } - - protected CallbackHandler getCallbackHandler() { - return WSS4JUtils.getCallbackHandler(message); - } - - /** - * Generates a wsu:Id attribute for the provided {@code Element} and returns the attribute value - * or finds and returns the value of the attribute if it already exists. - * - * @param element the {@code Element} to check/create the attribute on - * - * @return the generated or discovered wsu:Id attribute value - */ - public String addWsuIdToElement(Element elem) { - String id; - - //first try to get the Id attr - Attr idAttr = elem.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = elem.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - - if (idAttr != null) { - id = idAttr.getValue(); - } else { - //Add an id - id = wssConfig.getIdAllocator().createId("_", elem); - String pfx = null; - try { - pfx = elem.lookupPrefix(PolicyConstants.WSU_NAMESPACE_URI); - } catch (Throwable t) { - pfx = DOMUtils.getPrefixRecursive(elem, PolicyConstants.WSU_NAMESPACE_URI); - } - boolean found = !StringUtils.isEmpty(pfx); - int cnt = 0; - while (StringUtils.isEmpty(pfx)) { - pfx = "wsu" + (cnt == 0 ? "" : cnt); - - String ns; - try { - ns = elem.lookupNamespaceURI(pfx); - } catch (Throwable t) { - ns = DOMUtils.getNamespace(elem, pfx); - } - - if (!StringUtils.isEmpty(ns)) { - pfx = null; - cnt++; - } - } - if (!found) { - idAttr = elem.getOwnerDocument().createAttributeNS(WSDLConstants.NS_XMLNS, "xmlns:" + pfx); - idAttr.setValue(PolicyConstants.WSU_NAMESPACE_URI); - elem.setAttributeNodeNS(idAttr); - } - idAttr = elem.getOwnerDocument().createAttributeNS(PolicyConstants.WSU_NAMESPACE_URI, - pfx + ":Id"); - idAttr.setValue(id); - elem.setAttributeNodeNS(idAttr); - } - - return id; - } - - public List getEncryptedParts() - throws SOAPException { - - boolean isBody = false; - - EncryptedParts parts = null; - EncryptedElements elements = null; - ContentEncryptedElements celements = null; - - Collection ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - parts = (EncryptedParts)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - elements = (EncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - ais = getAllAssertionsByLocalname(SPConstants.CONTENT_ENCRYPTED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - celements = (ContentEncryptedElements)ai.getAssertion(); - ai.setAsserted(true); - } - } - - if (parts == null && elements == null && celements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String encModifier = "Element"; - if (MessageUtils.getContextualBoolean( - message, SecurityConstants.USE_ATTACHMENT_ENCRYPTION_CONTENT_ONLY_TRANSFORM, false)) { - encModifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", encModifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the encrypted list to prevent duplication / errors in encryption. - return getPartsAndElements(false, - isBody, - signedParts, - elements == null ? null : elements.getXPaths(), - celements == null ? null : celements.getXPaths()); - } - - public List getSignedParts(SupportingTokens supportingToken) - throws SOAPException { - - boolean isSignBody = false; - - SignedParts parts = null; - SignedElements elements = null; - - if (supportingToken != null && supportingToken.isEndorsing()) { - parts = supportingToken.getSignedParts(); - elements = supportingToken.getSignedElements(); - // Store them so that the main Signature doesn't sign them - if (parts != null) { - suppTokenParts.add(parts); - this.assertPolicy(parts.getName()); - } - if (elements != null) { - suppTokenParts.add(elements); - this.assertPolicy(elements.getName()); - } - } else { - Collection ais = getAllAssertionsByLocalname(SPConstants.SIGNED_PARTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedParts signedParts = (SignedParts)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedParts)) { - parts = signedParts; - } - } - } - - ais = getAllAssertionsByLocalname(SPConstants.SIGNED_ELEMENTS); - if (!ais.isEmpty()) { - for (AssertionInfo ai : ais) { - SignedElements signedElements = (SignedElements)ai.getAssertion(); - ai.setAsserted(true); - if (!suppTokenParts.contains(signedElements)) { - elements = signedElements; - } - } - } - } - - if (parts == null && elements == null) { - return new ArrayList(); - } - - List signedParts = new ArrayList(); - if (parts != null) { - isSignBody = parts.isBody(); - for (Header head : parts.getHeaders()) { - WSEncryptionPart wep = new WSEncryptionPart(head.getName(), - head.getNamespace(), - "Header"); - signedParts.add(wep); - } - Attachments attachments = parts.getAttachments(); - if (attachments != null) { - String modifier = "Element"; - if (attachments.isContentSignatureTransform()) { - modifier = "Content"; - } - WSEncryptionPart wep = new WSEncryptionPart("cid:Attachments", modifier); - signedParts.add(wep); - } - } - - // REVISIT consider catching exceptions and unassert failed assertions or - // to process and assert them one at a time. Additionally, a found list - // should be applied to all operations that involve adding anything to - // the signed list to prevent duplication in the signature. - return getPartsAndElements(true, - isSignBody, - signedParts, - elements == null ? null : elements.getXPaths(), - null); - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param contentXpaths - * any XPath expressions to content encrypt - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - * - * @deprecated Use {@link #getSignedParts()} and {@link #getEncryptedParts()} - * instead. - */ - public List getPartsAndElements(boolean sign, - boolean includeBody, - List parts, - List xpaths, - List contentXpaths) - throws SOAPException { - - List result = new ArrayList(); - - List found = new ArrayList(); - - // Handle sign/enc parts - result.addAll(this.getParts(sign, includeBody, parts, found)); - - // Handle sign/enc elements - result.addAll(this.getElements("Header", xpaths, found, sign)); - - if (!sign) { - // Handle content encrypted elements - result.addAll(this.getElements("Content", contentXpaths, found, sign)); - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param sign - * whether the matches are to be signed or encrypted - * @param includeBody - * if the body should be included in the signature/encryption - * @param parts - * any {@code WSEncryptionPart}s to match for signature or - * encryption as specified by WS-SP signed parts or encrypted - * parts. Parts without a name match all elements with the - * provided namespace. - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getParts(boolean sign, - boolean includeBody, List parts, - List found) throws SOAPException { - - List result = new ArrayList(); - - if (includeBody && !found.contains(SAAJUtils.getBody(this.saaj))) { - found.add(SAAJUtils.getBody(saaj)); - final String id = this.addWsuIdToElement(SAAJUtils.getBody(this.saaj)); - if (sign) { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Element"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } else { - WSEncryptionPart bodyPart = new WSEncryptionPart(id, "Content"); - bodyPart.setElement(SAAJUtils.getBody(this.saaj)); - result.add(bodyPart); - } - } - - final SOAPHeader header = SAAJUtils.getHeader(saaj); - - // Handle sign/enc parts - for (WSEncryptionPart part : parts) { - if (part.getId() != null && part.getId().startsWith("cid:")) { - // Attachments are handled inside WSS4J via a CallbackHandler - result.add(part); - continue; - } - final List elements; - - if (StringUtils.isEmpty(part.getName())) { - // An entire namespace - elements = - DOMUtils.getChildrenWithNamespace(header, part.getNamespace()); - } else { - // All elements with a given name and namespace - elements = - DOMUtils.getChildrenWithName(header, part.getNamespace(), part.getName()); - } - - for (Element el : elements) { - if (!found.contains(el)) { - found.add(el); - // Generate an ID for the element and use this ID or else - // WSS4J will only ever sign/encrypt the first matching - // element with the same name and namespace as that in the - // WSEncryptionPart - final String id = this.addWsuIdToElement(el); - WSEncryptionPart elPart = - new WSEncryptionPart(id, part.getEncModifier()); - elPart.setElement(el); - result.add(elPart); - } - } - } - - return result; - } - - /** - * Identifies the portions of the message to be signed/encrypted. - * - * @param encryptionModifier - * indicates the scope of the crypto operation over matched - * elements. Either "Content" or "Element". - * @param xpaths - * any XPath expressions to sign/encrypt matches - * @param found - * a list of elements that have previously been tagged for - * signing/encryption. Populated with additional matches found by - * this method and used to prevent including the same element - * twice under the same operation. - * @param forceId - * force adding a wsu:Id onto the elements. Recommended for signatures. - * @return a configured list of {@code WSEncryptionPart}s suitable for - * processing by WSS4J - * @throws XPathExpressionException - * if a provided XPath is invalid - * @throws SOAPException - * if there is an error extracting SOAP content from the SAAJ - * model - */ - protected List getElements(String encryptionModifier, - List xpaths, - List found, - boolean forceId) throws SOAPException { - - List result = new ArrayList(); - - if (xpaths != null && !xpaths.isEmpty()) { - XPathFactory factory = XPathFactory.newInstance(); - for (org.apache.wss4j.policy.model.XPath xPath : xpaths) { - XPath xpath = factory.newXPath(); - if (xPath.getPrefixNamespaceMap() != null) { - xpath.setNamespaceContext(new MapNamespaceContext(xPath.getPrefixNamespaceMap())); - } - - NodeList list = null; - try { - list = (NodeList)xpath.evaluate(xPath.getXPath(), saaj.getSOAPPart().getEnvelope(), - XPathConstants.NODESET); - } catch (XPathExpressionException e) { - LOG.log(Level.WARNING, "Failure in evaluating an XPath expression", e); - } - - if (list != null) { - for (int x = 0; x < list.getLength(); x++) { - Element el = (Element)list.item(x); - - if (!found.contains(el)) { - String id = setIdOnElement(el, forceId); - WSEncryptionPart part = - new WSEncryptionPart(id, encryptionModifier); - part.setElement(el); - part.setXpath(xPath.getXPath()); - - result.add(part); - } - } - } - } - } - - return result; - } - - private String setIdOnElement(Element element, boolean forceId) { - if (forceId) { - return this.addWsuIdToElement(element); - } - - //not forcing an ID on this. Use one if there is one - //there already, but don't force one - Attr idAttr = element.getAttributeNodeNS(null, "Id"); - if (idAttr == null) { - //then try the wsu:Id value - idAttr = element.getAttributeNodeNS(PolicyConstants.WSU_NAMESPACE_URI, "Id"); - } - if (idAttr != null) { - return idAttr.getValue(); - } - - return null; - } - - protected WSSecEncryptedKey getEncryptedKeyBuilder(AbstractToken token) throws WSSecurityException { - WSSecEncryptedKey encrKey = new WSSecEncryptedKey(wssConfig); - encrKey.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - encrKey.setStoreBytesInAttachment(storeBytesInAttachment); - Crypto crypto = getEncryptionCrypto(); - message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - setKeyIdentifierType(encrKey, token); - - boolean alsoIncludeToken = false; - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && encrKey.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE) { - alsoIncludeToken = true; - } - - String encrUser = setEncryptionUser(encrKey, token, false, crypto); - - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - encrKey.setSymmetricEncAlgorithm(algType.getEncryption()); - encrKey.setKeyEncAlgo(algType.getAsymmetricKeyWrap()); - - encrKey.prepare(saaj.getSOAPPart(), crypto); - - if (alsoIncludeToken) { - X509Certificate encCert = getEncryptCert(crypto, encrUser); - BinarySecurity bstToken = new X509Security(saaj.getSOAPPart()); - ((X509Security) bstToken).setX509Certificate(encCert); - bstToken.addWSUNamespace(); - bstToken.setID(wssConfig.getIdAllocator().createSecureId("X509-", encCert)); - WSSecurityUtil.prependChildElement( - secHeader.getSecurityHeader(), bstToken.getElement() - ); - bstElement = bstToken.getElement(); - } - - return encrKey; - } - - private X509Certificate getEncryptCert(Crypto crypto, String encrUser) throws WSSecurityException { - // Check for prepared encryption certificate - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - return encrCert; - } - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - return certs[0]; - } - - public Crypto getSignatureCrypto() throws WSSecurityException { - return getCrypto(SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES); - } - - public Crypto getEncryptionCrypto() throws WSSecurityException { - Crypto crypto = - getCrypto(SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES); - boolean enableRevocation = MessageUtils.isTrue( - message.getContextualProperty(SecurityConstants.ENABLE_REVOCATION)); - if (enableRevocation && crypto != null) { - CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); - String encrUser = (String)message.getContextualProperty(SecurityConstants.ENCRYPT_USERNAME); - if (encrUser == null) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - cryptoType.setAlias(encrUser); - X509Certificate[] certs = crypto.getX509Certificates(cryptoType); - if (certs != null && certs.length > 0) { - crypto.verifyTrust(certs, enableRevocation, null); - } - } - if (crypto != null) { - this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); - } - return crypto; - - } - - protected Crypto getCrypto( - String cryptoKey, - String propKey - ) throws WSSecurityException { - Crypto crypto = (Crypto)message.getContextualProperty(cryptoKey); - if (crypto != null) { - return crypto; - } - - Object o = message.getContextualProperty(propKey); - if (o == null) { - return null; - } - - crypto = getCryptoCache().get(o); - if (crypto != null) { - return crypto; - } - - ResourceManager manager = - message.getExchange().get(Bus.class).getExtension(ResourceManager.class); - URL propsURL = WSS4JUtils.getPropertiesFileURL(o, manager, this.getClass()); - Properties properties = WSS4JUtils.getProps(o, propsURL); - - if (properties != null) { - crypto = CryptoFactory.getInstance(properties, - Loader.getClassLoader(CryptoFactory.class), - WSS4JUtils.getPasswordEncryptor(message)); - getCryptoCache().put(o, crypto); - } - return crypto; - } - - public void setKeyIdentifierType(WSSecBase secBase, AbstractToken token) { - boolean tokenTypeSet = false; - - if (token instanceof X509Token) { - X509Token x509Token = (X509Token)token; - if (x509Token.isRequireIssuerSerialReference()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - tokenTypeSet = true; - } else if (x509Token.isRequireKeyIdentifierReference()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - tokenTypeSet = true; - } else if (x509Token.isRequireThumbprintReference()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - tokenTypeSet = true; - } - } else if (token instanceof KeyValueToken) { - secBase.setKeyIdentifierType(WSConstants.KEY_VALUE); - tokenTypeSet = true; - } - - assertToken(token); - - if (!tokenTypeSet) { - boolean requestor = isRequestor(); - if (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_NEVER - || token instanceof X509Token - && ((token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_RECIPIENT - && !requestor) - || (token.getIncludeTokenType() == IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_INITIATOR - && requestor))) { - Wss10 wss = getWss10(); - assertPolicy(wss); - if (wss == null || wss.isMustSupportRefKeyIdentifier()) { - secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER); - } else if (wss.isMustSupportRefIssuerSerial()) { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } else if (wss instanceof Wss11 && ((Wss11) wss).isMustSupportRefThumbprint()) { - secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); - } else { - secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); - } - } else { - secBase.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); - } - } - } - - public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, AbstractToken token, - boolean sign, Crypto crypto) { - // Check for prepared certificate property - X509Certificate encrCert = (X509Certificate)message.getContextualProperty(SecurityConstants.ENCRYPT_CERT); - if (encrCert != null) { - encrKeyBuilder.setUseThisCert(encrCert); - return null; - } - - String encrUser = (String)message.getContextualProperty(sign - ? SecurityConstants.SIGNATURE_USERNAME - : SecurityConstants.ENCRYPT_USERNAME); - if (crypto != null && (encrUser == null || "".equals(encrUser))) { - try { - encrUser = crypto.getDefaultX509Identifier(); - } catch (WSSecurityException e1) { - throw new Fault(e1); - } - } - if (encrUser == null || "".equals(encrUser)) { - policyNotAsserted(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared."); - } - if (WSHandlerConstants.USE_REQ_SIG_CERT.equals(encrUser)) { - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - if (results != null) { - encrKeyBuilder.setUseThisCert(WSS4JUtils.getReqSigCert(results)); - - //TODO This is a hack, this should not come under USE_REQ_SIG_CERT - if (encrKeyBuilder.isCertSet()) { - encrKeyBuilder.setUserInfo(getUsername(results)); - } - } else { - policyNotAsserted(token, "No security results in incoming message"); - } - } else { - encrKeyBuilder.setUserInfo(encrUser); - } - - return encrUser; - } - - /** - * Scan through WSHandlerResult list for a Username token and return - * the username if a Username Token found - * @param results - * @return - */ - public static String getUsername(List results) { - /* - * Scan the results for a matching actor. Use results only if the - * receiving Actor and the sending Actor match. - */ - for (WSHandlerResult rResult : results) { - List wsSecEngineResults = rResult.getResults(); - /* - * Scan the results for a username token. Use the username - * of this token to set the alias for the encryption user - */ - for (WSSecurityEngineResult wser : wsSecEngineResults) { - Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION); - if (actInt.intValue() == WSConstants.UT) { - UsernameTokenPrincipal principal - = (UsernameTokenPrincipal)wser.get(WSSecurityEngineResult.TAG_PRINCIPAL); - return principal.getName(); - } - } - } - - return null; - } - - private void checkForX509PkiPath(WSSecSignature sig, AbstractToken token) { - if (token instanceof X509Token) { - X509Token x509Token = (X509Token) token; - TokenType tokenType = x509Token.getTokenType(); - if (tokenType == TokenType.WssX509PkiPathV1Token10 - || tokenType == TokenType.WssX509PkiPathV1Token11) { - sig.setUseSingleCertificate(false); - } - } - } - - protected WSSecSignature getSignatureBuilder( - AbstractToken token, boolean attached, boolean endorse - ) throws WSSecurityException { - WSSecSignature sig = new WSSecSignature(wssConfig); - sig.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message)); - sig.setStoreBytesInAttachment(storeBytesInAttachment); - checkForX509PkiPath(sig, token); - if (token instanceof IssuedToken || token instanceof SamlToken) { - assertToken(token); - SecurityToken securityToken = getSecurityToken(); - String tokenType = securityToken.getTokenType(); - - Element ref; - if (attached) { - ref = securityToken.getAttachedReference(); - } else { - ref = securityToken.getUnattachedReference(); - } - - if (ref != null) { - - // DIGST WORKAROUND START - - // old code that is replaced - // SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - - // new code - String id = securityToken.getId(); - SecurityTokenReference secRef = null; - if ((id != null) && (id.equals("encryptedassertion"))) { - Document doc = ref.getOwnerDocument(); - secRef = new SecurityTokenReference(doc); - secRef.addTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"); - Element keyId = doc.createElementNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:KeyIdentifier"); - keyId.setAttributeNS(null, "ValueType", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID"); - keyId.appendChild(doc.createTextNode(id)); - Element elem = secRef.getElement(); - elem.appendChild(keyId); - } - else { - secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer()); - } - - // DIGST WORKAROUND END - - sig.setSecurityTokenReference(secRef); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - int type = attached ? WSConstants.CUSTOM_SYMM_SIGNING - : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT; - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER); - } else { - sig.setCustomTokenValueType(tokenType); - sig.setKeyIdentifierType(type); - } - } - - String sigTokId; - if (attached) { - sigTokId = securityToken.getWsuId(); - if (sigTokId == null) { - sigTokId = securityToken.getId(); - } - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - } else { - sigTokId = securityToken.getId(); - } - - sig.setCustomTokenId(sigTokId); - } else { - setKeyIdentifierType(sig, token); - // Find out do we also need to include the token as per the Inclusion requirement - if (token instanceof X509Token - && token.getIncludeTokenType() != IncludeTokenType.INCLUDE_TOKEN_NEVER - && (sig.getKeyIdentifierType() != WSConstants.BST_DIRECT_REFERENCE - && sig.getKeyIdentifierType() != WSConstants.KEY_VALUE)) { - sig.setIncludeSignatureToken(true); - } - } - - boolean encryptCrypto = false; - String userNameKey = SecurityConstants.SIGNATURE_USERNAME; - String type = "signature"; - if (binding instanceof SymmetricBinding && !endorse) { - encryptCrypto = ((SymmetricBinding)binding).getProtectionToken() != null; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - } - - Crypto crypto = encryptCrypto ? getEncryptionCrypto() : getSignatureCrypto(); - - if (endorse && crypto == null && binding instanceof SymmetricBinding) { - type = "encryption"; - userNameKey = SecurityConstants.ENCRYPT_USERNAME; - crypto = getEncryptionCrypto(); - } - - if (!encryptCrypto) { - message.getExchange().put(SecurityConstants.SIGNATURE_CRYPTO, crypto); - } - String user = (String)message.getContextualProperty(userNameKey); - if (StringUtils.isEmpty(user)) { - if (crypto != null) { - try { - user = crypto.getDefaultX509Identifier(); - if (StringUtils.isEmpty(user)) { - policyNotAsserted(token, "No configured " + type + " username detected"); - return null; - } - } catch (WSSecurityException e1) { - LOG.log(Level.FINE, e1.getMessage(), e1); - throw new Fault(e1); - } - } else { - policyNotAsserted(token, "Security configuration could not be detected. " - + "Potential cause: Make sure jaxws:client element with name " - + "attribute value matching endpoint port is defined as well as a " - + SecurityConstants.SIGNATURE_PROPERTIES + " element within it."); - return null; - } - } - - String password = getPassword(user, token, WSPasswordCallback.SIGNATURE); - sig.setUserInfo(user, password); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.setWsConfig(wssConfig); - try { - sig.prepare(saaj.getSOAPPart(), crypto, secHeader); - } catch (WSSecurityException e) { - LOG.log(Level.FINE, e.getMessage(), e); - policyNotAsserted(token, e); - } - - return sig; - } - - protected void doEndorsedSignatures(List tokenList, - boolean isTokenProtection, - boolean isSigProtect) { - - for (SupportingToken supportingToken : tokenList) { - Object tempTok = supportingToken.getTokenImplementation(); - - List sigParts = new ArrayList(); - WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId); - sigPart.setElement(bottomUpElement); - sigParts.add(sigPart); - - if (supportingToken.getSignedParts() != null) { - for (WSEncryptionPart signedPart : supportingToken.getSignedParts()) { - sigParts.add(signedPart); - } - } - - if (tempTok instanceof WSSecSignature) { - WSSecSignature sig = (WSSecSignature)tempTok; - if (isTokenProtection && sig.getBSTTokenId() != null) { - WSEncryptionPart bstPart = - new WSEncryptionPart(sig.getBSTTokenId()); - bstPart.setElement(sig.getBinarySecurityTokenElement()); - sigParts.add(bstPart); - } - try { - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - sig.computeSignature(referenceList, false, null); - - signatures.add(sig.getSignatureValue()); - if (isSigProtect) { - WSEncryptionPart part = new WSEncryptionPart(sig.getId(), "Element"); - encryptedTokensList.add(part); - } - } catch (WSSecurityException e) { - policyNotAsserted(supportingToken.getToken(), e); - } - - } else if (tempTok instanceof WSSecurityTokenHolder) { - SecurityToken token = ((WSSecurityTokenHolder)tempTok).getToken(); - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(token.getId())); - } - - try { - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), token, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), token, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - } else if (tempTok instanceof WSSecUsernameToken) { - WSSecUsernameToken utBuilder = (WSSecUsernameToken)tempTok; - String id = utBuilder.getId(); - - Date created = new Date(); - Date expires = new Date(); - expires.setTime(created.getTime() + 300000); - SecurityToken secToken = - new SecurityToken(id, utBuilder.getUsernameTokenElement(), created, expires); - - if (isTokenProtection) { - sigParts.add(new WSEncryptionPart(secToken.getId())); - } - - try { - byte[] secret = utBuilder.getDerivedKey(); - secToken.setSecret(secret); - - if (supportingToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - doSymmSignatureDerived(supportingToken.getToken(), secToken, sigParts, - isTokenProtection); - } else { - doSymmSignature(supportingToken.getToken(), secToken, sigParts, isTokenProtection); - } - } catch (Exception e) { - LOG.log(Level.FINE, e.getMessage(), e); - } - - } - } - } - - private void doSymmSignatureDerived(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecDKSign dkSign = new WSSecDKSign(wssConfig); - - //Check whether it is security policy 1.2 and use the secure conversation accordingly - if (policyToken.getVersion() == SPConstants.SPVersion.SP11) { - dkSign.setWscVersion(ConversationConstants.VERSION_05_02); - } - - //Check for whether the token is attached in the message or not - boolean attached = false; - if (isTokenRequired(policyToken.getIncludeTokenType())) { - attached = true; - } - - // Setting the AttachedReference or the UnattachedReference according to the flag - Element ref; - if (attached) { - ref = tok.getAttachedReference(); - } else { - ref = tok.getUnattachedReference(); - } - - if (ref != null) { - ref = cloneElement(ref); - dkSign.setExternalKey(tok.getSecret(), ref); - } else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { - // If the Encrypted key used to create the derived key is not - // attached use key identifier as defined in WSS1.1 section - // 7.7 Encrypted Key reference - SecurityTokenReference tokenRef - = new SecurityTokenReference(doc); - if (tok.getSHA1() != null) { - tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1()); - tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE); - } - dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement()); - - } else { - dkSign.setExternalKey(tok.getSecret(), tok.getId()); - } - - //Set the algo info - dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - dkSign.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8); - if (tok.getSHA1() != null) { - //Set the value type of the reference - dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#" - + WSConstants.ENC_KEY_VALUE_TYPE); - } else if (policyToken instanceof UsernameToken) { - dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } - - dkSign.prepare(doc, secHeader); - - if (isTokenProtection) { - //Hack to handle reference id issues - //TODO Need a better fix - String sigTokId = tok.getId(); - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - sigParts.add(new WSEncryptionPart(sigTokId)); - } - - dkSign.setParts(sigParts); - - List referenceList = dkSign.addReferencesToSign(sigParts, secHeader); - - //Add elements to header - addSupportingElement(dkSign.getdktElement()); - - //Do signature - dkSign.computeSignature(referenceList, false, null); - - signatures.add(dkSign.getSignatureValue()); - } - - private void doSymmSignature(AbstractToken policyToken, SecurityToken tok, - List sigParts, boolean isTokenProtection) - throws WSSecurityException { - - Document doc = saaj.getSOAPPart(); - WSSecSignature sig = new WSSecSignature(wssConfig); - // If a EncryptedKeyToken is used, set the correct value type to - // be used in the wsse:Reference in ds:KeyInfo - if (policyToken instanceof X509Token) { - if (isRequestor()) { - // TODO Add support for SAML2 here - sig.setCustomTokenValueType( - WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE - ); - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } else { - //the tok has to be an EncryptedKey token - sig.setEncrKeySha1value(tok.getSHA1()); - sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); - } - - } else { - String tokenType = tok.getTokenType(); - if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) - || WSConstants.SAML2_NS.equals(tokenType)) { - sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE); - } else if (tokenType != null) { - sig.setCustomTokenValueType(tokenType); - } else if (policyToken instanceof UsernameToken) { - sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE); - } else { - sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); - } - sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING); - } - - String sigTokId = tok.getWsuId(); - if (sigTokId == null) { - sigTokId = tok.getId(); - } - - //Hack to handle reference id issues - //TODO Need a better fix - if (sigTokId.startsWith("#")) { - sigTokId = sigTokId.substring(1); - } - - sig.setCustomTokenId(sigTokId); - sig.setSecretKey(tok.getSecret()); - sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature()); - AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType(); - sig.setDigestAlgo(algType.getDigest()); - sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue()); - sig.prepare(doc, getSignatureCrypto(), secHeader); - - sig.setParts(sigParts); - List referenceList = sig.addReferencesToSign(sigParts, secHeader); - - //Do signature - sig.computeSignature(referenceList, false, null); - signatures.add(sig.getSignatureValue()); - } - - protected void addSupportingTokens(List sigs) throws WSSecurityException { - Collection sgndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_SUPPORTING_TOKENS); - List sigSuppTokList = this.handleSupportingTokens(sgndSuppTokens, false); - - Collection endSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_SUPPORTING_TOKENS); - endSuppTokList = this.handleSupportingTokens(endSuppTokens, true); - - Collection sgndEndSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_SUPPORTING_TOKENS); - sgndEndSuppTokList = this.handleSupportingTokens(sgndEndSuppTokens, true); - - Collection sgndEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENCRYPTED_SUPPORTING_TOKENS); - List sgndEncSuppTokList - = this.handleSupportingTokens(sgndEncryptedSuppTokens, false); - - Collection endorsingEncryptedSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - endSuppTokList.addAll(this.handleSupportingTokens(endorsingEncryptedSuppTokens, true)); - - Collection sgndEndEncSuppTokens = - getAllAssertionsByLocalname(aim, SPConstants.SIGNED_ENDORSING_ENCRYPTED_SUPPORTING_TOKENS); - sgndEndSuppTokList.addAll(this.handleSupportingTokens(sgndEndEncSuppTokens, true)); - - Collection supportingToks = - getAllAssertionsByLocalname(aim, SPConstants.SUPPORTING_TOKENS); - this.handleSupportingTokens(supportingToks, false); - - Collection encryptedSupportingToks = - getAllAssertionsByLocalname(aim, SPConstants.ENCRYPTED_SUPPORTING_TOKENS); - this.handleSupportingTokens(encryptedSupportingToks, false); - - //Setup signature parts - addSignatureParts(sigSuppTokList, sigs); - addSignatureParts(sgndEncSuppTokList, sigs); - addSignatureParts(sgndEndSuppTokList, sigs); - } - - protected void doEndorse() { - boolean tokenProtect = false; - boolean sigProtect = false; - if (binding instanceof AsymmetricBinding) { - tokenProtect = ((AsymmetricBinding)binding).isProtectTokens(); - sigProtect = ((AsymmetricBinding)binding).isEncryptSignature(); - } else if (binding instanceof SymmetricBinding) { - tokenProtect = ((SymmetricBinding)binding).isProtectTokens(); - sigProtect = ((SymmetricBinding)binding).isEncryptSignature(); - } - // Do endorsed signatures - doEndorsedSignatures(endSuppTokList, tokenProtect, sigProtect); - - // Do signed endorsing signatures - doEndorsedSignatures(sgndEndSuppTokList, tokenProtect, sigProtect); - } - - protected void addSignatureConfirmation(List sigParts) { - Wss10 wss10 = getWss10(); - - if (!(wss10 instanceof Wss11) - || !((Wss11)wss10).isRequireSignatureConfirmation()) { - //If we don't require sig confirmation simply go back :-) - return; - } - - List results = - CastUtils.cast((List) - message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); - /* - * loop over all results gathered by all handlers in the chain. For each - * handler result get the various actions. After that loop we have all - * signature results in the signatureActions list - */ - List signatureActions = new ArrayList(); - final List signedActions = new ArrayList(2); - signedActions.add(WSConstants.SIGN); - signedActions.add(WSConstants.UT_SIGN); - for (WSHandlerResult wshResult : results) { - signatureActions.addAll( - WSSecurityUtil.fetchAllActionResults(wshResult.getResults(), signedActions) - ); - } - - sigConfList = new ArrayList(); - // prepare a SignatureConfirmation token - WSSecSignatureConfirmation wsc = new WSSecSignatureConfirmation(wssConfig); - if (signatureActions.size() > 0) { - for (WSSecurityEngineResult wsr : signatureActions) { - byte[] sigVal = (byte[]) wsr.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE); - wsc.setSignatureValue(sigVal); - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - } else { - //No Sig value - wsc.prepare(saaj.getSOAPPart()); - addSupportingElement(wsc.getSignatureConfirmationElement()); - if (sigParts != null) { - WSEncryptionPart part = new WSEncryptionPart(wsc.getId(), "Element"); - part.setElement(wsc.getSignatureConfirmationElement()); - sigParts.add(part); - sigConfList.add(part); - } - } - - assertPolicy( - new QName(wss10.getName().getNamespaceURI(), SPConstants.REQUIRE_SIGNATURE_CONFIRMATION)); - } - - /** - * Processes the parts to be signed and reconfigures those parts that have - * already been encrypted. - * - * @param encryptedParts - * the parts that have been encrypted - * @param signedParts - * the parts that are to be signed - * - * @throws IllegalArgumentException - * if an element in {@code signedParts} contains a {@code - * WSEncryptionPart} with a {@code null} {@code id} value - * and the {@code WSEncryptionPart} {@code name} value is not - * "Token" - */ - public void handleEncryptedSignedHeaders(List encryptedParts, - List signedParts) { - - final List signedEncryptedParts = new ArrayList(); - - for (WSEncryptionPart encryptedPart : encryptedParts) { - final Iterator signedPartsIt = signedParts.iterator(); - while (signedPartsIt.hasNext()) { - WSEncryptionPart signedPart = signedPartsIt.next(); - // Everything has to be ID based except for the case of a part - // indicating "Token" as the element name. This name is a flag - // for WSS4J to sign the initiator token used in the signature. - // Since the encryption happened before the signature creation, - // this element can't possibly be encrypted so we can safely ignore - // if it were ever to be set before this method is called. - if (signedPart.getId() == null && !"Token".equals(signedPart.getName())) { - throw new IllegalArgumentException( - "WSEncryptionPart must be ID based but no id was found."); - } else if (encryptedPart.getEncModifier().equals("Header") - && signedPart.getId().equals(encryptedPart.getId())) { - // We are to sign something that has already been encrypted. - // We need to preserve the original aspects of signedPart but - // change the ID to the encrypted ID. - - signedPartsIt.remove(); - WSEncryptionPart part = new WSEncryptionPart( - encryptedPart.getEncId(), - encryptedPart.getEncModifier()); - part.setElement(encryptedPart.getElement()); - signedEncryptedParts.add(part); - } - } - } - - signedParts.addAll(signedEncryptedParts); - } - - /** - * Convert a DOM Element into a WSEncryptionPart, adding a (wsu:)Id if there is not - * one already. - * @param element The DOM Element to convert - * @return The WSEncryptionPart representing the DOM Element argument - */ - public WSEncryptionPart convertToEncryptionPart(Element element) { - String id = addWsuIdToElement(element); - WSEncryptionPart part = new WSEncryptionPart(id); - part.setElement(element); - return part; - } - - static class SupportingToken { - private final AbstractToken token; - private final Object tokenImplementation; - private final List signedParts; - - public SupportingToken(AbstractToken token, Object tokenImplementation, - List signedParts) { - this.token = token; - this.tokenImplementation = tokenImplementation; - this.signedParts = signedParts; - } - - public AbstractToken getToken() { - return token; - } - - public Object getTokenImplementation() { - return tokenImplementation; - } - - public List getSignedParts() { - return signedParts; - } - - } -} diff --git a/examples/lbsb/system-user-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java b/examples/lbsb/system-user-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java deleted file mode 100644 index 96cb070..0000000 --- a/examples/lbsb/system-user-scenario/src/main/java/org/apache/wss4j/dom/transform/STRTransform.java +++ /dev/null @@ -1,281 +0,0 @@ -// NOTE!!! -// -// This is a copy of STRTransform.java found in wss4j-ws-security-dom version 2.0.10, -// which matches CXF version 3.0.16. -// -// There is a single modification to this class (compared to the original version), -// found in the transformIt() method below. It has been clearly marked as -// a workaround - and the code can likely be adapted to other versions of CXF/WSS4J -// -// The change is required when using the NemLog-in STS, as it returns an EncryptedAssertion -// element with an embedded EncryptedData element. The EncryptedData element has the ID -// referenced by the RAR in the RequestSecurityTokenResponse, but we need to dereference -// the parent element for this to work - -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.wss4j.dom.transform; - -import org.apache.wss4j.dom.WSConstants; -import org.apache.wss4j.dom.WSDocInfo; -import org.apache.wss4j.dom.bsp.BSPEnforcer; -import org.apache.wss4j.dom.message.token.PKIPathSecurity; -import org.apache.wss4j.dom.message.token.SecurityTokenReference; -import org.apache.wss4j.dom.message.token.X509Security; -import org.apache.wss4j.dom.util.WSSecurityUtil; - -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignatureInput; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import java.io.ByteArrayInputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Iterator; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.NodeSetData; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; - - -/** - * Class STRTransform. - */ -public class STRTransform extends TransformService { - - public static final String TRANSFORM_URI = - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform"; - - public static final String TRANSFORM_WS_DOC_INFO = "transform_ws_doc_info"; - - private TransformParameterSpec params; - - private Element transformElement; - - private static final org.slf4j.Logger LOG = - org.slf4j.LoggerFactory.getLogger(STRTransform.class); - - public final AlgorithmParameterSpec getParameterSpec() { - return params; - } - - public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { - this.params = params; - } - - public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - transformElement = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - } - - public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - if (context != null && !(context instanceof DOMCryptoContext)) { - throw new ClassCastException - ("context must be of type DOMCryptoContext"); - } - if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { - throw new ClassCastException("parent must be of type DOMStructure"); - } - Element transformElement2 = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); - appendChild(transformElement2, transformElement); - transformElement = transformElement2; - } - - - public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - return transformIt(data, xc, null); - } - - public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - if (data == null) { - throw new NullPointerException("data must not be null"); - } - if (os == null) { - throw new NullPointerException("output stream must not be null"); - } - return transformIt(data, xc, os); - } - - - private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - - // - // First step: Get the required c14n argument and get the specified - // Canonicalizer - // - String canonAlgo = null; - Element transformParams = WSSecurityUtil.getDirectChildElement( - transformElement, "TransformationParameters", WSConstants.WSSE_NS - ); - if (transformParams != null) { - Element canonElem = - WSSecurityUtil.getDirectChildElement( - transformParams, "CanonicalizationMethod", WSConstants.SIG_NS - ); - canonAlgo = canonElem.getAttributeNS(null, "Algorithm"); - } - try { - // - // Get the input (node) to transform. - // - Element str = null; - if (data instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)data; - Iterator iterator = nodeSetData.iterator(); - while (iterator.hasNext()) { - Node node = (Node)iterator.next(); - if (node instanceof Element && "SecurityTokenReference".equals(node.getLocalName())) { - str = (Element)node; - break; - } - } - } else { - try { - XMLSignatureInput xmlSignatureInput = - new XMLSignatureInput(((OctetStreamData)data).getOctetStream()); - str = (Element)xmlSignatureInput.getSubNode(); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - if (str == null) { - throw new TransformException("No SecurityTokenReference found"); - } - // - // The element to transform MUST be a SecurityTokenReference - // element. - // - SecurityTokenReference secRef = new SecurityTokenReference(str, new BSPEnforcer()); - - Canonicalizer canon = Canonicalizer.getInstance(canonAlgo); - - byte[] buf = null; - - // - // Third and fourth step are performed by dereferenceSTR() - // - Object wsDocInfoObject = xc.getProperty(TRANSFORM_WS_DOC_INFO); - WSDocInfo wsDocInfo = null; - if (wsDocInfoObject instanceof WSDocInfo) { - wsDocInfo = (WSDocInfo)wsDocInfoObject; - } - if (wsDocInfo == null) { - LOG.debug("STRTransform: no WSDocInfo found"); - } - - Document doc = str.getOwnerDocument(); - Element dereferencedToken = - STRTransformUtil.dereferenceSTR(doc, secRef, wsDocInfo); - - if (dereferencedToken != null) { - String type = dereferencedToken.getAttributeNS(null, "ValueType"); - if (X509Security.X509_V3_TYPE.equals(type) - || PKIPathSecurity.getType().equals(type)) { - // - // Add the WSSE/WSU namespaces to the element for C14n - // - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX - ); - WSSecurityUtil.setNamespace( - dereferencedToken, WSConstants.WSU_NS, WSConstants.WSU_PREFIX - ); - } - } - - // BEGIN DIGST WORKAROUND - boolean parentNodeIsNull = (dereferencedToken.getParentNode() == null); - boolean encryptedAssertionId = (dereferencedToken.getAttribute("wsu:Id") != null && dereferencedToken.getAttribute("wsu:Id").equals("encryptedassertion")); - - if (!parentNodeIsNull && encryptedAssertionId) { - dereferencedToken = (Element) dereferencedToken.getParentNode(); - } - // END DIGST WORKAROUND - - // - // C14n with specified algorithm. According to WSS Specification. - // - buf = canon.canonicalizeSubtree(dereferencedToken, "#default", true); - if (LOG.isDebugEnabled()) { - LOG.debug("after c14n: " + new String(buf, "UTF-8")); - } - - if (os != null) { - os.write(buf); - return null; - } - return new OctetStreamData(new ByteArrayInputStream(buf)); - } catch (Exception ex) { - throw new TransformException(ex); - } - } - - - public final boolean isFeatureSupported(String feature) { - if (feature == null) { - throw new NullPointerException(); - } else { - return false; - } - } - - private static void appendChild(Node parent, Node child) { - Document ownerDoc = null; - if (parent.getNodeType() == Node.DOCUMENT_NODE) { - ownerDoc = (Document)parent; - } else { - ownerDoc = parent.getOwnerDocument(); - } - if (child.getOwnerDocument() != ownerDoc) { - parent.appendChild(ownerDoc.importNode(child, true)); - } else { - parent.appendChild(child); - } - } - -} diff --git a/examples/lbsb/system-user-scenario/src/main/resources/HelloWorld-Hok.wsdl b/examples/lbsb/system-user-scenario/src/main/resources/HelloWorld-Hok.wsdl deleted file mode 100644 index 75b24aa..0000000 --- a/examples/lbsb/system-user-scenario/src/main/resources/HelloWorld-Hok.wsdl +++ /dev/null @@ -1,182 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/system-user-scenario/src/main/resources/client.pfx b/examples/lbsb/system-user-scenario/src/main/resources/client.pfx deleted file mode 100644 index f6ed4ce..0000000 Binary files a/examples/lbsb/system-user-scenario/src/main/resources/client.pfx and /dev/null differ diff --git a/examples/lbsb/system-user-scenario/src/main/resources/client.properties b/examples/lbsb/system-user-scenario/src/main/resources/client.properties deleted file mode 100644 index 09a24f1..0000000 --- a/examples/lbsb/system-user-scenario/src/main/resources/client.properties +++ /dev/null @@ -1,8 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=pkcs12 -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=java ref. test (funktionscertifikat) -org.apache.ws.security.crypto.merlin.file=client.pfx - -org.apache.ws.security.crypto.merlin.truststore.type=jks -org.apache.ws.security.crypto.merlin.truststore.file=trust.jks -org.apache.ws.security.crypto.merlin.truststore.password=Test1234 diff --git a/examples/lbsb/system-user-scenario/src/main/resources/cxf.xml b/examples/lbsb/system-user-scenario/src/main/resources/cxf.xml deleted file mode 100644 index 7615767..0000000 --- a/examples/lbsb/system-user-scenario/src/main/resources/cxf.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/system-user-scenario/src/main/resources/sts.properties b/examples/lbsb/system-user-scenario/src/main/resources/sts.properties deleted file mode 100644 index 8af9ada..0000000 --- a/examples/lbsb/system-user-scenario/src/main/resources/sts.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.apache.ws.security.crypto.merlin.keystore.type=jks -org.apache.ws.security.crypto.merlin.keystore.password=Test1234 -org.apache.ws.security.crypto.merlin.keystore.alias=sts -org.apache.ws.security.crypto.merlin.file=trust.jks diff --git a/examples/lbsb/system-user-scenario/src/main/resources/sts.wsdl b/examples/lbsb/system-user-scenario/src/main/resources/sts.wsdl deleted file mode 100644 index 367a5ec..0000000 --- a/examples/lbsb/system-user-scenario/src/main/resources/sts.wsdl +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/lbsb/system-user-scenario/src/main/resources/trust.jks b/examples/lbsb/system-user-scenario/src/main/resources/trust.jks deleted file mode 100644 index 74dedb8..0000000 Binary files a/examples/lbsb/system-user-scenario/src/main/resources/trust.jks and /dev/null differ diff --git a/examples/pom.xml b/examples/pom.xml index 9e93680..381b916 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -97,7 +97,6 @@ - lbsb oio-idws-soap oio-idws-rest