SHYAM RAO

Monday Aug 11, 2008

Example Tutorial to write advance WS-Trust applications

On 6th August, Sun has released Metro1.3

Here is the example tutorial for developing advanced WS-Trust application. The direct links of advanced example applications are as follow :

Example: Broker Trust STS (BT)

Example: STS Issued Token With SecureConversation (STS+SC)

How to use Key and Encryption Requirements in WS-Trust application using Metro ?

This blog is on how to put additional "Key and Encryption Requirements" in the issued key from SecurityTokenService (STS) for a WS-Trust application using Metro.

Here is the details of Key and Encryption Requirements for a issued key :

SignWith : This optional URI element indicates the desired signature algorithm to be used with the issued security token (typically from the policy of the target site for which the token is being requested.

EncryptWith : This optional URI element indicates the desired encryption algorithm to be used with the issued security token (typically from the policy of the target site for which the token is being requested.) 

SignatureAlgorithm : This optional URI element indicates the desired signature algorithm used within the returned token.  This is specified as a URI indicating the algorithm (see [XML-Signature] for typical signing algorithms).

EncryptionAlgorithm : This optional URI element indicates the desired encryption algorithm used within the returned token.  This is specified as a URI indicating the algorithm (see [XML-Encrypt] for typical encryption algorithms).

CanonicalizationAlgorithm : This optional URI element indicates the desired canonicalization method used within the returned token.  This is specified as a URI indicating the method (see [XML-Signature] for typical canonicalization methods).

KeyWrapAlgorithm : This optional URI element indicates the desired algorithm to use for key wrapping when STS encrypts the issued token for the relying party using an asymmetric key.

This is how you can define the above Key and Encryption Requirements under RequestSecurityTokenTemplate assertion in the service wsdl.

<sp:RequestSecurityTokenTemplate xmlns:t="http://docs.oasis-open.org/ws-sx/ws-trust/200512"> 
        <t:CanonicalizationAlgorithm>http://www.w3.org/2001/10/xml-exc-c14n#</t:CanonicalizationAlgorithm>
        <t:EncryptionAlgorithm>http://www.w3.org/2001/04/xmlenc#aes256-cbc</t:EncryptionAlgorithm>
        <t:SignatureAlgorithm>http://www.w3.org/2000/09/xmldsig#hmac-sha1</t:SignatureAlgorithm>
        <t:EncryptWith>http://www.w3.org/2001/04/xmlenc#aes256-cbc</t:EncryptWith>
        <t:SignWith>http://www.w3.org/2000/09/xmldsig#hmac-sha1</t:SignWith>
        <t:KeyWrapAlgorithm>http://www.w3.org/2001/04/xmlenc#aes256-cbc</t:KeyWrapAlgorithm>
</sp:RequestSecurityTokenTemplate>

Wednesday Jul 23, 2008

How to implement SAMLAssertionValidator for custom validation of SAML Assetion ?

Metro Forum users were asking for custom validation of SAML Token on server side. This blog gives you the idea 
on how to archive the said title.
For custom validation of the SAML Token on server side, user must implement SAMLAssertionValidator interface.
To enable the custom validator, the following ValidatorConfiguration element has to be put in the service wsdl. 
The format of defining Validator Configurations in the service wsdl is :
<sc:ValidatorConfiguration wspp:visibility="private">
    <sc:Validator name="samlAssertionValidator" classname = {class name of a SAML Assertion Validator, should implement com.sun.xml.wss.impl.callback.SAMLAssertionValidator, Partial validation (in the form of verifying enveloped signature) occurs on SAML Assertion within  the WSIT/XWSS 3.0 Runtime even if the validator is not specified} />
</sc:ValidatorConfiguration>

In the custom validator, the following two method of  SAMLAssertionValidator interface has to be implemented.
1) public void validate(Element domAssertion) throws SAMLValidationException;
2) public void validate(XMLStreamReader streamAssertion) throws SAMLValidationException;

Only difference between the above two methods is : first method takes SAML assertion of type DOM element as 
argument and second method takes SAML Assertion of type XMLStreamReader.
Note : By default, streaming security is enabled in Metro security runtime, which calls the validate method with 
SAML assertion of type XMLStreamReader as argument. 

