Archive

Archive for the ‘Security’ Category

OpenStack Barbican & HSM Flow

December 28, 2016 Leave a comment

I assume you know what Hardware Security Module in short HSM is… if not https://en.wikipedia.org/wiki/Hardware_security_module

HSM Limitations

  • Maximum 20 partitions/slots (eg: Luna HSM)
    • Enough space to hold an RSA key-pair
    • Default total storage space on the HSM is 2 MB (upgrade to 15MB)
  • Only limited number of keys can be stored
  • Performance subject to network latency, scale and HSM performance

Barbican is an Openstack module for storing secrets. I’ll write few blog posts on Barbican PoC later. Barbican + HSM can make a great combination for storing your cloud secrets to meet security and PCI based compliance requirements. Not wasting time, here is how integration flow looks like…

barbican_hsm_flow

High-Level flow of Barbican & HSM integration

  • MKEK (Master Key Encryption Key) is global key to Barbican
  • Project level unique KEK stored in Barbican (in fact encrypted KEK is stored)
  • Data Encryption Keys (DEK) stored in Barbican (in fact encrypted DEK is stored)
  • MKEK wraps every project’s unique KEK
  • KEK wraps project’s DEK

 

Tomcat 2 way SSL Configuration (Step-by-Step)

August 9, 2016 1 comment

The is a working POC for 2 way SSL configuration in Tomcat server, where client and server has OpenSSL key pairs. This POC covers CA, Server & Client all running on same machine.

Step 1: Create your own root CA


~/openssl$ mkdir -m 0700 /home/ubuntu/openssl/CA /home/ubuntu/openssl/CA/certs /home/ubuntu/openssl/CA/crl /home/ubuntu/openssl/CA/newcerts /home/ubuntu/openssl/CA/private

~/openssl$ touch /home/ubuntu/openssl/CA/indext.txt

~/openssl$ echo 1000 >> /home/ubuntu/openssl/CA/serial

~/openssl$ mv karun-tomcat-root-ca.key CA/private/

~/openssl$ sudo vi /etc/openssl.cnf
 # Make changes here
 dir = /home/ubuntu/openssl/CA
 #optionally change policy definitions as well

~/openssl$ openssl genrsa -des3 -out karun-tomcat-root-ca.key 2048
#In below command make sure to use CN=<hostname of your machine>

~/openssl$ openssl req -new -x509 -days 36520 -key karun-tomcat-root-ca.key -out karun-tomcat-root-ca.crt -config openssl.cnf

~$ sudo cp ~/openssl/CA/certs/karun-tomcat-root-ca.crt /usr/share/ca-certificates/

# make sure in the UI you enable/select the certificate created above

~$ sudo dpkg-reconfigure ca-certificates

# Now reboot ubuntu machine just to make sure certificates are loaded successfully and tomcat picks it

 

Step 2: Create Tomcat Server’s Key Pair


~$ openssl genrsa -out tomcat-server.key 2048

# Use common name =<Give IP address>, department = Tomcat Server CSR

~$ openssl req -new -sha256 -config ~/openssl/openssl.cnf -key tomcat-server.key -out tomcat-server.csr

~$ openssl x509 -req -sha256 -days 36520 -in tomcat-server.csr -signkey tomcat-server.key -CA ~/openssl/CA/certs/karun-tomcat-root-ca.crt -CAkey ~/openssl/CA/private/karun-tomcat-root-ca.key -CAcreateserial -out tomcat-server.crt

~$ openssl pkcs12 -export -name karun-tomcat-server-cert -in tomcat-server.crt -out tomcat-server.p12 -inkey tomcat-server.key -CAfile ~/openssl/CA/certs/karun-tomcat-root-ca.crt -caname karun-root -chain

~$ keytool -importkeystore -destkeystore tomcat-server.jks -srckeystore tomcat-server.p12 -srcstoretype pkcs12 -alias karun-tomcat-server-cert

~$ keytool -import -alias karun-root -keystore tomcat-server.jks -trustcacerts -file ~/openssl/CA/certs/karun-tomcat-root-ca.crt

# Run this once client cert is generated
~$ keytool -importkeystore -alias karun-tomcat-client-cert -srckeystore ~/client-certs/tomcat-client.p12 -srcstoretype PKCS12 -destkeystore tomcat-server.jks -deststoretype JKS

# Run this once tomcat server started successfully
~$ openssl s_client -connect localhost:8443 -cert ~/client-certs/tomcat-client.crt -key ~/client-certs/tomcat-client.key -debug -showcerts 

Step 3: Create Client Side Key Pair


~$ openssl genrsa -out tomcat-client.key 2048
# Use common name = <tomcat-user.xml's user say 'admin'>, department = Tomcat Client CSR

~$ openssl req -new -sha256 -config ~/openssl/openssl.cnf -key tomcat-client.key -out tomcat-client.csr

~$ openssl x509 -req -sha256 -days 36520 -in tomcat-client.csr -signkey tomcat-client.key -CA ~/openssl/CA/certs/karun-tomcat-root-ca.crt -CAkey ~/openssl/CA/private/karun-tomcat-root-ca.key -CAcreateserial -out tomcat-client.crt

~$ openssl pkcs12 -export -name karun-tomcat-client-cert -in tomcat-client.crt -out tomcat-client.p12 -inkey tomcat-client.key -CAfile ~/openssl/CA/certs/karun-tomcat-root-ca.crt -caname karun-root -chain

~$ (optional step) keytool -importkeystore -destkeystore tomcat-client.jks -srckeystore tomcat-client.p12 -srcstoretype pkcs12 -alias karun-tomcat-client-cert

~$ (optional step) keytool -import -alias root -keystore tomcat-client.jks -trustcacerts -file ~/openssl/CA/certs/karun-tomcat-root-ca.crt

<p class="lang-java prettyprint prettyprinted">

Step 4: Tomcat Changes


<p class="lang-java prettyprint prettyprinted"><!-- Make this change in server.xml of tomcat server -->
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
keystoreFile="/opt/tomcat/openssl-certs/tomcat-server.jks"
keystorePass="password"
keyAlias="karun-tomcat-server-cert"
truststoreFile="/opt/tomcat/openssl-certs/tomcat-server.jks"
truststorePass="password"
clientAuth="true" sslProtocol="TLS" /></p>
<p class="lang-java prettyprint prettyprinted">

Step 5: Restart Tomcat Server && check logs to ensure no errors at bootup

Step 6: Upload Client cert to browser

In your browser, eg: firefox, navigate Preferences -> Advanced -> Certificate -> View Certificates -> Your Certificates

Import “tomcat-client.p12”

https://localhost:8443/

References

http://pages.cs.wisc.edu/~zmiller/ca-howto/

http://www.area536.com/projects/be-your-own-certificate-authority-with-openssl/

Docker & Kubernetes Cheat Sheet

Categories: General, Security Tags: , ,

All Demo POC Videos


http://www.youtube.com/channel/UCSLhSPCG4rc7AuDRi5utEBA

I’ve uploaded demo videos in above channel. Feel free to take a look and pass a feedback/like

Oracle STS – OnBehalfOf SAML Token Validation


There have been requests to my previous blog post on how to validate a SAML token issued by Oracle STS.

Here is the SOAP request format that should be fired on Oracle STS to validate the token:


