Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Tuesday, April 16, 2013

Enterprise Security and Identity Management Use Cases with WSO2 Identity Server

This is the set of slides used in WSO2Con 2013 - tutorial session on the topic: "Enterprise Security and Identity Management Use Cases with WSO2 Identity Server", along with demos for each of these use cases.

I plan to blog about individual samples used to demonstrate each of these use cases in my future posts.


Sunday, August 12, 2012

Digital Signature by Example

We use digital signature for two main purposes in message communication:

1. To guarantee the integrity of the content (i.e to ensure that message has not been changed during transmission from sender to receiver)
2. To authenticate the message origination (i.e to verify that the message was sent from the party that we think it is sent from)

We use cryptographic mechanisms to generate and verify digital signature.
Before going into the code level, let me briefly mention the steps involved in creating and verifying the digital signature.

Pre-requisites:

Have your keystore created with private key and public key. You can refer to the posts at here and here for the steps in creating a keystore with private/public key pair using java keytool.

Creating digital signature at the sender:

1. Computing the hash value of the content to be signed...

Here we use hash functions in cryptography to create a fixed length hash value such that it is impossible to calculate the original content or the length of the content from the hash value. This is called message digest or one-way encryption. Hence hash functions provide a digital fingerprint of the content to be signed.

2. Encrypting the hash value with his/her private key...

Here we use asymmetric key cryptography to encrypt the hash value computed from the message content.

Verifying digital signature at the receiver:

1. Decrypting the signature and obtaining the message digest..

Receiver once again applies asymmetric key cryptography to decrypt the message signature using sender's public key. 

How does the receiver obtain sender's public key?
It can happen in different ways according to the message communication protocol that you use. Usually communicating parties can exchange keys before the message communication, in a trusted way or the sender can send the certificate containing the public key along with the signed content and the signature. It is not recommended to send the public key itself since it is susceptible to MIM attacks. You can read more about it from here.

At this step, message origin authentication happens. Since only the one who owns the private key related to the public key used to decrypt the signature, can sign the message - we can identify who has sent the message.

2. Comparing the hash values to verify message integrity...
Receiver computes the hash value on the original message and compares it with the hash value sent by the sender, which was obtained in the above step after decrypting the digital signature. If the two values are identical, receiver can verify that the message integrity is protected during the transmission.

Now let us see how we can create and verify digital signature over some text content with an existing private/public key pair in the keystore named 'mykeystore.jks', using Java Security API.

I hope the comments in the following source code will help you understand each step performed in doing this.
package org.digital.signature.sample;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;


public class Sample {
    //keystore related constants
    private static String keyStoreFile = "/home/hasini/Digital-Signature/sample/src/main/resources/mykeystore.jks";
    private static String password = "mypassword";
    private static String alias = "mycert";

    public static void main(String[] args) {

        try {
            KeyStore keystore = KeyStore.getInstance("JKS");
            char[] storePass = password.toCharArray();

            //load the key store from file system
            FileInputStream fileInputStream = new FileInputStream(keyStoreFile);
            keystore.load(fileInputStream, storePass);
            fileInputStream.close();

            /***************************signing********************************/
            //read the private key
            KeyStore.ProtectionParameter keyPass = new KeyStore.PasswordProtection(storePass);
            KeyStore.PrivateKeyEntry privKeyEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, keyPass);
            PrivateKey privateKey = privKeyEntry.getPrivateKey();

            //initialize the signature with signature algorithm and private key
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);

            //Read the string into a buffer
            String data = "{\n" +
                          "  \"schemas\":[\"urn:scim:schemas:core:1.0\"],\n" +
                          "  \"userName\":\"bjensen\",\n" +
                          "  \"externalId\":\"bjensen\",\n" +
                          "  \"name\":{\n" +
                          "    \"formatted\":\"Ms. Barbara J Jensen III\",\n" +
                          "    \"familyName\":\"Jensen\",\n" +
                          "    \"givenName\":\"Barbara\"\n" +
                          "  }\n" +
                          "}";

            byte[] dataInBytes = data.getBytes();

            //update signature with data to be signed
            signature.update(dataInBytes);

            //sign the data
            byte[] signedInfo = signature.sign();

            System.out.println(signedInfo.toString());

            /**************************verify the signature****************************/
            Certificate publicCert = keystore.getCertificate(alias);

            //create signature instance with signature algorithm and public cert, to verify the signature.
            Signature verifySig = Signature.getInstance("SHA256withRSA");
            verifySig.initVerify(publicCert);

            //update signature with signature data.
            verifySig.update(dataInBytes);

            //verify signature
            boolean isVerified = verifySig.verify(signedInfo);

            if (isVerified) {
                System.out.println("Signature verified successfully");
            }
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (UnrecoverableEntryException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();  
        }
    }
}

References:

[2] http://www.garykessler.net/library/crypto.html#intro

Sunday, September 18, 2011

How to use pre-compiled JSPs in a webapp with tomcat 7

Problem:
Recently I had the following requirement:

I had a webapp that has some jsp files which directly call some methods in some libraries. But those libraries are in a sandbox environment secured by Java Security Manager. Therefore only the calls that come from classes that are signed by a particular key, are allowed to be executed.

My webapp was not working until I guarantee the sandbox environment that the method calls are coming from a signed source.

Solution:
The solution for the above problem is consisted with following steps:
1. Pre-compile jsp files.
2. Package the pre compiled jsp files into a jar file.
3. Sign the jar file using the appropriate key.
4. Package the signed jar file in the WEB-INF/lib folder of the webapp
5. Remove all the jsp files from the webapp.