In the implementation of second validate method, we need to create a saml assertion of type DOM element from 
saml assertion of type XMLStreamReader. 
For this, use the static method createSAMLAssertion(XMLStreamReader streamAssertion) of class SAMLUtil.
Element domSamlAssertion = SAMLUtil.createSAMLAssertion(streamAssertion);

Then, create SAML assertion object of type com.sun.xml.wss.saml.Assertion  from the above domSamlAssertion 
element. 
Here is the code snippet in bold on how to create a SAML assertion object from DOM element :
String samlVer = null;
if (samlAssertion.getNamespaceURI().equals("urn:oasis:names:tc:SAML:1.0:assertion")) {    
    samlVer = SAMLAssertionFactory.SAML1_1;
} else if (samlAssertion.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {    
    samlVer = SAMLAssertionFactory.SAML2_0;
}
SAMLAssertionFactory samlAsserFac = SAMLAssertionFactory.newInstance(samlVer);
Assertion assertion = samlAsserFac.createAssertion(domSamlAssertion);

You can refer to com.sun.xml.wss.saml.Assertion api to know all methods available in it.

For example : to get the conditions values of the above saml assertion, do the following :
Conditions cond = assertion.getConditions();
Date _notBefore = cond.getNotBeforeDate();
Date _notOnOrAfter = cond.getNotOnOrAfterDate();
And now, you can compare _notBefore and _notOnOrAfter dates to complete the condition validation process.
Similar way, you can use other methods of com.sun.xml.wss.saml.Assertion api for validation of other 
elements of the saml assertion.

Monday Jul 14, 2008

How to log WS-Trust & WS-SecureConversation messages

In this blog i will show, how to enable logging of WS-Trust and WS-SecureConvesation messages for the application developed using Metro Web Services stack.

To get debug messages on client/server for WS-Trust and WS-SecureConvesation, change your JDK's (<JAVA_HOME>/jre/lib/logging.properties) level from INFO to FINE / FINER / FINEST :

java.util.logging.ConsoleHandler.level = FINEST

For WS-Trust, put the following WS-Trust logger to FINER :

com.sun.xml.ws.security.trust.level = FINER

For WS-SecureConversation, put the following WS-SecureConversation logger to FINER :

com.sun.xml.ws.security.secconv.level = FINER

The above logging properties print the RST and RSTR messages on the client's console and server's log file.

Tuesday May 06, 2008

How to Renew a SecureConversationToken Using Metro 1.2

Renewal of SecureConversation Token for submitted and standard(WS-SX) version of SecureConversation specification is supported in Metro 1.2 release. In this blog, i will show you how to enable the renewal of SecureConversation Token automatically, once it is expired.

Metro 1.2 defines the following client side SecureConversation configuration policy :
    1) lifetime of SecureConversation Token.
    2) whether to Renew Expired Secure Session Tokens

Here is the client-side SecureConversation  policy, which has to be put in the client-side configuration (i.e. in wsit-client.xml file)

<scc:SCClientConfiguration xmlns:scc="http://schemas.sun.com/ws/2006/05/sc/client" renewExpiredSCT="true">
     <scc:LifeTime>36000</scc:LifeTime>
</scc:SCClientConfiguration>

We also have a tooling support for this configuration in Netbeans 6.0 onwards. Here is the Netbeans screenshots for configuring Web Services Client with SecureConversation policy.

Figure 1 : Right click on Web Services Reference node and select Web Services Editor to configure Quality of service on the client side

 Figure 1 : Right click on Web Services Reference node and select Web Services Editor to configure Quality of Service on the client side 

 


Figure 2 : In Client's Web Services Editor, configure client with SecureConversation policy (i.e Token Lifetime, Enable/disable of token renewal)

 

Here is the format of Renew request from client :

 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" >
    <S:Header>
         ...........
        <Action xmlns="http://www.w3.org/2005/08/addressing" wsu:Id="_5004">
                    http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew</Action>
         .........

Here is the format of Renew response from service :

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Header>
         ...........
        <Action xmlns="http://www.w3.org/2005/08/addressing" wsu:Id="_5005"> 
                        http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew</Action>
         .........

 