<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:trus="http://schemas.xmlsoap.org/ws/2005/02/trust">
<soap:Header>
<wsse:Security soap:mustUnderstand="true" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>weblogic</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Welcome1</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soap:Header>
<soap:Body>
<wst:RequestSecurityToken Context="Id-0001313145021190-00000000008d4682-1" xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200512" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wst:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate</wst:RequestType>
<wst:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1</wst:TokenType>
<wst:ValidateTarget>
<wsse:SecurityTokenReference>
<wsse:KeyIdentifier ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID">id-McjucPrvkxXpY6m3w-8iFtvmEYQ-</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</wst:ValidateTarget>
</wst:RequestSecurityToken>
</soap:Body>
</soap:Envelope>

You get SecurityTokenReference from SAML token issued by STS. You need to use it for further validation, like above SOAP request.

This returns you with the response:


<wst:Status>
<wst:Code>http://docs.oasis-open.org/ws-sx/ws-trust/200512/status/valid</wst:Code>
</wst:Status>

 

Hope this helps.

SAML2.0 Weblogic Sender-Vouches Configuration & POC

June 4, 2016 8 comments

This blog post intends to highlight on the SAML2.0 configuration for web services in Weblogic. It details step-by-step guide to configure weblogic domains with a sample test client to test the web service. We will look into SAML2.0 Sender Vouches web service configuration.

What is Sender Vouches?

Sender-Vouches – The asserting party (different from the subject) vouches for the verification of the subject. The receiver must have a trust relationship with the asserting party.

Sender Vouches
1. Rather than authenticating with the STS, here, Client authenticates with an intermediate service.
2. The intermediary gets the security token from the STS.
3. Then it signs the request and sends to the RP.
4. RP trusts both the intermediary and the STS. So, it validates both of them.