Walk through:
jspc-maven-plugin comes to the rescue in this occasion.

I will walk you through how to pre-compile jsp files of the example webapp of WSO2 AppServer by integrating pre-compiling step into the maven pom.xml.

Following is the complete pom.xml file with modifications to include the steps of pre-compiling and packaging the jsp files.

    
        org.wso2.appserver
        wso2appserver-samples-parent
        4.1.1
        ../../pom.xml
    

    4.0.0
    
    example
    war
    WSO2 AS - Example webapp

    
        
            org.wso2.carbon
            org.wso2.carbon.tomcat
            ${carbon.platform.version}
        
        
            org.apache.axis2.wso2
            axis2-client
            ${axis2.osgi.version}
        
        
            org.wso2.carbon
            org.wso2.carbon.authenticator.proxy
            ${carbon.platform.version}
        
        
            org.wso2.carbon
            org.wso2.carbon.authenticator.stub
            ${carbon.platform.version}
        
        
            org.wso2.carbon
            org.wso2.carbon.core.common
            ${carbon.platform.version}
        
        
            org.wso2.carbon
            org.wso2.carbon.core
        

        
            org.apache.axis2.wso2
            axis2
        
    

    
        
            
                org.codehaus.mojo
                build-helper-maven-plugin
                
                    
                        add-source
                        generate-sources
                        
                            add-source
                        
                        
                            
                                target/generated-code/src
                            
                        
                    
                
            

            
                org.codehaus.mojo.jspc
                jspc-maven-plugin
                
                    
                        
                            compile
                        
                    
                
                
                    ${pom.basedir}/src/main/resources/WEB-INF/web.xml
                    1.5
                    1.5
                    
                        ${pom.basedir}/src/main/resources
                        
                            **/*.jsp
                        
                    
                
                
                
                
                    
                        org.codehaus.mojo.jspc
                        jspc-compiler-tomcat6
                        2.0-alpha-3
                        
                        
                            
                                org.apache.tomcat
                                jasper
                            
                            
                                org.apache.tomcat
                                jasper-el
                            
                            
                                org.apache.tomcat
                                jasper-jdt
                            
                            
                                org.apache.tomcat
                                servlet-api
                            
                            
                                org.apache.tomcat
                                jsp-api
                            
                            
                                org.apache.tomcat
                                el-api
                            
                            
                                org.apache.tomcat
                                annotations-api
                            
                        
                    
                    
                    
                        org.apache.tomcat
                        tomcat-jasper
                        7.0.12
                    
                    
                    
                        org.eclipse.jdt.core.compiler
                        ecj
                        3.5.1
                    
                
            

            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.5
                    1.5
                
            
            
            
                org.apache.maven.plugins
                maven-war-plugin
                2.1-beta-1
                
                    example
                    
                        WEB-INF/classes/**,
                        WEB-INF/*,
                        WEB-INF/jsp/*,
                        WEB-INF/jsp2/*,
                        WEB-INF/lib/jstl.jar,
                        WEB-INF/lib/standard.jar,
                        WEB-INF/lib/jsp.jar,
                        **/axis2-client*.jar,
                        **/org.wso2.carbon.authenticator.proxy*.jar,
                        **/org.wso2.carbon.authenticator.stub*.jar,
                        **/org.wso2.carbon.core.common*.jar,
                        **/*.java,
                        **/tags/**,
                        **/servlets/**,
                        **/carbon/**,
                        **/*.class,
                        **/*.html,
                        jsp/images/*
                    
                    
                        
                            
                            src/main/resources
                        
                    
                    ${pom.basedir}/target/jspweb.xml
                
            
        
    


Following is what is done... please follow with the line numbers:

1. line 73 introduces jspc-maven-plugin to the pom.xml file.
This will compile jsp files to servlets and then into .class files which include the byte code. These can be found under "target/jsp-source" once the maven build succeeds.

2. Note the 'Configuration' element from line 83 to 93:
    - inputwebxml: specify where the original web.xml file of the webapp resides. jspc-maven-plugin will detect that and update the servlet mappings according to the compiled jsp files and create a new file called "jspweb.xml" in the target folder, which you need to package with the webapp instead of the original web.xml.
    - sources: specify where the jsp files resides in your webapp .

3. Then comes the trick: there is no jspc-maven-compiler plugin for tomcat 7 yet. So we need to use tomcat 6 version of it by removing the incompatibilities. This is what is done from line 97 to line 147.

4. As in line 190, you need to specify the new web.xml created by this plugin, to be included in the .war file of the webapp.

5. Now the step 1 mentioned in the above 'solution' section is achieved and the files obtained by pre-compiling jsp files are available in 'target/jsp-source' folder.

Now, in order to complete steps from 2-4 in the above 'solution', you may need to write a ant build.xml file or can integrate those steps into the pom.xml file itself. I did it through a ant build.xml file.

You can use jarsigner tool that comes with JDK installation  to sign the jar file containing the compiled jsps, as described here.

Once you include the compiled jsps in a jar file in the webapp, you need to remove the original jsp files from the webapp or avoid packaging them in the .war file because if they are included, those will be compiled and used by the servlet container instead of the already pre-compiled ones.

In my case, I had to remove the jsp files packaged inside web-inf/classes/carbon
and web-inf/classes/jsp/carbon of the webapp.

Hope this helps...