In the WS-SX version of SecurityPolicy specification, MustNotSendRenew policy is being introduced under SecureConversationToken. MustNotSendRenew optional element is a policy assertion that indicates the  SCT Token issuer issuing the secure conversation token does not support SCT/Renew RST messages. If this assertion is not present it means that SCT/Renew RST messages are supported by the STS.

Here is the format of  MustNotSendRenew optional element under SecureConversationToken policy :

<sp:SecureConversationToken sp:IncludeToken="xs:anyURI"? xmlns:sp="..." ... >
    ........
    <wsp:Policy xmlns:wsp="...">
        .......
        <sp:MustNotSendRenew ... /> ?
        <sp:BootstrapPolicy ... >
            <wsp:Policy> ... </wsp:Policy>
        </sp:BootstrapPolicy>
    </wsp:Policy>
</sp:SecureConversationToken>

 

If client side SecureConversation configuration policy has renewExpiredSCT=true, and MustNotSendRenew optional element is not present in SecureConversationToken service policy, then the  renewal of  SCT token will be successful.

Monday Apr 14, 2008

Advanced Web Service Interoperability Sample Tutorial using Metro and Netbeans6.0

Here is a nice link on developing Advanced Web Service Interoperability Samples using Metro and Netbeans6.0. It has step-by-step screenshots for developing the application.

Netbeans also has tutorials on the following :

Tuesday Aug 07, 2007

WS-Trust Extension points support in METRO

Metro provides Secure, Reliable, Transactional and .NET 3.0 interoperable Web services stack in GlassFish. This entry talks about WS-Trust Extension points support in Metro .

There are three extension points being exposed in Sun's WS-Trust implementation.
The purpose of these extension points is to make STS implementation more transparent to user. User can implement these extension points, if they want to implement STS as per their business requirement.

1. STSAuthorizationProvider :

Developer can implement this extension to do runtime authorization of a requestor for token to be issued. 

For example : Create two users and in the provider implementation, put a authorization logic for only one user to be allowed to access the target service. You get the user name from the user's Subject principal.


2. STSAttributeProvider :

Developer can implement this extension to pass requestor's detail to be included in the token to be issued. The attribute returned by this provider implementation will be picked up by the SAML assertion created by STS. Users may have different identities for different services. You may have a identity mapping for different services. On the service side, you may supply your SAML Token validator to check if the actual user id and attributes returned by the provider implementation are picked up or not.

For example :

  • alice maps to abcd if the target service is http://..... and also provide some attributes like role, email address

  • Issued SAML Token carries a user attribute like "role of the user", which can be used for authorization on service

3. STSConfigurationProvider :

STSConfiguration element in the STS WSDL is used to have attributes for configuring an STS (e.g. Issuer for the STS, Issued tokens from this STS must be encrypted or not, Issued keys from the STS must be encrypted or not, Issued Token time-out, Implementation contract class for the STS, etc.)

Developer can implement this extension to provide/replace the STS configuration properties other than what is present in the "STSConfiguration" element of STS WSDL.

For example : If you are writing a STSConfiguration element and thinking you might change values of few properties at run time, then you need to implement this provider

Note : All the providers can be plug in using the standard ServiceFinder, i.e, with a file of name  com.sun.xml.ws.api.security.trust.STSAttributeProvider , etc, which contains the actual implementation class.

Click here to know "how to create customer STS with STSAttributeProvider implementation using WSIT"

Technorati: wsit 

Wednesday Jul 18, 2007

How to import PFX file into JKS using pkcs12import utility

The pkcs12import utility allows Public-Key Cryptography Standards version 12 (PKCS-12) files (referred to as PFX files) to be imported into a keystore, typically a keystore of type Java KeyStore (JKS).

If you have PKCS-12 formatted file, you would import this key-pair (certificate/private-key pair) into your private keystore using the pkcs12import utility. The result of the import is that the private-key and the corresponding certificate in the PKCS-12 file are stored as a key entry inside the keystore, associated with some alias.

The pkcs12import utility can be found here. Unzip the downloaded pkcs12import.zip file. pkcs12import utility can be run from the command line by executing pkcs12import.sh (on Unix systems) or pkcs12import.bat (on Windows systems). Before executing this script, make sure JAVA_HOME environment variable points to your JAVA installation.