Here are the steps:

  • Configure STS (Weblogic Domain – Certificate used is wssipsts
  • Configure Weblogic domain for weblogic web service with SAML2.0 Sender Vouches policy – Bob is used for this
  • Create a stand alone client that which retrieves token from STS and fires a request to web service with SAML1.1 token retrieved from STS – Alice is used for this

Configure STS:

  1. Create a weblogic domain here ‘am using weblogic 10.3.5
  2. We need to configure SSL for this domain
  3. While creating the domain I configure weblogic to use 6001 for Non-SSL and 6002 for SSL port. Let domain name be STSDomain.
  4. Now go to http://localhost:6001/console
  5. Got to STSDomain –> Environment –> Admin Server –> Keystores
    • Select Custom Identity and Custom Trust
    • Custom Identity Keystore: F:\Oracle\Middleware\user_projects\domains\STSDomain\certs\oasis.jks
    • Type: JKS
    • password: password
    • Custom Trust Keystore: F:\Oracle\Middleware\user_projects\domains\STSDomain\certs\cacerts
    • Type: JKS
    • password: changeit
    • Save and restart server if it asks to do so
  6. Got to STSDomain –> Environment –> Admin Server –>SSL
    • Private Key Alias: WssIPSTS
    • Private Key passphrase: password
    • Save and restart if asked to do so
  7. Now build the web service StsUnt.java and deploy it in the domain. Check after successful deployment whether you can open the WSDL url or not.
  8. STSDomain–>Security Realms –>myrealm
  9. We need to configure only ‘Credential Mapper’ here. Credential Mapper basically responsible for Issuing SAML tokens. Where as identity Asserter are responsible for validating the SAML tokens. So we will configure Credential Mapper for STS and Identity Asserter for webservice
  10. Go to Providers –> Credential Mapping
  11. Add PKI Credential Mapper
    • In Provider Specific tab, Keystore Provider: SUN
    • Keystore Type: JKS
    • Keystore file name: F:\Oracle\Middleware\user_projects\domains\STSDomain\certs\oasis.jks
    • Keystore pass phrase: password
    • Use resource hierarchy and Initator group names check boxes should be selected.
    • Click on save and restart if asked to do so
  12. Add SAML2CredentialMapper
    • In Configuration –> Provider specific tab, Issuer URI: www.oracle.com
    • Name Qualifier: www.oracle.com
    • Default time to live: 120
    • offset: 0
    • Webservice Assertion Signing key alias: WssIPSTS
    • Key pass phrase: password
    • Select check box ‘Generate Attributes’
    • Save and go to Management tab in the same section
    • New–>New Webservice Service Provider Partner
    • Add sender vouches relying party: Sendervouches:/echoservicesaml2/EchoServiceSAML2
    • Make sure to select ‘Enabled’ check box
    • Give description
    • Audience URIs:  target:*:http://HYD-69ZRV01-L:7001/echoservicesaml2
    • Generate Attributes checkbox to be selected
    • Select confirmation methods as ‘Sender-Vouches’
    • Save and restart the server if asked to do so
  13. That’s all the configuration from STS side.

Configure Weblogic Webservice:

  1. Create a weblogic domain here ‘am using weblogic 10.3.5
  2. We do not need to configure SSL for this domain
  3. While creating domain configure weblogic to use 7001 port and no SSL port required. Let the domain name be ‘WebserviceDomain’
  4. Login to weblogic console.
  5. WebserviceDomain–>servers–>Adminserver–>keystore
    • Custom Identity and Custom Trust store
    • Custom Identity Keystore: F:\Oracle\Middleware\user_projects\domains\WebserviceDomain\certs\oasis.jks
    • Key type: JKS
    • password: password
    • Trust Keystore: F:\Oracle\Middleware\user_projects\domains\WebserviceDomain\certs\cacerts
    • Type: JKS
    • password: changeit
    • Save and restart the server if asked to do so.
    • SSL
    • Private key alias: Bob
    • password: password
    • Save
  6. Build and deploy the weblogic web service. The scripts and the webservice code is given below.
  7. Go to security realm–>myrealm–>Providers–>Authentication
    • Add SAMLAuthenticator
    • Make control Flag as ‘SUFFICIENT’
    • Make control Flag of Default Authenticator too as ‘SUFFICIENT’
    • (optional step) Also in Default Authenticator’s ‘Provider Specific’ Enable password digest, minimum password length as 1 and save.
    • (optional step) In Default Identity Asserter’s –> Common. chose Active Types ‘wsse:passworddigest’ and ‘x.509’ send it to right and click on save.
    • (optional step) In Defaul Identity Asserter –> Provider Specific. Default Username as @, Mapper attribute type as ‘CN’, select ‘use default user name mapper’ and click on Save button. Restart if asked to do so
  8. Got to security realm–>myrealm–>Providers–> Authentication
    • Add SAML2IdentityAsserterV
    • Go to Management –> New –> New Webservice Identity Provider Partner
    • Name: Sendervouches:/echoservicesaml2/EchoServiceSAML2
    • Chose Enabled
    • Audience URIs: target:*:/echoservicesaml2
    • Issuer URI: www.oracle.com
    • Virtual User selected
    • Confirmation Method: Sender-Vouches
    • Process Attributes selected
    • Save and restart if asked to do so.
  9. That’s all the configuration of web service.

Client Testing:

  1. Open a command prompt window
  2. Run setWLSEnv.cmd from that command window to set the paths
  3. ant runsaml2
  4. That’s all for now…

StsUnt.java

package com.saml.example;</pre>
<pre>import weblogic.jws.Policy;
 import weblogic.wsee.security.saml.SAMLTrustTokenProvider;
 import weblogic.wsee.security.wst.framework.TrustTokenProviderRegistry;</pre>
<pre>import javax.jws.WebMethod;
 import javax.jws.WebService;</pre>
<pre>@WebService
 @Policy(uri="policy:Wssp1.2-2007-Wssc1.3-Bootstrap-Https-UNT.xml")
 public class StsUnt {
         static {
         init();
     }
     @WebMethod
     @Policy(uri="policy:Wssp1.2-2007-SignBody.xml")
     public String dummyMethod(String s) {
         return s;
     }
    static void init() {
         TrustTokenProviderRegistry reg = TrustTokenProviderRegistry.getInstance();
         SAMLTrustTokenProvider provider = <span class="il">new</span> MySAMLTrustTokenProvider();
         reg.registerProvider("<a href="http://docs.oasis-open.org/wss/2004/01/oasis-2004-01-saml-token-profile-1.0#SAMLAssertionID" target="_blank">http://docs.oasis-open.org/wss/2004/01/oasis-2004-01-saml-token-profile-1.0#SAMLAssertionID</a>", provider);
         reg.registerProvider("<a href="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID" target="_blank">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID</a>", provider);
         reg.registerProvider("<a href="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" target="_blank">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</a>",  provider);
         reg.registerProvider("<a href="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.0" target="_blank">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.0</a>",  provider);
         reg.registerProvider("<a href="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1" target="_blank">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1</a>",  provider);
     }
    static class MySAMLTrustTokenProvider extends SAMLTrustTokenProvider {</pre>
<pre>    }
 }

build.xml for StsUnt.java

<?xml version="1.0"?>
<project name="SenderVouches11" default="all" basedir=".">
<property name="root.dir" value="${basedir}" />
<taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />
<taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />
<taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy" />
<taskdef name="wsdlc" classname="weblogic.wsee.tools.anttasks.WsdlcTask" />
<property file="${basedir}/properties.txt" />
<property name="source.dir" value="${basedir}" />
<property name="output.dir" value="${basedir}/build" />
<path id="class.path">
<pathelement path="${java.class.path}" />
</path>
<target name="all" depends="clean,jwsc,deploy" />
<target name="build" depends="clean,jwsc" />
<target name="clean">
<delete dir="${output.dir}" />
</target>
<target name="jwsc">
<antcall target="jwsc-sts" />
</target>
<target name="jwsc-sts">
<jwsc srcdir="${source.dir}" destdir="${output.dir}" debug="on" classpath="${class.path}">
<module contextpath="standalonests" name="standalonests" explode="true">
<jws file="StsUnt.java" type="JAXWS">
<WLHttpTransport serviceUri="SamlSTS" />
</jws>
</module>
</jwsc>
</target>
<target name="deploy">
<antcall target="deploy-sts" />
</target>
<target name="deploy-sts">
<wldeploy action="deploy" source="${output.dir}/standalonests" user="${sts-wls-username}" password="${sts-wls-passwd}" verbose="false" adminurl="t3://${sts-wls-server}" debug="false" targets="${sts-wls-target}" />
</target>
<target name="undeploy">
<property name="wls-admin-server" value="${wls-server}" />
<wldeploy action="undeploy" name="standalonests" user="${sts-wls-username}" password="${sts-wls-passwd}" verbose="false" adminurl="t3://${sts-wls-server}" debug="false" targets="${sts-wls-target}" />
</target>
<property name="extra-server-verbose" value="
-Dweblogic.xml.crypto.encrypt.verbose=true
-Dweblogic.xml.crypto.dsig.debug=true
-Dweblogic.xml.crypto.dsig.verbose=true
-Dweblogic.wsee.security.debug=true
-Dweblogic.wsee.security.verbose=true
-Dweblogic.xml.crypto.wss.debug=true
-Dweblogic.xml.crypto.wss.verbose=true
-Dweblogic.xml.crypto.keyinfo.debug=true
-Dweblogic.xml.crypto.keyinfo.verbose=true
-Dweblogic.xml.crypto.dsig.debug=true
-Dweblogic.xml.crypto.dsig.verbose=true
-Dweblogic.xml.crypto.encrypt.debug=true
-Dweblogic.xml.crypto.encrypt.verbose=true
-Dweblogic.debug.DebugSecuritySAMLService=true
-Dweblogic.debug.DebugSecuritySAMLCredMap=true
-Dweblogic.debug.DebugSecuritySAMLAtn=true
-Dweblogic.debug.DebugSecuritySAMLLib=true
-Dweblogic.debug.DebugSecuritySAML2Service=true
-Dweblogic.debug.DebugSecuritySAML2CredMap=true
-Dweblogic.debug.DebugSecuritySAML2Atn=true
-Dweblogic.debug.DebugSecuritySAML2Lib=true
-Dweblogic.debug.DebugSecurityCredMap=true
-Dweblogic.log.StdoutSeverity=Debug" />
</project>

properties.txt for StsUnt.java

certs.dir=${root.dir}/../certs/
 config.dir=${root.dir}/../config/
 build.dir=${root.dir}/../build
 sts.stage.dir=${build.dir}/sts_stage</pre>
<pre>sts-wls-host=localhost
 sts-wls-port=6001
 sts-wls-server=${sts-wls-host}:${sts-wls-port}
 sts-wls-username=weblogic
 sts-wls-passwd=Welcome1
 sts-wls-target=AdminServer</pre>
<pre># common properties
 sts-sport=6002</pre>
<pre>sts-server-keystore-name=${root.dir}/../certs/oasis.jks</pre>
<pre>sts-server-keystore-pass=password
 sts-serverKey=${sts.stage.dir}/WssIPPrv.pem
 sts-server-cert=${sts.stage.dir}/WssIPCert.pem
 sts-server-alias=WssIPSTS
 sts-server-cert-alias=WssIPSTS
 sts-server-certs-pass=password
 sts-server-key-pass=password
 sts-server-truststore-name=${sts.stage.dir}/cacerts
 sts-server-truststore-pwd=changeit</pre>
<pre>samlStsURL=https://${sts-wls-host}:${sts-sport}/standalonests/SamlSTS</pre>
<pre> 

EchoServiceSAML2.java

package com.saml.example;</pre>
<pre>import weblogic.jws.Policies;
 import weblogic.jws.Policy;
 import javax.jws.WebService;</pre>
<pre>@Policies(
   {
     @Policy(uri = "policy:Wssp1.2-2007-Saml2.0-SenderVouches-Wss1.1-Asymmetric.xml"),
     @Policy(uri = "policy:Wssp1.2-2007-SignBody.xml"),
     @Policy(uri = "policy:Wssp1.2-2007-EncryptBody.xml")
   }
 )</pre>
<pre>@WebService
 public class EchoServiceSAML2 {
   public String echo( String hello){
   System.out.println("Inside EchoServiceSAML2!!!");
     return hello;
   }
 }

build.xml for webservice

</pre>
<pre>
<?xml version="1.0"?> <project name="SenderVouches11" default="all" basedir=".">     <property name="root.dir" value="${basedir}" />     <taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />     <taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />     <taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy" />     <taskdef name="wsdlc" classname="weblogic.wsee.tools.anttasks.WsdlcTask" /></pre>
<pre>    <property file="${basedir}/properties.txt" /></pre>
<pre>    <property name="source.dir" value="${basedir}" />
     <property name="output.dir" value="${basedir}/build" />
     <property name="clientclasses.dir" value="${basedir}/build/client" />
     <property name="clientclassessaml2.dir" value="${basedir}/build/clientsaml2" />
     
     <path id="class.path">
         <pathelement path="${java.class.path}" />
         <pathelement path="${basedir}/build/client" />
         <pathelement path="${basedir}/build/clientsaml2" />
     </path></pre>
<pre>    <target name="all" depends="clean,jwsc,deploy,client" /></pre>
<pre>    <target name="build" depends="clean,jwsc,client" /></pre>
<pre>    <target name="clean">
         <delete dir="${output.dir}" />
     </target></pre>
<pre>    <target name="jwsc">
         <antcall target="jwsc-ws" />
     </target></pre>
<pre>    <target name="jwsc-ws">
         <jwsc srcdir="${source.dir}" destdir="${output.dir}" debug="on" classpath="${class.path}">
             <module contextpath="echoservice" name="echoservice" explode="true">
                 <jws file="EchoService.java" type="JAXWS">
                     <WLHttpTransport serviceUri="EchoService" />
                 </jws>
             </module>
         </jwsc>
        
         <jwsc srcdir="${source.dir}" destdir="${output.dir}" debug="on" classpath="${class.path}">
             <module contextpath="echoservicesaml2" name="echoservicesaml2" explode="true">
                 <jws file="EchoServiceSAML2.java" type="JAXWS">
                     <WLHttpTransport serviceUri="EchoServiceSAML2" />
                 </jws>
             </module>
         </jwsc>
     </target>
     
     <target name="clientgen">
         <mkdir dir="${clientclasses.dir}" />
         <clientgen destdir="${clientclasses.dir}" wsdl="${basedir}/EchoService.wsdl" type="JAXWS" packageName="com.saml.example" />
         <clientgen destdir="${clientclassessaml2.dir}" wsdl="${basedir}/EchoServiceSAML2.wsdl" type="JAXWS" packageName="com.saml.example" />
     </target>
     
     <target name="client">
         <mkdir dir="${clientclasses.dir}" />
         <copy todir="${clientclasses.dir}" overwrite="true">
             <fileset dir="${certs.dir}" includes="*" />
         </copy>
         <antcall target="clientgen" />
         <javac debug="true" srcdir="${source.dir}" destdir="${clientclasses.dir}">
             <classpath refid="class.path" />
             <include name="EchoServicePortClient.java" />
         </javac>
         <javac debug="true" srcdir="${source.dir}" destdir="${clientclassessaml2.dir}">
             <classpath refid="class.path" />
             <include name="EchoServiceSAML2PortClient.java" />
         </javac>
     </target>
</pre>
<pre>    <target name="deploy">
         <antcall target="deploy-ws" />
     </target></pre>
<pre>    <target name="deploy-ws">
         <wldeploy action="deploy" source="${output.dir}/echoservice" user="${wls-username}" password="${wls-passwd}" verbose="false" adminurl="t3://${wls-server}" debug="false" targets="${wls-target}" />
         <wldeploy action="deploy" source="${output.dir}/echoservicesaml2" user="${wls-username}" password="${wls-passwd}" verbose="false" adminurl="t3://${wls-server}" debug="false" targets="${wls-target}" />
     </target></pre>
<pre>    <target name="undeploy">
         <property name="wls-admin-server" value="${wls-server}" />
         <wldeploy action="undeploy" name="echoservice" user="${wls-username}" password="${wls-passwd}" verbose="false" adminurl="t3://${wls-server}" debug="false" targets="${wls-target}" />
         <wldeploy action="undeploy" name="echoservicesaml2" user="${wls-username}" password="${wls-passwd}" verbose="false" adminurl="t3://${wls-server}" debug="false" targets="${wls-target}" />
     </target>
     
     <target name="run">
         <java classname="com.saml.example.client.EchoServicePortClient" fork="true">
             <classpath refid="class.path" />
             <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8453
               ${extra-server-verbose}
               -Dweblogic.wsee.verbose=*,!weblogic.wsee.connection.soap.SoapConnectionMessage" /></pre>
<pre>        </java>
     </target>
     
     <target name="runsaml2">
         <java classname="com.saml.example.client.EchoServiceSAML2PortClient" fork="true">
             <classpath refid="class.path" />
             <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8453
               ${extra-server-verbose}
               -Dweblogic.wsee.verbose=*,!weblogic.wsee.connection.soap.SoapConnectionMessage" /></pre>
<pre>        </java>
     </target>
     
     <property name="extra-server-verbose" value="
       -Dweblogic.xml.crypto.encrypt.verbose=true
       -Dweblogic.xml.crypto.dsig.debug=true
       -Dweblogic.xml.crypto.dsig.verbose=true
       -Dweblogic.wsee.security.debug=true
       -Dweblogic.wsee.security.verbose=true
       -Dweblogic.xml.crypto.wss.debug=true
       -Dweblogic.xml.crypto.wss.verbose=true
       -Dweblogic.xml.crypto.keyinfo.debug=true
       -Dweblogic.xml.crypto.keyinfo.verbose=true
       -Dweblogic.xml.crypto.dsig.debug=true
       -Dweblogic.xml.crypto.dsig.verbose=true
       -Dweblogic.xml.crypto.encrypt.debug=true
       -Dweblogic.xml.crypto.encrypt.verbose=true
       -Dweblogic.debug.DebugSecuritySAMLService=true
       -Dweblogic.debug.DebugSecuritySAMLCredMap=true
       -Dweblogic.debug.DebugSecuritySAMLAtn=true
       -Dweblogic.debug.DebugSecuritySAMLLib=true
       -Dweblogic.debug.DebugSecuritySAML2Service=true
       -Dweblogic.debug.DebugSecuritySAML2CredMap=true
       -Dweblogic.debug.DebugSecuritySAML2Atn=true
       -Dweblogic.debug.DebugSecuritySAML2Lib=true
       -Dweblogic.debug.DebugSecurityCredMap=true
       -Dweblogic.log.StdoutSeverity=Debug" />
 </project>

properties.txt for webservice

certs.dir=${root.dir}/../certs/ config.dir=${root.dir}/../config/ build.dir=${root.dir}/../build</pre>
<pre>wls-host=localhost
 wls-port=7001
 wls-server=${wls-host}:${wls-port}
 wls-username=weblogic
 wls-passwd=Welcome1
 wls-target=AdminServer

EchoServicePortClient.java

package com.saml.example.client;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceRef;
import weblogic.security.SSL.TrustManager;
import weblogic.wsee.message.WlMessageContext;
import weblogic.wsee.security.bst.ClientBSTCredentialProvider;
import weblogic.wsee.security.saml.SAMLTrustCredentialProvider;
import weblogic.wsee.security.unt.ClientUNTCredentialProvider;
import weblogic.xml.crypto.wss.provider.CredentialProvider;
import com.saml.example.*;
import weblogic.wsee.security.saml.*;
import weblogic.wsee.jaxrpc.WLStub;
import weblogic.jws.Policies;
import weblogic.jws.Policy;
import weblogic.xml.crypto.wss.WSSecurityContext;
import weblogic.security.principal.WLSPrincipal;
import weblogic.wsee.jaxrpc.WLStub;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.util.*;
import java.security.Principal;
import javax.security.auth.Subject;
public class EchoServiceSAML2PortClient {
     @WebServiceRef
     private static EchoServiceSAML2Service echoServiceService;
    private static String stsUntPolicy = "&lt;?xml version=\"1.0\"?&gt;\n"
             + "&lt;wsp:Policy\n"
             + "  xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\"\n"
             + "  xmlns:sp=\"http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702\"\n"
             + "  &gt;\n"
             + "  &lt;sp:TransportBinding&gt;\n"
             + "    &lt;wsp:Policy&gt;\n"
             + "      &lt;sp:TransportToken&gt;\n"
             + "        &lt;wsp:Policy&gt;\n"
             + "          &lt;sp:HttpsToken/&gt;\n"
             + "        &lt;/wsp:Policy&gt;\n"
             + "      &lt;/sp:TransportToken&gt;\n"
             + "      &lt;sp:AlgorithmSuite&gt;\n"
             + "        &lt;wsp:Policy&gt;\n"
             + "          &lt;sp:Basic256/&gt;\n"
             + "        &lt;/wsp:Policy&gt;\n"
             + "      &lt;/sp:AlgorithmSuite&gt;\n"
             + "      &lt;sp:Layout&gt;\n"
             + "        &lt;wsp:Policy&gt;\n"
             + "          &lt;sp:Lax/&gt;\n"
             + "        &lt;/wsp:Policy&gt;\n"
             + "      &lt;/sp:Layout&gt;\n"
             + "      &lt;sp:IncludeTimestamp/&gt;\n"
             + "    &lt;/wsp:Policy&gt;\n"
             + "  &lt;/sp:TransportBinding&gt;\n"
             + "  &lt;sp:SupportingTokens&gt;\n"
             + "    &lt;wsp:Policy&gt;\n"
             + "      &lt;sp:UsernameToken\n"
             + "        sp:IncludeToken=\"http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient\"&gt;\n"
             + "        &lt;wsp:Policy&gt;\n" + "          &lt;sp:WssUsernameToken10/&gt;\n"
             + "        &lt;/wsp:Policy&gt;\n" + "      &lt;/sp:UsernameToken&gt;\n"
             + "    &lt;/wsp:Policy&gt;\n" + "  &lt;/sp:SupportingTokens&gt;\n"
             + "&lt;/wsp:Policy&gt;";
    public static void main(String[] args) {
         System.setProperty(
                 "com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump",
                 "true");
         try {
            String wsURL = "http://HYD-69ZRV01-L:7001/echoservicesaml2/EchoServiceSAML2?WSDL";
            echoServiceService = new EchoServiceSAML2Service(new URL(wsURL),
                     new QName("http://example.saml.com/",
                             "EchoServiceSAML2Service"));
             EchoServiceSAML2 echoService = echoServiceService.getEchoServiceSAML2Port();
            System
                     .setProperty("javax.net.ssl.trustStore",
                             "F:/Oracle/Middleware/user_projects/domains/WebserviceDomain/certs/cacerts");
            Map&lt;String, Object&gt; requestContext = ((BindingProvider) echoService)
                     .getRequestContext();
            List&lt;CredentialProvider&gt; credList = new ArrayList&lt;CredentialProvider&gt;();
            // Add the necessary credential providers to the list
             InputStream policy = new ByteArrayInputStream(stsUntPolicy
                     .getBytes("UTF-8"));
             requestContext.put(WlMessageContext.WST_BOOT_STRAP_POLICY, policy);
            String stsURL = "https://HYD-69ZRV01-L:6002/standalonests/SamlSTS";
            requestContext.put(WlMessageContext.STS_ENDPOINT_ADDRESS_PROPERTY,
                     stsURL);
             requestContext.put(WSSecurityContext.TRUST_MANAGER,
                     new TrustManager() {
                         public boolean certificateCallback(
                                 X509Certificate[] chain, int validateErr) {
                             // need to validate if the server cert can be
                             // trusted
                             return true;
                         }
                     });
            requestContext.put(WLStub.SAML_ATTRIBUTE_ONLY, "False");
             credList.add(new SAMLTrustCredentialProvider());
             credList.add(new MySAMLCredentialProvider1());
            String username = "Alice";
             String password = "Interop1";
             credList.add(new ClientUNTCredentialProvider(username.getBytes(),
                     password.getBytes()));
            // ClientBSTCredentialProvider
             String defaultClientcert = "F:/Oracle/Middleware/user_projects/domains/WebserviceDomain/certs/Alice.cer";
             String clientcert = System.getProperty("target.clientcert",
                     defaultClientcert);
             String defaultClientkey = "F:/Oracle/Middleware/user_projects/domains/WebserviceDomain/certs/Alice.prv";
             String clientkey = System.getProperty("target.clientkey",
                     defaultClientkey);
            String defaultServerCert = "F:/Oracle/Middleware/user_projects/domains/WebserviceDomain/certs/Bob.cer";
             String serverCert = System.getProperty("target.serverCert",
                     defaultServerCert);
            credList.add(new ClientBSTCredentialProvider(clientcert, clientkey,
                     serverCert));
            requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST,
                     credList);
            // Add your code to call the desired methods.
             System.out.println(echoService.echo("Hello SAML2"));
        } catch (Exception ex) {
             ex.printStackTrace();
         }
     }
     /**
    * This Credntail Provider is for SMAL 2.0 Sender Vouches
    */
  private static class MySAMLCredentialProvider1 extends SAML2CredentialProvider {
    public SAMLAttributeStatementData getSAMLAttributeData(Subject subject) {
      System.out.println(" Prividing SAML Attributes from MySAMLCredentialProvider1 for Subject =" + subject);
       // There are four types of attributes in this test
      SAMLAttributeStatementData attributes = new SAMLAttributeStatementDataImpl();
      String xmlns = "www.oracle.com/webservices/saml/test";
      // 1. The attribute without value
       SAMLAttributeData attribute1 = new SAMLAttributeDataImpl();
       attribute1.setAttributeName("test.no.value.attribute");
       // Friendly name is optional. It is set in this example.
       attribute1.setAttributeFriendlyName("Type 1 - No Value");
       attribute1.setAttributeNameSpace(xmlns);
       attributes.addAttributeInfo(attribute1);
      // 2. Static attribute that has static value
       SAMLAttributeData attribute2 = new SAMLAttributeDataImpl();
       attribute2.setAttributeName("test.static.attribute");
       attribute2.setAttributeFriendlyName("Type 2 - Static Attribute");
       attribute2.setAttributeNameSpace(xmlns);
       attribute2.addAttributeValue("static.attribute.value");
       attributes.addAttributeInfo(attribute2);
      // 3. Subjust dependent attributes
       SAMLAttributeData attribute3 = new SAMLAttributeDataImpl();
       attribute3.setAttributeName("test.subject.dependent.attribute");
       attribute3.setAttributeFriendlyName("Type 3 - Subject Dependent Attribute");
       attribute3.setAttributeNameSpace(xmlns);
       if (hasUser("Alice", subject)) {
         attribute3.addAttributeValue("Alice A");
       } else if (hasUser("Bob", subject)) {
         attribute3.addAttributeValue("Bob B");
       } else {
         attribute3.addAttributeValue("Hacker X");
       }
       attributes.addAttributeInfo(attribute3);
      // 4. Multiple value attributes
       SAMLAttributeData attribute4 = new SAMLAttributeDataImpl();
       attribute4.setAttributeName("test.multi.value.attribute");
       attribute4.setAttributeFriendlyName("Type 4 - Multi-Value Attribute");
       attribute4.setAttributeNameSpace(xmlns);
       if (hasUser("Alice", subject)) {
         attribute4.addAttributeValue("Team Lead");
         attribute4.addAttributeValue("Programmer");
       } else if (hasUser("Bob", subject)) {
         attribute4.addAttributeValue("System Admin");
         attribute4.addAttributeValue("QA");
       } else {
         attribute4.addAttributeValue("Hacker");
         attribute4.addAttributeValue("meber of unkown");
       }
       attributes.addAttributeInfo(attribute4);
       return attributes;
     }
    private static boolean hasUser(String user, Subject subject) {
       if (null == user || null == subject) {
         return false;
       }
       Set principals = subject.getPrincipals();
       if (null == principals || principals.isEmpty()) {
         return false;
       }
       for (Iterator it = principals.iterator(); it.hasNext();) {
         Object obj = it.next();
         if (obj instanceof Principal) {
           Principal p = (Principal) obj;
           if (user.equals(p.getName())) {
             return true;
           }
         } else if (obj instanceof WLSPrincipal) {
           WLSPrincipal principal = (WLSPrincipal) obj;
           if (user.equals(principal.getName())) {
             return true;
           }
         }
       }
       return false;
     }
   }
 }

Java Sample Client – Oracle Access Manager API – OAMAuthnCookie Validator

June 4, 2016 3 comments

Here is a sample Java Client code that validates the OAMAuthnCookie token. It performs 2 steps:

  1. Checks whether passed in OAMAuthnCookie token is valid and not expired
  2. Retrieves username for given OAMAuthnCookie token

OAMAuthnCookie can be found inside cookies of a browser. In the below Java client you need to put the value of OAMAuthnCookie inside the getUserNameFromToken() sessionToken.

 

package com.oam.test;

import java.util.Hashtable;

import oracle.security.am.asdk.AccessClient;
import oracle.security.am.asdk.AccessException;
import oracle.security.am.asdk.AuthenticationScheme;
import oracle.security.am.asdk.ResourceRequest;
import oracle.security.am.asdk.UserSession;

/**
 * This class is a sample to extract OAM Session cookie for authenticated user
 * and to extract userid for given OAM Session token
 * 
 * @author Karun
 * 
 */
public class OAMSessionCookieValidate {
    public static final String ms_resource = "//<STS IP>:7777/atest/index.jsp";

    public static final String ms_protocol = "http";
    public static final String ms_method = "GET";
    public static final String ms_login = "weblogic";
    public static final String ms_passwd = "<password>";
    public static final String m_configLocation = "D:\\Installables\\ofm_oam_sdk_generic_11.1.2.2.0_disk1_1of1";

    public static void main(String args[]) {
        AccessClient ac = null;
        try {
            System.out.println("Entered Try..");
            ac = AccessClient.createDefaultInstance(m_configLocation,
                    AccessClient.CompatibilityMode.OAM_10G);

            // ac = AccessClient.createDefaultInstance(m_configLocation);
            System.out.println("Created Default Instance.." + ac);
            ResourceRequest rrq = new ResourceRequest(ms_protocol, ms_resource,
                    ms_method);
            System.out.println("Created Resource Request object.." + rrq);
            String sessionToken = null;
            if (rrq.isProtected()) {
                System.out.println("Resource is protected.");
                AuthenticationScheme authnScheme = new AuthenticationScheme(rrq);
                System.out.println("Athentication Scheme:"
                        + authnScheme.isBasic());
                if (authnScheme.isBasic()) {
                    System.out.println("Basic Authentication Scheme.");
                    Hashtable creds = new Hashtable();
                    creds.put("userid", ms_login);
                    creds.put("password", ms_passwd);
                    UserSession session = new UserSession(rrq, creds);
                    if (session.getStatus() == UserSession.LOGGEDIN) {
                        if (session.isAuthorized(rrq)) {
                            System.out
                                    .println("User is logged in and authorized for the"
                                            + "request at level "
                                            + session.getLevel());
                            System.out.println("User Identity:"
                                    + session.getUserIdentity());
                            System.out
                                    .println("Status: " + session.getStatus());
                            System.out.println("Start time:"
                                    + session.getStartTime());
                            sessionToken = session.getSessionToken();
                            System.out.println("Session Token:" + sessionToken);
                            System.out.println("Last Usetime:"
                                    + session.getLastUseTime());

                            String userName = getUserNameFromToken(sessionToken);
                            System.out.println("Username*****=" + userName);

                        } else {
                            System.out
                                    .println("User is logged in but NOT authorized");
                        }
                        // user can be loggedout by calling logoff method on the
                        // session object
                    } else {
                        System.out.println("User is NOT logged in");
                    }
                } else {
                    System.out.println("non-Basic Authentication Scheme.");
                }
            } else {
                System.out.println("Resource is NOT protected.");
            }
        } catch (AccessException ae) {
            System.out.println("Access Exception: " + ae.getCause());
            ae.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ac != null)
            ac.shutdown();
    }

    public static String getUserNameFromToken(String sessionToken)
            throws AccessException {
        String userName = null;
        sessionToken = "rHt95P4PrMP2k%2FG%2BxydisWbDdtbjKoIjHgL7sRVtIwDy6DBbP7WSzyrHxQs%2FIYfNe7QTXw%2Fruw6873smWJppdy8ooAAIqcJLj7BocSlV%2FUBdXVUhJWaySY%2BOrbRMaolMpe6lzwtOcsvSpxZ6fMdH976JYlsYJapNr%2FgC7HvONAUJD%2BwPwryFXrQ6%2F0zqrxsPGGztiPy%2BbC9N%2BwcDbPmZUzcfQksmF6%2BPRvZ4Gbi%2FDUKuxz8kBPYIOphaLIZ2BkWTo6kXwOuXMDP4mwF25%2FCHECk03uNZVOTYza%2BBOmzl52JykyABehI0M1xvLjutJ0NBm0Oz9fUZzKGByb31kNYMD2ltQfjKS271HBh37NlLa%2FQ42oTRDtg2HZQUgeyruRmpdSSDlLzq2NPEDB8oHbxADBKLOzrRWkdDEGv63TVb2LLS5LyCGUwRiPqbPHFz1hWoGNS34uoW1Lh1rglWEcLH%2F7Pc9HSCNDI2D9IGw57vKopbw2FIPl64wbOt8TY06uYz";
        UserSession session = new UserSession(sessionToken);
        userName = session.getUserIdentity();
        if (userName != null) {
            userName = userName.substring(userName.indexOf("uid=") + 4,
                    userName.indexOf(","));
        }
        return userName;
    }
}

SAML2 Assertion is not yet valid (NotBefore condition)

June 4, 2016 1 comment

My current setup:

Oracle STS is running on Machine 1 and Oracle Weblogic Web service is running on Machine 2

When I wrote a client to invoke SAML2 token from STS on Machine 1 and use the token to call SAML2 web service on weblogic running on Machine 2. My client constantly kept throwing following error:

<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <found idp partner with targetResource: /echoservicesaml2/EchoServiceSAML2>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: Start verify assertion signature>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: The assertion is signed.>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: End verify assertion signature>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: Start verify assertion attributes>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: End verify assertion attributes>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: Start verify assertion issuer>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: End verify assertion issuer>
<16 Jun, 2014 5:48:56 PM IST> <Debug> <SecuritySAML2Atn> <BEA-000000> <SAML2Assert: Start verify assertion conditions>
<WSEE:12>Exception while asserting identity: javax.security.auth.login.LoginException: [Security:090377]Identity Assertion Failed, weblogic.security.spi.IdentityAssertionException: [Security:090377]Identity Assertion Failed, weblogic.security.spi.IdentityAssertionException: [Security:096537]Assertion is not yet valid (NotBefore condition).<CSSUtils.assertIdentity:429>

Root Cause:
Oracle STS returned token appropriately, but the request fails on the weblogic server.

After a bit of fight we could figure out that the Machine 2 time is 2 minutes behind Machine 1. When we adjusted the times (synced) of Machine 1 and Machine 2 things worked smoothly there after.

Hope this tip helps some one there.

About SAML (Security Assertion Markup Language)


Starting this post I would like to post series of posts on SAML security. I’ve come across lot of folks who are fascinated by this buzz word but knew very little about what it does in real world.

One can consider this series as a tutorial and step-by-step guide to developing SAML based webservices.

 

http://docs.oracle.com/cd/E12839_01/web.1111/e13710/archtect.htm

  • Sender-Vouches – The asserting party (different from the subject) vouches for the verification of the subject. The receiver must have a trust relationship with the asserting party.
  • Holder-of-Key – The purpose of SAML token with “holder-of-key” subject confirmation is to allow the subject to use an X.509 certificate that may not be trusted by the receiver to protect the integrity of the request messages.Conceptually, the asserting party inserts an X.509 public certificate (or other key info) into a SAML assertion. (More correctly, the asserting party binds a key to a subject.) In order to protect this embedded certificate, the SAML assertion itself must be signed by the asserting entity. For WebLogic Server, the Web Service client signs the SAML assertion with its private key. That is, the signature on the assertion is the signature of the SAML authority, and is not based on the certificate contained in, or identified by, the assertion.
  • Bearer – The subject of the assertion is the bearer of the assertion, subject to optional constraints on confirmation using attributes that may be included in the<SubjectConfirmationData>element of the assertion.

As per http://dulanja.blogspot.in/2013/01/saml-subject-confirmation-methods.html

Bearer

This is actually not a confirmation method – means subject confirmation is not needed! The RP simply trusts whoever brings the token!

Holder of Key (HoK)
1. STS includes the public key of the client, inside the security token and signs it.
2. Then before sending, client itself signs the request.
3. When the RP receives it, it first validates STS signature and then validates client’s signature with the public key embedded inside the token.

Sender Vouches
1. Rather than authenticating with the STS, here, Client authenticates with an intermediate service.
2. The intermediary gets the security token from the STS.
3. Then it signs the request and sends to the RP.
4. RP trusts both the intermediary and the STS. So, it validates both of them.

Categories: SAML

Playing with Docker & Docker CLI


root@karun-1:/home/paas# man docker-run
root@karun-1:/home/paas#


root@karun-1:/home/paas# sudo docker run -i -t ubuntu /bin/bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
487bffc61de6: Pull complete
acb8e44f43fa: Pull complete
202e40f8bb3a: Pull complete
b0c2dfa2701f: Pull complete
17b6a9e179d7: Pull complete
Digest: sha256:5718d664299eb1db14d87db7bfa6945b28879a67b74f36da3e34f5914866b71c
Status: Downloaded newer image for ubuntu:latest

# Note: -i STDIN open from the container, -t above provides a putty option to connect to the container through ssh. In above command we've asked docker to run /bin/bash command in the container. This presents container's shell as below.

root@9426fd62a696:/#

Note: Here 9426fd62a696 is like a hostname to the container.

root@9426fd62a696:/# hostname
9426fd62a696

root@9426fd62a696:/# uname -a
Linux 9426fd62a696 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
root@9426fd62a696:/#

root@9426fd62a696:/# cat /etc/hosts
172.17.0.3 9426fd62a696
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

root@9426fd62a696:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18236 2008 ? Ss 17:43 0:00 /bin/bash
root 31 0.0 0.0 34416 1464 ? R+ 20:32 0:00 ps -aux
root@9426fd62a696:/#

Note: If you are behind firewall or a proxy set environment variage http_proxy and https_proxy before firing below command

root@9426fd62a696:/# apt-get update && apt-get install vim
Get:1 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
Get:2 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [94.5 kB]
Get:3 http://archive.ubuntu.com/ubuntu xenial-security InRelease [93.3 kB]
Get:4 http://archive.ubuntu.com/ubuntu xenial/main Sources [1103 kB]
Get:5 http://archive.ubuntu.com/ubuntu xenial/restricted Sources [5179 B]

root@9426fd62a696:/# exit
exit

# Note: This exits the container, but container is still running ...
root@karun-1:/home/paas# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9426fd62a696 ubuntu "/bin/bash" 3 hours ago Exited (127) About a minute ago hungry_gates


root@karun-1:/home/paas# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9426fd62a696 ubuntu "/bin/bash" 3 hours ago Exited (127) 2 minutes ago hungry_gates


# Note: -l means last container's status, -a show all running/stopped/exited containers, none means only running containers

# To create containers with your own naming convention...
root@karun-1:/home/paas# sudo docker run --name karun_container -i -t ubuntu /bin/bash
root@521cfbc8bf97:/#

root@karun-1:/home/paas# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
521cfbc8bf97 ubuntu "/bin/bash" About a minute ago Exited (0) 6 seconds ago karun_container
root@karun-1:/home/paas#

# to stop/start/restart karun_container
root@karun-1:/home/paas# sudo docker stop 521cfbc8bf97
521cfbc8bf97
root@karun-1:/home/paas# sudo docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
521cfbc8bf97 ubuntu "/bin/bash" 4 minutes ago Exited (0) 4 seconds ago karun_container
root@karun-1:/home/paas# sudo docker start 521cfbc8bf97
521cfbc8bf97
root@karun-1:/home/paas# sudo docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
521cfbc8bf97 ubuntu "/bin/bash" 14 minutes ago Up 4 seconds karun_container
root@karun-1:/home/paas# sudo docker restart 521cfbc8bf97
521cfbc8bf97
root@karun-1:/home/paas# sudo docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
521cfbc8bf97 ubuntu "/bin/bash" 14 minutes ago Up 2 seconds karun_container


# to attach a container anytime...to bring back to docker's bash command prompt (Hit Enter twice)
root@karun-1:/home/paas# sudo docker attach 521cfbc8bf97
root@521cfbc8bf97:/#
root@521cfbc8bf97:/#


# Again on exit container goes down. Hence above container is not ideal for running applications, let's create a daemonized container for running applications and have an interactive session in a way are longer running containers

root@karun-1:/home/paas# sudo docker run --name karun_daemon -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"
561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4

# -d flag to tell Docker to detaich the container to the background. Above while loop continues till container is stopped or the process stops.

root@karun-1:/home/paas# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
561787e6a699 ubuntu "/bin/sh -c 'while tr" About a minute ago Up About a minute karun_daemon
521cfbc8bf97 ubuntu "/bin/bash" 55 minutes ago Up 2 minutes karun_container

# check the logs of container now... -f flag is like tail -f command
root@karun-1:/home/paas# sudo docker logs -f karun_daemon
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world

root@karun-1:/home/paas# sudo docker logs --tail 10 karun_daemon
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
root@karun-1:/home/paas#

# For timestamp
root@karun-1:/home/paas# sudo docker logs -ft karun_daemon
2016-05-13T21:49:18.608885021Z hello world
2016-05-13T21:49:19.607061776Z hello world
2016-05-13T21:49:20.608568951Z hello world
2016-05-13T21:49:21.609976161Z hello world
2016-05-13T21:49:22.611418756Z hello world
2016-05-13T21:49:23.613123250Z hello world
2016-05-13T21:49:24.614493112Z hello world
2016-05-13T21:49:25.615742071Z hello world

# To inspect processes running inside the container
root@karun-1:/home/paas# sudo docker top karun_daemon
UID PID PPID C STIME TTY TIME CMD
root 29614 867 0 05:49 ? 00:00:00 /bin/sh -c while true; do echo hello world; sleep 1; done
root 31063 29614 0 06:06 ? 00:00:00 sleep 1

# For checking stats of the docker containers
root@karun-1:/home/paas# sudo docker stats karun_daemon
CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
karun_daemon 0.10% 454.7 kB / 8.373 GB 0.01% 648 B / 648 B 0 B / 0 B

# This creates a new file in docker container karun_daemon
root@karun-1:/home/paas# sudo docker exec -d karun_daemon touch /etc/new_config_file

# Interactive command to connect or open a shell inside our karun_daemon
# -t is to create TTY and -i is to capture STDIN for executed process
# This creates a new bash session inside the container karun_daemon
root@karun-1:/home/paas# sudo docker exec -t -i karun_daemon /bin/bash
root@561787e6a699:/#

### since it's an interactive container, up on exit you can see that docker container didn't shutdown.
# To shutdown explicity you need to issue sudo docker shutdown <id> command
root@karun-1:/home/paas# sudo docker exec -t -i karun_daemon /bin/bash
root@561787e6a699:/# exit
exit
root@karun-1:/home/paas# sudo docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
561787e6a699 ubuntu "/bin/sh -c 'while tr" 40 minutes ago Up 40 minutes karun_daemon

# For auto start of docker always
root@karun-1:/home/paas# sudo docker run --restart=always --name karun-daemon -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"

# Restart only on failure a maximum of five time if a non-zero exit code is received
root@karun-1:/home/paas# sudo docker run --restart=on-failure:5 --name karun-daemon -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"

# docker inspect
root@karun-1:/home/paas# sudo docker inspect 561787e6a699
[
{
 "Id": "561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4",
 "Created": "2016-05-13T21:49:18.326489298Z",
 "Path": "/bin/sh",
 "Args": [
 "-c",
 "while true; do echo hello world; sleep 1; done"
 ],
 "State": {
 "Status": "running",
 "Running": true,
 "Paused": false,
 "Restarting": false,
 "OOMKilled": false,
 "Dead": false,
 "Pid": 29614,
 "ExitCode": 0,
 "Error": "",
 "StartedAt": "2016-05-13T21:49:18.605583292Z",
 "FinishedAt": "0001-01-01T00:00:00Z"
 },
 "Image": "17b6a9e179d7cb99d2f27978ca3ac6cf23eefb23201472ed54f5d9fb94894922",
 "ResolvConfPath": "/var/lib/docker/containers/561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4/resolv.conf",
 "HostnamePath": "/var/lib/docker/containers/561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4/hostname",
 "HostsPath": "/var/lib/docker/containers/561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4/hosts",
 "LogPath": "/var/lib/docker/containers/561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4/561787e6a6992434ffe4551a1d5f47a6debdb08377544d68b406b667ed3e37b4-json.log",
 "Name": "/karun_daemon",
 "RestartCount": 0,
 "Driver": "aufs",
 "ExecDriver": "native-0.2",
 "MountLabel": "",
 "ProcessLabel": "",
 "AppArmorProfile": "",
 "ExecIDs": null,
 "HostConfig": {
 "Binds": null,
 "ContainerIDFile": "",
 "LxcConf": [],
 "Memory": 0,
 "MemoryReservation": 0,
 "MemorySwap": 0,
 "KernelMemory": 0,
 "CpuShares": 0,
 "CpuPeriod": 0,
 "CpusetCpus": "",
 "CpusetMems": "",
 "CpuQuota": 0,
 "BlkioWeight": 0,
 "OomKillDisable": false,
 "MemorySwappiness": -1,
 "Privileged": false,
 "PortBindings": {},
 "Links": null,
 "PublishAllPorts": false,
 "Dns": [],
 "DnsOptions": [],
 "DnsSearch": [],
 "ExtraHosts": null,
 "VolumesFrom": null,
 "Devices": [],
 "NetworkMode": "default",
 "IpcMode": "",
 "PidMode": "",
 "UTSMode": "",
 "CapAdd": null,
 "CapDrop": null,
 "GroupAdd": null,
 "RestartPolicy": {
 "Name": "no",
 "MaximumRetryCount": 0
 },
 "SecurityOpt": null,
 "ReadonlyRootfs": false,
 "Ulimits": null,
 "LogConfig": {
 "Type": "json-file",
 "Config": {}
 },
 "CgroupParent": "",
 "ConsoleSize": [
 0,
 0
 ],
 "VolumeDriver": ""
 },
 "GraphDriver": {
 "Name": "aufs",
 "Data": null
 },
 "Mounts": [],
 "Config": {
 "Hostname": "561787e6a699",
 "Domainname": "",
 "User": "",
 "AttachStdin": false,
 "AttachStdout": false,
 "AttachStderr": false,
 "Tty": false,
 "OpenStdin": false,
 "StdinOnce": false,
 "Env": [],
 "Cmd": [
 "/bin/sh",
 "-c",
 "while true; do echo hello world; sleep 1; done"
 ],
 "Image": "ubuntu",
 "Volumes": null,
 "WorkingDir": "",
 "Entrypoint": null,
 "OnBuild": null,
 "Labels": {},
 "StopSignal": "SIGTERM"
 },
 "NetworkSettings": {
 "Bridge": "",
 "SandboxID": "35851c5605d975eb3f5c2fe04d8cea1f61e3d97e2cda84bba975218c41cbde8d",
 "HairpinMode": false,
 "LinkLocalIPv6Address": "",
 "LinkLocalIPv6PrefixLen": 0,
 "Ports": {},
 "SandboxKey": "/var/run/docker/netns/35851c5605d9",
 "SecondaryIPAddresses": null,
 "SecondaryIPv6Addresses": null,
 "EndpointID": "b05b3e5cb956298308212a1e3168352e780550c21c3281347040994ff6391edb",
 "Gateway": "172.17.0.1",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "IPAddress": "172.17.0.4",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "MacAddress": "02:42:ac:11:00:04",
 "Networks": {
 "bridge": {
 "EndpointID": "b05b3e5cb956298308212a1e3168352e780550c21c3281347040994ff6391edb",
 "Gateway": "172.17.0.1",
 "IPAddress": "172.17.0.4",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "MacAddress": "02:42:ac:11:00:04"
 }
 }
 }
}
]

# docker inspect formatting
root@karun-1:/home/paas# sudo docker inspect --format '{{.NetworkSettings.IPAddress}}' karun_daemon
172.17.0.4

root@karun-1:/home/paas# sudo docker inspect --format '{{.Name}} {{.State.Running}}' karun_daemon
/karun_daemon true

# to delete all docker containers
$ sudo docker rm 'sudo docker ps -a -q'

Categories: General, Security Tags: ,