Options for pkcs12import utility
Option
Description
-file pkcs12-file
Required. The location of the PKCS-12 file to be imported.
[ -pass pkcs12-password ]    
The password used to protect the PKCS-12 file. The user is prompted for this password if this option is omitted.
[ -keystore keystore-file ]       
Location of the keystore file into which to import the contents of the PKCS-12 file. If no value is given, defaults to ${user-home}/.keystore.
[ -storepass store-password ]   
The password of the keystore. User is prompted for the password of the truststore if this option is omitted.
[ -keypass key-password ]
The password to be used to protect the private key inside the keystore. The user is prompted for this password if this option is omitted.
[ -alias alias ]
The alias to be used to store the key entry (private key and the certificate) inside the keystore.

Tuesday Mar 13, 2007

Develop WSTrust Application Using NetBeans

The WS-Trust specification addresses the issue of  brokering trust,  in scenarios where  the SecurityToken possessed by the Web Service consumer is not trusted by the Service Provider or in cases where the type of the Sercurity Token possesed by the client is not understood by the Service Provider.   For example, when the Web Service client and the Web Service provider sit in different security domains (having different trust roots) and have no direct trust relationships. The protocols defined in WS-Trust allow for establishing a Security Token Service as a trust authority for brokering trust among Web Services consumers and Web Services providers. WS-Trust provides methods for issuing, renewing, and validating security tokens used by WS-Security. It also provides way to establish and broker trust relationships.

NetBeans has made life easier in developing WS-Trust applications to get Interoperability among different domains.

Download NetBeans & WSIT Plugin from :
    NetBeans v5.5.1 : http://netbeans.info/downloads/dev.php
    WSIT Module     : http://websvc.netbeans.org/servlets/ProjectDocumentList?folderID=123

    For WSIT Installation instructions, click here  ( Note : Use latest promoted WSIT build from here to develop a WS-Trust application). WSIT is being developed within the Glassfish community and will be delivered through Glassfish v2.

In this blog i would like to show how you can develop a Security Token Service using WSIT. This Security Token Service can be used to act as the STS for any of the Security Mechanisms defined in NetBeans that require an STS.  When a Security Mechanism requires the use of an STS, then the security configuration of the Consumer should be setup in such a way that it can securely communicate with both the STS and the Service Provider.  This blog will also explain how the  secuity configuration of the Consumer can be setup for doing this.

The first step is to Create a service  which requires an STS, so here are the steps to create the service:


  1. Refer to Security Chapters of WSIT Tutorial on how to create/secure a service.

    • when you select "Edit Web Services Attributes" for configuring security options and click "Secure All Services Operations" check box. You will see 3 profiles that require the use of an STS under Security Mechanism(s).
      • STS Issued Token
      • STS Issued Token with Service Certificate
      • STS Issued Endorsing Token

                 Selecting any of these mechanisms listed above will require you to develop or configure an STS. All these 3 mechanism will have the default settings.


  1. Run the service project, it will open a deployed service wsdl in the browser.


Create an STS :


  1. Refer to the Tutorial's section on how to create/secure STS to create a new service and
    configure it as an STS. Besides this, we need to implement the provider implementation class as given below, which is created by STS wizard (i.e. STS wizard creates an empty implementation of provider class).


import com.sun.xml.ws.security.trust.sts.BaseSTSImpl;
import javax.annotation.Resource;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.Service.Mode;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.transform.Source;
import javax.xml.ws.handler.MessageContext;


@ServiceMode(value = Mode.PAYLOAD)
@WebServiceProvider(wsdlLocation = "WEB-INF/wsdl/<Class_Name>/sts.wsdl", serviceName = "SecurityTokenService", targetNamespace = "http://tempuri.org/", portName = "ISecurityTokenService_Port" )
public class <Class_Name> extends BaseSTSImpl implements javax.xml.ws.Provider<Source> {

    @Resource
    protected WebServiceContext context;

    /** Creates a new instance of <Class_Name> */
    public <Class_name>() {
    }
    public Source invoke(Source rstElement){
        return super.invoke(rstElement);
    }
    protected MessageContext getMessageContext() {
        MessageContext msgCtx = context.getMessageContext();
        return msgCtx;
    }
}

  1. Select any security Mechanisms.


  2. Keep the default values of “Act As Secure Token Service” checkbox, or else you can change the values in STSConfiguration Assertion of the sts wsdl using configure button.


  3. run the STS project. here service name="SecurityTokenService". So if you want to access the wsdl, just append "SecurityTokenService" in the deployed application URL and hit the browser. STS wsdl appears. 

    For step by step screenshots for creating STS project, See below. 

Prior to creating the Trust client, create an account (username/password) on glassfish for Username Authentication. Refer to the Tutorial's section on Adding Users to Glassfish


Create a Client :


  1. Refer to Security Chapter of WSIT Tutorial on how to create/secure Client. Besides this, follow the additional steps given below to create a separate client-config for STS and import it in wsit-client.xml ( Note`: wsit-client.xml is a client side configuration).


A ) The service requires a token to be issued from STS at "http://<url>/SecurityTokenService”, with wsdl file being "http://<url>/SecurityTokenService?wsdl". So, in the same project, follow WebService Client wizard again for "http://<url>/SecurityTokenService?wsdl". As a result you see a  SecurityTokenService client node in Web Services References . Now configure this client with sts related keystore & truststore. Once you are done, the layout of  wsit-client.xml would be :


wsit-client.xml
|
| imports
|-----------> <clinet_config_for_STS>.wsdl [STS related keystore/truststore assertions in client ]
|
|imports
|-----------> <client_config_for_service>.wsdl [Service related keystore/truststore assertions in client ]


  1. Run the client project.

 For step by step screenshots for creating STS project & Client Project, See below.

Complete snapshots for creating STS  in Netbeans: 

Create a web Project for STS : 


 

Right Click on STS project, select New -> File/Folder... and choss the SecureTokenService(STS) from FileType under WebServices Categories :

 

 

Create STS class name and package :

 

 

 Created STS class looks like :

 

Replace the implementation of STS class with the specified one above. Now, STS class looks like :

 

Right Click SecurityTokenService node under WebServices folder and select Edit Web Service Attributes :

 

 Select Security Mechanishm (Mutual Certificated Security) :

 


Select Keystore button and configure keystore for STS, then click OK: 

 

Select Truststore button and configure truststore for STS, then click OK:

 

Click on configure... button, which is infront of Act As Security Token Service (STS) checkbox. Change the STSConfiguration if you want, then click OK:

 

Generated sts.wsdl looks like : 

 

Right Click on STS prokect and select Properties

 

 In project properties, write /SecurityTokenService?wsdl in Relative URL :


 

Right Click on STS project, and select Run Project

 

 
 Now STS wsdl gets deployed on Glassfish and a browser opens up to show the deployed sts wsdl :

 

 

Complete snapshots for creating Client project in Netbeans:

Create a WebApplication for the Client Project. Right Click on Client Node and select New -> Web Services Client... :

 

Give deployed Server wsdl  url in WSDL URL Radio button (this url can be found from server project) and create package name :

 

Right Click on generated server node under Web Service References 
and select Edit Web Services Attributes. Provide the client side
Keystore/Truststore for server. Also provide the details for Security Token Service for adding PreconfiguredSTS in client configuration as below. Then click OK :

 

Generate client configuration for server looks like :

 

Create another WebService Client for client-side confugiration for STS : 

 

Give deployed STS wsdl  url in WSDL URL Radio button (this url can be found from STS project) and create package name :

 

Right Click on generated SecurityTokenService node under Web Service References 
and select Edit Web Services Attributes :

 

Provide the client side
Keystore/Truststore for STS. Also provide the details of Username Authentication, if you are using usernameToken in the sts wsdl. Then click OK :

 

Generated client side configuration (wsit-client.xml) will import both client-side configuration ( server & sts ) :

 

Open index.jsp file, and move your curson just below the statement <%-- start web service invocation --%> . Right click there, select Web Service Client Resources -> Call Web Service Operation. Now expand the client node for server, and see the operation name (which was implemented while creating server project) and select it, then click OK.

 

Default template for web service invocation shows : 

 

Give the value for parameters, which will be passed to the operation name and print the exception : 

 

Right Click on Client Project and select Run Project :

 

Once the execution completes. A browser window with JSP page opens up to display the result :


 

Give it a try! And, let Jiandong & me know what do you think!

Shyam Rao 

 

Technorati: wsit

Calendar

Search

Links

Navigation

Referers