blob: bae7aee7aa8d9f10d8fd942517ba2be9efdb3893 [file] [log] [blame]
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../.resources/report.css" type="text/css"/><link rel="shortcut icon" href="../.resources/report.gif" type="image/gif"/><title>RampartUtil.java</title><link rel="stylesheet" href="../.resources/prettify.css" type="text/css"/><script type="text/javascript" src="../.resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../.sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">Coverage Report</a> &gt; <a href="index.source.html" class="el_package">org.apache.rampart.util</a> &gt; <span class="el_source">RampartUtil.java</span></div><h1>RampartUtil.java</h1><pre class="source lang-java linenums">/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rampart.util;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.axiom.soap.*;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.dataretrieval.DRConstants;
import org.apache.axis2.dataretrieval.client.MexClient;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.mex.MexConstants;
import org.apache.axis2.mex.MexException;
import org.apache.axis2.mex.om.Metadata;
import org.apache.axis2.mex.om.MetadataReference;
import org.apache.axis2.mex.om.MetadataSection;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.Token;
import org.apache.rahas.TrustException;
import org.apache.rahas.TrustUtil;
import org.apache.rahas.client.STSClient;
import org.apache.rampart.PolicyBasedResultsValidator;
import org.apache.rampart.PolicyValidatorCallbackHandler;
import org.apache.rampart.RampartConfigCallbackHandler;
import org.apache.rampart.RampartConstants;
import org.apache.rampart.RampartException;
import org.apache.rampart.RampartMessageData;
import org.apache.rampart.policy.RampartPolicyData;
import org.apache.rampart.policy.SupportingPolicyData;
import org.apache.rampart.policy.model.CryptoConfig;
import org.apache.rampart.policy.model.RampartConfig;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.secpolicy.model.*;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.WSSConfig;
import org.apache.ws.security.WSSecurityEngineResult;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.WSUsernameTokenPrincipal;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.conversation.ConversationConstants;
import org.apache.ws.security.conversation.ConversationException;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.handler.WSHandlerResult;
import org.apache.ws.security.message.WSSecBase;
import org.apache.ws.security.message.WSSecEncryptedKey;
import org.apache.ws.security.util.Loader;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.utils.Constants;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.crypto.KeyGenerator;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.xml.namespace.QName;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
<span class="pc bfc" id="L96" title="All 2 branches covered.">public class RampartUtil {</span>
private static final String CRYPTO_PROVIDER = &quot;org.apache.ws.security.crypto.provider&quot;;
<span class="fc" id="L99"> private static Log log = LogFactory.getLog(RampartUtil.class);</span>
<span class="fc" id="L101"> private static Map&lt;String, CachedCrypto&gt; cryptoStore = new ConcurrentHashMap&lt;String, CachedCrypto&gt;();</span>
<span class="nc" id="L103"> private static class CachedCrypto {</span>
private Crypto crypto;
private long creationTime;
<span class="fc" id="L107"> public CachedCrypto(Crypto crypto, long creationTime) {</span>
<span class="fc" id="L108"> this.crypto = crypto;</span>
<span class="fc" id="L109"> this.creationTime = creationTime;</span>
<span class="fc" id="L110"> }</span>
}
public static CallbackHandler getPasswordCB(RampartMessageData rmd) throws RampartException {
<span class="fc" id="L115"> MessageContext msgContext = rmd.getMsgContext();</span>
<span class="fc" id="L116"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="fc" id="L118"> return getPasswordCB(msgContext, rpd);</span>
}
/**
* @param msgContext
* @param rpd
* @return The &lt;code&gt;CallbackHandler&lt;/code&gt; instance
* @throws RampartException
*/
public static CallbackHandler getPasswordCB(MessageContext msgContext, RampartPolicyData rpd) throws RampartException {
CallbackHandler cbHandler;
<span class="pc bpc" id="L131" title="1 of 4 branches missed."> if (rpd.getRampartConfig() != null &amp;&amp; rpd.getRampartConfig().getPwCbClass() != null) {</span>
<span class="fc" id="L133"> String cbHandlerClass = rpd.getRampartConfig().getPwCbClass();</span>
<span class="fc" id="L134"> ClassLoader classLoader = msgContext.getAxisService().getClassLoader();</span>
<span class="pc bpc" id="L136" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L137"> log.debug(&quot;loading class : &quot; + cbHandlerClass);</span>
}
Class cbClass;
try {
<span class="fc" id="L142"> cbClass = Loader.loadClass(classLoader, cbHandlerClass);</span>
<span class="nc" id="L143"> } catch (ClassNotFoundException e) {</span>
<span class="nc" id="L144"> throw new RampartException(&quot;cannotLoadPWCBClass&quot;, </span>
new String[]{cbHandlerClass}, e);
<span class="fc" id="L146"> }</span>
try {
<span class="fc" id="L148"> cbHandler = (CallbackHandler) cbClass.newInstance();</span>
<span class="nc" id="L149"> } catch (java.lang.Exception e) {</span>
<span class="nc" id="L150"> throw new RampartException(&quot;cannotCreatePWCBInstance&quot;,</span>
new String[]{cbHandlerClass}, e);
<span class="fc" id="L152"> }</span>
<span class="fc" id="L153"> } else {</span>
<span class="fc" id="L154"> cbHandler = (CallbackHandler) msgContext.getProperty(</span>
WSHandlerConstants.PW_CALLBACK_REF);
<span class="fc bfc" id="L156" title="All 2 branches covered."> if(cbHandler == null) {</span>
<span class="fc" id="L157"> Parameter param = msgContext.getParameter(</span>
WSHandlerConstants.PW_CALLBACK_REF);
<span class="pc bpc" id="L159" title="1 of 2 branches missed."> if(param != null) {</span>
<span class="nc" id="L160"> cbHandler = (CallbackHandler)param.getValue();</span>
}
}
}
<span class="fc" id="L165"> return cbHandler;</span>
}
/**
* Returns an instance of PolicyValidatorCallbackHandler to be used to validate ws-security results.
*
* @param msgContext {@link MessageContext}
* @param rpd {@link RampartPolicyData}
* @return {@link PolicyValidatorCallbackHandler}
* @throws RampartException RampartException
*/
public static PolicyValidatorCallbackHandler getPolicyValidatorCB(MessageContext msgContext, RampartPolicyData rpd) throws RampartException {
PolicyValidatorCallbackHandler cbHandler;
<span class="pc bpc" id="L180" title="1 of 4 branches missed."> if (rpd.getRampartConfig() != null &amp;&amp; rpd.getRampartConfig().getPolicyValidatorCbClass() != null) {</span>
<span class="nc" id="L182"> String cbHandlerClass = rpd.getRampartConfig().getPolicyValidatorCbClass();</span>
<span class="nc" id="L183"> ClassLoader classLoader = msgContext.getAxisService().getClassLoader();</span>
<span class="nc bnc" id="L185" title="All 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L186"> log.debug(&quot;loading class : &quot; + cbHandlerClass);</span>
}
Class cbClass;
try {
<span class="nc" id="L191"> cbClass = Loader.loadClass(classLoader, cbHandlerClass);</span>
<span class="nc" id="L192"> } catch (ClassNotFoundException e) { </span>
<span class="nc" id="L193"> throw new RampartException(&quot;cannotLoadPolicyValidatorCbClass&quot;, </span>
new String[]{cbHandlerClass}, e);
<span class="nc" id="L195"> }</span>
try {
<span class="nc" id="L197"> cbHandler = (PolicyValidatorCallbackHandler) cbClass.newInstance();</span>
<span class="nc" id="L198"> } catch (java.lang.Exception e) {</span>
<span class="nc" id="L199"> throw new RampartException(&quot;cannotCreatePolicyValidatorCallbackInstance&quot;,</span>
new String[]{cbHandlerClass}, e);
<span class="nc" id="L201"> }</span>
<span class="nc" id="L203"> } else { // Initialise default PolicyValidatorCallbackHandler...</span>
<span class="fc" id="L204"> cbHandler = new PolicyBasedResultsValidator();</span>
}
<span class="fc" id="L207"> return cbHandler;</span>
}
public static RampartConfigCallbackHandler getRampartConfigCallbackHandler(MessageContext msgContext,
RampartPolicyData rpd) throws RampartException {
RampartConfigCallbackHandler rampartConfigCB;
<span class="fc bfc" id="L215" title="All 4 branches covered."> if (rpd.getRampartConfig() != null &amp;&amp; rpd.getRampartConfig().getRampartConfigCbClass() != null) {</span>
<span class="fc" id="L217"> String cbHandlerClass = rpd.getRampartConfig().getRampartConfigCbClass();</span>
<span class="fc" id="L218"> ClassLoader classLoader = msgContext.getAxisService().getClassLoader();</span>
<span class="pc bpc" id="L220" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L221"> log.debug(&quot;loading class : &quot; + cbHandlerClass);</span>
}
Class cbClass;
try {
<span class="fc" id="L226"> cbClass = Loader.loadClass(classLoader, cbHandlerClass);</span>
<span class="nc" id="L227"> } catch (ClassNotFoundException e) {</span>
<span class="nc" id="L228"> throw new RampartException(&quot;cannotLoadRampartConfigCallbackClass&quot;, </span>
new String[]{cbHandlerClass}, e);
<span class="fc" id="L230"> }</span>
try {
<span class="fc" id="L232"> rampartConfigCB = (RampartConfigCallbackHandler) cbClass.newInstance();</span>
<span class="nc" id="L233"> } catch (java.lang.Exception e) {</span>
<span class="nc" id="L234"> throw new RampartException(&quot;cannotCreateRampartConfigCallbackInstance&quot;,</span>
new String[]{cbHandlerClass}, e);
<span class="fc" id="L236"> }</span>
<span class="fc" id="L238"> return rampartConfigCB;</span>
}
<span class="fc" id="L242"> return null;</span>
}
/**
* Perform a callback to get a password.
* &lt;p&gt;
* The called back function gets an indication why to provide a password:
* to produce a UsernameToken, Signature, or a password (key) for a given
* name.
*/
public static WSPasswordCallback performCallback(CallbackHandler cbHandler,
String username,
int doAction)
throws RampartException {
WSPasswordCallback pwCb;
<span class="nc" id="L258"> int reason = 0;</span>
<span class="nc bnc" id="L260" title="All 4 branches missed."> switch (doAction) {</span>
case WSConstants.UT:
case WSConstants.UT_SIGN:
<span class="nc" id="L263"> reason = WSPasswordCallback.USERNAME_TOKEN;</span>
<span class="nc" id="L264"> break;</span>
case WSConstants.SIGN:
<span class="nc" id="L266"> reason = WSPasswordCallback.SIGNATURE;</span>
<span class="nc" id="L267"> break;</span>
case WSConstants.ENCR:
<span class="nc" id="L269"> reason = WSPasswordCallback.KEY_NAME;</span>
break;
}
<span class="nc" id="L272"> pwCb = new WSPasswordCallback(username, reason);</span>
<span class="nc" id="L273"> Callback[] callbacks = new Callback[1];</span>
<span class="nc" id="L274"> callbacks[0] = pwCb;</span>
/*
* Call back the application to get the password
*/
try {
<span class="nc" id="L279"> cbHandler.handle(callbacks);</span>
<span class="nc" id="L280"> } catch (Exception e) {</span>
<span class="nc" id="L281"> throw new RampartException(&quot;pwcbFailed&quot;, e);</span>
<span class="nc" id="L282"> }</span>
<span class="nc" id="L283"> return pwCb;</span>
}
/**
* Create the &lt;code&gt;Crypto&lt;/code&gt; instance for encryption using information
* from the rampart configuration assertion
*
* @param config
* @return The &lt;code&gt;Crypto&lt;/code&gt; instance to be used for encryption
* @throws RampartException
*/
public static Crypto getEncryptionCrypto(RampartConfig config, ClassLoader loader)
throws RampartException {
<span class="fc" id="L297"> log.debug(&quot;Loading encryption crypto&quot;);</span>
<span class="fc" id="L299"> Crypto crypto = null;</span>
<span class="fc bfc" id="L301" title="All 4 branches covered."> if (config != null &amp;&amp; config.getEncrCryptoConfig() != null) {</span>
<span class="fc" id="L302"> CryptoConfig cryptoConfig = config.getEncrCryptoConfig();</span>
<span class="fc" id="L303"> String provider = cryptoConfig.getProvider();</span>
<span class="pc bpc" id="L304" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L305"> log.debug(&quot;Using provider: &quot; + provider);</span>
}
<span class="fc" id="L307"> Properties prop = cryptoConfig.getProp();</span>
<span class="fc" id="L308"> prop.put(CRYPTO_PROVIDER, provider);</span>
<span class="fc" id="L310"> String cryptoKey = null;</span>
<span class="fc" id="L311"> String interval = null;</span>
<span class="pc bpc" id="L312" title="1 of 2 branches missed."> if (cryptoConfig.isCacheEnabled()) {</span>
<span class="pc bpc" id="L313" title="1 of 2 branches missed."> if (cryptoConfig.getCryptoKey() != null) {</span>
<span class="nc" id="L314"> cryptoKey = prop.getProperty(cryptoConfig.getCryptoKey());</span>
<span class="nc" id="L315"> interval = cryptoConfig.getCacheRefreshInterval();</span>
}
<span class="pc bpc" id="L317" title="1 of 2 branches missed."> else if(provider.equals(RampartConstants.MERLIN_CRYPTO_IMPL)){</span>
<span class="fc" id="L318"> cryptoKey = cryptoConfig.getProp().getProperty(RampartConstants.MERLIN_CRYPTO_IMPL_CACHE_KEY);</span>
}
}
<span class="pc bpc" id="L323" title="1 of 2 branches missed."> if (cryptoKey != null) {</span>
// Crypto caching is enabled
<span class="fc" id="L325"> crypto = retrieveCryptoFromCache(cryptoKey.trim() + &quot;#&quot; + provider.trim(), interval);</span>
}
<span class="pc bpc" id="L328" title="1 of 2 branches missed."> if (crypto == null) {</span>
// cache miss
<span class="nc" id="L330"> crypto = createCrypto(prop, loader);</span>
<span class="nc bnc" id="L332" title="All 2 branches missed."> if (cryptoKey != null) {</span>
// Crypto caching is enabled - cache the Crypto object
<span class="nc" id="L334"> cacheCrypto(cryptoKey.trim() + &quot;#&quot; + provider.trim(), crypto);</span>
}
}
<span class="fc" id="L337"> } else {</span>
<span class="fc" id="L338"> log.debug(&quot;Trying the signature crypto info&quot;);</span>
<span class="fc" id="L339"> crypto = getSignatureCrypto(config, loader);</span>
}
<span class="fc" id="L341"> return crypto;</span>
}
private static Crypto createCrypto(Properties properties, ClassLoader classLoader) throws RampartException {
try {
<span class="fc" id="L347"> return CryptoFactory.getInstance(properties, classLoader);</span>
<span class="nc" id="L348"> } catch (WSSecurityException e) {</span>
<span class="nc" id="L349"> log.error(&quot;Error loading crypto properties.&quot;, e);</span>
<span class="nc" id="L350"> throw new RampartException(&quot;cannotCrateCryptoInstance&quot;, e);</span>
}
}
/**
* Create the &lt;code&gt;Crypto&lt;/code&gt; instance for signature using information
* from the rampart configuration assertion
*
* @param config
* @return The &lt;code&gt;Crypto&lt;/code&gt; instance to be used for signature
* @throws RampartException
*/
public static Crypto getSignatureCrypto(RampartConfig config, ClassLoader loader)
throws RampartException {
<span class="fc" id="L365"> log.debug(&quot;Loading Signature crypto&quot;);</span>
<span class="fc" id="L367"> Crypto crypto = null;</span>
<span class="fc bfc" id="L369" title="All 4 branches covered."> if (config != null &amp;&amp; config.getSigCryptoConfig() != null) {</span>
<span class="fc" id="L370"> CryptoConfig cryptoConfig = config.getSigCryptoConfig();</span>
<span class="fc" id="L371"> String provider = cryptoConfig.getProvider();</span>
<span class="pc bpc" id="L372" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L373"> log.debug(&quot;Using provider: &quot; + provider);</span>
}
<span class="fc" id="L375"> Properties prop = cryptoConfig.getProp();</span>
<span class="fc" id="L376"> prop.put(CRYPTO_PROVIDER, provider);</span>
<span class="fc" id="L377"> String cryptoKey = null;</span>
<span class="fc" id="L378"> String interval = null;</span>
<span class="pc bpc" id="L380" title="1 of 2 branches missed."> if (cryptoConfig.isCacheEnabled()) {</span>
<span class="pc bpc" id="L381" title="1 of 2 branches missed."> if (cryptoConfig.getCryptoKey() != null) {</span>
<span class="nc" id="L382"> cryptoKey = prop.getProperty(cryptoConfig.getCryptoKey());</span>
<span class="nc" id="L383"> interval = cryptoConfig.getCacheRefreshInterval();</span>
}
<span class="pc bpc" id="L385" title="1 of 2 branches missed."> else if(provider.equals(RampartConstants.MERLIN_CRYPTO_IMPL)){</span>
<span class="fc" id="L386"> cryptoKey = cryptoConfig.getProp().getProperty(RampartConstants.MERLIN_CRYPTO_IMPL_CACHE_KEY);</span>
}
}
<span class="pc bpc" id="L390" title="1 of 2 branches missed."> if (cryptoKey != null) {</span>
// cache enabled
<span class="fc" id="L392"> crypto = retrieveCryptoFromCache(cryptoKey.trim() + &quot;#&quot; + provider.trim(), interval);</span>
}
<span class="fc bfc" id="L395" title="All 2 branches covered."> if (crypto == null) {</span>
// cache miss
<span class="fc" id="L397"> crypto = createCrypto(prop, loader);</span>
<span class="pc bpc" id="L398" title="1 of 2 branches missed."> if (cryptoKey != null) {</span>
// cache enabled - let's cache
<span class="fc" id="L400"> cacheCrypto(cryptoKey.trim() + &quot;#&quot; + provider.trim(), crypto);</span>
}
}
}
<span class="fc" id="L404"> return crypto;</span>
}
/**
* figureout the key identifier of a give X509Token
* @param token
* @return The key identifier of a give X509Token
* @throws RampartException
*/
public static int getKeyIdentifier(X509Token token) throws RampartException {
<span class="nc bnc" id="L415" title="All 2 branches missed."> if (token.isRequireIssuerSerialReference()) {</span>
<span class="nc" id="L416"> return WSConstants.ISSUER_SERIAL;</span>
<span class="nc bnc" id="L417" title="All 2 branches missed."> } else if (token.isRequireThumbprintReference()) {</span>
<span class="nc" id="L418"> return WSConstants.THUMBPRINT_IDENTIFIER;</span>
<span class="nc bnc" id="L419" title="All 2 branches missed."> } else if (token.isRequireEmbeddedTokenReference()) {</span>
<span class="nc" id="L420"> return WSConstants.BST_DIRECT_REFERENCE;</span>
} else {
<span class="nc" id="L422"> throw new RampartException(</span>
&quot;unknownKeyRefSpeficier&quot;);
}
}
/**
* Process a give issuer address element and return the address.
* @param issuerAddress
* @return The address of an issuer address element
* @throws RampartException If the issuer address element is malformed.
*/
public static String processIssuerAddress(OMElement issuerAddress)
throws RampartException {
<span class="pc bpc" id="L437" title="1 of 2 branches missed."> if(issuerAddress == null){</span>
<span class="nc" id="L438"> throw new RampartException(&quot;invalidIssuerAddress&quot;, </span>
new String[] { &quot;Issuer address null&quot; });
}
<span class="pc bpc" id="L442" title="2 of 4 branches missed."> if(issuerAddress.getText() == null || &quot;&quot;.equals(issuerAddress.getText())) {</span>
<span class="nc" id="L443"> throw new RampartException(&quot;invalidIssuerAddress&quot;, </span>
new String[] { issuerAddress.toString() });
}
<span class="fc" id="L447"> return issuerAddress.getText().trim();</span>
}
/**
* Retrieve policy using metadata reference
* &lt;pre&gt; &amp;lt;wsa:Metadata xmlns:wsa=&quot;http://www.w3.org/2005/08/addressing&quot;&amp;gt;
* &amp;lt;mex:Metadata
* xmlns:mex=&quot;http://schemas.xmlsoap.org/ws/2004/09/mex&quot;
* xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&amp;gt;
* &amp;lt;mex:MetadataSection&amp;gt;
* &amp;lt;mex:MetadataReference&amp;gt;
* &amp;lt;wsa:Address&amp;gt;http://address/of/mex/service&amp;lt;/wsa:Address&amp;gt;
* &amp;lt;/mex:MetadataReference&amp;gt;
* &amp;lt;/mex:MetadataSection&amp;gt;
* &amp;lt;/mex:Metadata&amp;gt;
* &amp;lt;/wsa:Metadata&amp;gt;&lt;/pre&gt;
* @param mex Metadata element
* @return Policy from the mex service
*/
public static Policy getPolicyFromMetadataRef(OMElement mex) throws RampartException {
try {
<span class="fc" id="L469"> Metadata metadata = new Metadata();</span>
<span class="fc" id="L470"> metadata.fromOM(mex.getFirstElement());</span>
<span class="fc" id="L472"> MetadataSection[] metadataSections = metadata.getMetadatSections();</span>
<span class="fc" id="L473"> MetadataReference reference = metadataSections[0].getMetadataReference();</span>
<span class="fc" id="L475"> MexClient serviceClient = new MexClient();</span>
<span class="fc" id="L477"> Options options = serviceClient.getOptions();</span>
<span class="fc" id="L478"> options.setTo(reference.getEPR());</span>
<span class="fc" id="L479"> options.setAction(DRConstants.SPEC.Actions.GET_METADATA_REQUEST);</span>
<span class="fc" id="L481"> OMElement request = serviceClient.setupGetMetadataRequest(</span>
MexConstants.SPEC.DIALECT_TYPE_POLICY,null);
<span class="fc" id="L483"> OMElement result = serviceClient.sendReceive(request);</span>
<span class="fc" id="L485"> metadata.fromOM(result);</span>
<span class="fc" id="L486"> MetadataSection[] mexSecs = metadata.getMetadataSection(MexConstants.SPEC.DIALECT_TYPE_POLICY, null);</span>
<span class="fc" id="L487"> OMElement policyElement = (OMElement) mexSecs[0].getInlineData();</span>
<span class="fc" id="L489"> return PolicyEngine.getPolicy(policyElement);</span>
<span class="nc" id="L492"> } catch (MexException e) {</span>
<span class="nc" id="L493"> throw new RampartException(&quot;Error Retrieving the policy from mex&quot;, e);</span>
<span class="nc" id="L494"> } catch (AxisFault e) {</span>
<span class="nc" id="L495"> throw new RampartException(&quot;Error Retrieving the policy from mex&quot;, e);</span>
}
}
public static Policy addRampartConfig (RampartMessageData rmd, Policy policy) {
<span class="fc" id="L502"> RampartConfig servicRampConf = rmd.getPolicyData().getRampartConfig(); </span>
<span class="fc" id="L503"> RampartConfig stsRampConf = new RampartConfig();</span>
//TODO copy all the properties of service ramp conf to sts ramp conf
<span class="fc" id="L506"> stsRampConf.setUser(servicRampConf.getUser());</span>
<span class="fc" id="L507"> stsRampConf.setSigCryptoConfig(servicRampConf.getSigCryptoConfig());</span>
<span class="fc" id="L508"> stsRampConf.setPwCbClass(servicRampConf.getPwCbClass());</span>
<span class="fc" id="L510"> stsRampConf.setEncryptionUser(servicRampConf.getStsAlias());</span>
<span class="fc" id="L511"> stsRampConf.setEncrCryptoConfig(servicRampConf.getStsCryptoConfig());</span>
<span class="fc" id="L513"> policy.addAssertion(stsRampConf);</span>
<span class="fc" id="L515"> return policy;</span>
}
public static OMElement createRSTTempalteForSCT(int conversationVersion,
int wstVersion) throws RampartException {
try {
<span class="fc" id="L523"> log.debug(&quot;Creating RSTTemplate for an SCT request&quot;);</span>
<span class="fc" id="L524"> OMFactory fac = OMAbstractFactory.getOMFactory();</span>
<span class="fc" id="L526"> OMNamespace wspNs = fac.createOMNamespace(SPConstants.P_NS, &quot;wsp&quot;);</span>
<span class="fc" id="L527"> OMElement rstTempl = fac.createOMElement(</span>
SPConstants.REQUEST_SECURITY_TOKEN_TEMPLATE,
wspNs);
//Create TokenType element and set the value
<span class="fc" id="L532"> OMElement tokenTypeElem = TrustUtil.createTokenTypeElement(</span>
wstVersion, rstTempl);
<span class="fc" id="L534"> String tokenType = ConversationConstants</span>
.getWSCNs(conversationVersion)
+ ConversationConstants.TOKEN_TYPE_SECURITY_CONTEXT_TOKEN;
<span class="fc" id="L537"> tokenTypeElem.setText(tokenType);</span>
<span class="fc" id="L539"> return rstTempl;</span>
<span class="nc" id="L540"> } catch (TrustException e) {</span>
<span class="nc" id="L541"> throw new RampartException(&quot;errorCreatingRSTTemplateForSCT&quot;, e);</span>
<span class="nc" id="L542"> } catch (ConversationException e) {</span>
<span class="nc" id="L543"> throw new RampartException(&quot;errorCreatingRSTTemplateForSCT&quot;, e);</span>
}
}
public static int getTimeToLive(RampartMessageData messageData) {
<span class="fc" id="L550"> RampartConfig rampartConfig = messageData.getPolicyData().getRampartConfig();</span>
<span class="fc bfc" id="L551" title="All 2 branches covered."> if (rampartConfig != null) {</span>
<span class="fc" id="L552"> String ttl = rampartConfig.getTimestampTTL();</span>
<span class="fc" id="L553"> int ttl_i = 0;</span>
<span class="pc bpc" id="L554" title="1 of 2 branches missed."> if (ttl != null) {</span>
try {
<span class="fc" id="L556"> ttl_i = Integer.parseInt(ttl);</span>
<span class="nc" id="L557"> } catch (NumberFormatException e) {</span>
<span class="nc" id="L558"> ttl_i = messageData.getTimeToLive();</span>
<span class="fc" id="L559"> }</span>
}
<span class="pc bpc" id="L561" title="1 of 2 branches missed."> if (ttl_i &lt;= 0) {</span>
<span class="nc" id="L562"> ttl_i = messageData.getTimeToLive();</span>
}
<span class="fc" id="L564"> return ttl_i;</span>
} else {
<span class="fc" id="L566"> return RampartConfig.DEFAULT_TIMESTAMP_TTL;</span>
}
}
public static int getTimestampMaxSkew(RampartMessageData messageData) {
<span class="fc" id="L572"> RampartConfig rampartConfig = messageData.getPolicyData().getRampartConfig();</span>
<span class="fc bfc" id="L573" title="All 2 branches covered."> if (rampartConfig != null) {</span>
<span class="fc" id="L574"> String maxSkew = rampartConfig.getTimestampMaxSkew();</span>
<span class="fc" id="L575"> int maxSkew_i = 0;</span>
<span class="pc bpc" id="L576" title="1 of 2 branches missed."> if (maxSkew != null) {</span>
try {
<span class="fc" id="L578"> maxSkew_i = Integer.parseInt(maxSkew);</span>
<span class="nc" id="L579"> } catch (NumberFormatException e) {</span>
<span class="nc" id="L580"> maxSkew_i = messageData.getTimestampMaxSkew();</span>
<span class="fc" id="L581"> }</span>
}
<span class="pc bpc" id="L583" title="1 of 2 branches missed."> if (maxSkew_i &lt; 0) {</span>
<span class="nc" id="L584"> maxSkew_i = 0;</span>
}
<span class="fc" id="L586"> return maxSkew_i;</span>
} else {
<span class="fc" id="L588"> return RampartConfig.DEFAULT_TIMESTAMP_MAX_SKEW;</span>
}
}
/**
* Obtain a security context token.
* @param rmd
* @param secConvTok
* @return Return the SecurityContextidentifier of the token
* @throws TrustException
* @throws RampartException
*/
public static String getSecConvToken(RampartMessageData rmd,
SecureConversationToken secConvTok) throws TrustException,
RampartException {
<span class="fc" id="L603"> String action = TrustUtil.getActionValue(</span>
rmd.getWstVersion(),
RahasConstants.RST_ACTION_SCT);
// Get sts epr
<span class="fc" id="L608"> OMElement issuerEpr = secConvTok.getIssuerEpr();</span>
<span class="fc" id="L609"> String issuerEprAddress = rmd.getMsgContext().getTo().getAddress();</span>
<span class="pc bpc" id="L610" title="1 of 2 branches missed."> if(issuerEpr != null) {</span>
<span class="nc" id="L611"> issuerEprAddress = RampartUtil.processIssuerAddress(issuerEpr);</span>
}
//Find SC version
<span class="fc" id="L615"> int conversationVersion = rmd.getSecConvVersion();</span>
<span class="fc" id="L617"> OMElement rstTemplate = RampartUtil.createRSTTempalteForSCT(</span>
conversationVersion,
rmd.getWstVersion());
<span class="fc" id="L621"> Policy stsPolicy = null;</span>
//Try boot strap policy
<span class="fc" id="L624"> Policy bsPol = secConvTok.getBootstrapPolicy();</span>
<span class="pc bpc" id="L626" title="1 of 2 branches missed."> if(bsPol != null) {</span>
<span class="fc" id="L627"> log.debug(&quot;BootstrapPolicy found&quot;);</span>
<span class="fc" id="L628"> bsPol.addAssertion(rmd.getPolicyData().getRampartConfig());</span>
//copy the &lt;wsoma:OptimizedMimeSerialization/&gt; to BootstrapPolicy
<span class="pc bpc" id="L630" title="1 of 2 branches missed."> if (rmd.getPolicyData().getMTOMAssertion() != null) {</span>
<span class="nc" id="L631"> bsPol.addAssertion(rmd.getPolicyData().getMTOMAssertion()); </span>
}
<span class="fc" id="L633"> stsPolicy = bsPol;</span>
} else {
//No bootstrap policy use issuer policy
<span class="nc" id="L636"> log.debug(&quot;No bootstrap policy, using issuer policy&quot;);</span>
<span class="nc" id="L637"> stsPolicy = rmd.getPolicyData().getIssuerPolicy();</span>
}
<span class="fc" id="L640"> String id = getToken(rmd, rstTemplate,</span>
issuerEprAddress, action, stsPolicy);
<span class="pc bpc" id="L643" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L644"> log.debug(&quot;SecureConversationToken obtained: id=&quot; + id);</span>
}
<span class="fc" id="L646"> return id;</span>
}
/**
* Obtain an issued token.
* @param rmd
* @param issuedToken
* @return The identifier of the issued token
* @throws RampartException
*/
public static String getIssuedToken(RampartMessageData rmd,
IssuedToken issuedToken) throws RampartException {
try {
//TODO : Provide the overriding mechanism to provide a custom way of
//obtaining a token
<span class="fc" id="L665"> String action = TrustUtil.getActionValue(rmd.getWstVersion(),</span>
RahasConstants.RST_ACTION_ISSUE);
// Get sts epr
<span class="fc" id="L669"> String issuerEprAddress = RampartUtil.processIssuerAddress(issuedToken</span>
.getIssuerEpr());
<span class="fc" id="L672"> OMElement rstTemplate = issuedToken.getRstTemplate();</span>
// Get STS policy
<span class="fc" id="L675"> Policy stsPolicy = (Policy)rmd.getMsgContext().getProperty(RampartMessageData.RAMPART_STS_POLICY);</span>
<span class="pc bpc" id="L677" title="1 of 4 branches missed."> if( stsPolicy == null &amp;&amp; issuedToken.getIssuerMex() != null) {</span>
<span class="fc" id="L678"> stsPolicy = RampartUtil.getPolicyFromMetadataRef(issuedToken.getIssuerMex());</span>
<span class="fc" id="L679"> RampartUtil.addRampartConfig(rmd, stsPolicy);</span>
}
<span class="fc" id="L682"> String id = getToken(rmd, rstTemplate, issuerEprAddress, action,</span>
stsPolicy);
<span class="pc bpc" id="L685" title="1 of 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L686"> log.debug(&quot;Issued token obtained: id=&quot; + id);</span>
}
<span class="fc" id="L688"> return id;</span>
<span class="nc" id="L689"> } catch (TrustException e) {</span>
<span class="nc" id="L690"> throw new RampartException(&quot;errorInObtainingToken&quot;, e);</span>
}
}
/**
* Request a token.
* @param rmd
* @param rstTemplate
* @param issuerEpr
* @param action
* @param issuerPolicy
* @return Return the identifier of the obtained token
* @throws RampartException
*/
public static String getToken(RampartMessageData rmd, OMElement rstTemplate,
String issuerEpr, String action, Policy issuerPolicy) throws RampartException {
try {
//First check whether the user has provided the token
<span class="fc" id="L709"> MessageContext msgContext = rmd.getMsgContext();</span>
<span class="fc" id="L710"> String customTokeId = (String) msgContext</span>
.getProperty(RampartMessageData.KEY_CUSTOM_ISSUED_TOKEN);
<span class="fc bfc" id="L712" title="All 2 branches covered."> if(customTokeId != null) {</span>
<span class="fc" id="L713"> return customTokeId;</span>
} else {
<span class="fc" id="L716"> Axis2Util.useDOOM(false);</span>
<span class="fc" id="L718"> STSClient client = new STSClient(rmd.getMsgContext()</span>
.getConfigurationContext());
// Set request action
<span class="fc" id="L721"> client.setAction(action);</span>
<span class="fc" id="L723"> client.setVersion(rmd.getWstVersion());</span>
<span class="fc" id="L725"> client.setRstTemplate(rstTemplate);</span>
// Set crypto information
<span class="fc" id="L728"> Crypto crypto = RampartUtil.getSignatureCrypto(rmd.getPolicyData().getRampartConfig(), </span>
rmd.getMsgContext().getAxisService().getClassLoader());
<span class="fc" id="L730"> CallbackHandler cbh = RampartUtil.getPasswordCB(rmd);</span>
<span class="fc" id="L731"> client.setCryptoInfo(crypto, cbh);</span>
// Get service policy
<span class="fc" id="L734"> Policy servicePolicy = rmd.getServicePolicy();</span>
// Get service epr
<span class="fc" id="L737"> String servceEprAddress = rmd.getMsgContext()</span>
.getOptions().getTo().getAddress();
//If addressing version can be found set it
<span class="fc" id="L741"> Object addrVersionNs = msgContext.getProperty(AddressingConstants.WS_ADDRESSING_VERSION);</span>
<span class="pc bpc" id="L742" title="1 of 2 branches missed."> if(addrVersionNs != null) {</span>
<span class="nc" id="L743"> client.setAddressingNs((String)addrVersionNs);</span>
}
<span class="fc" id="L746"> Options options = new Options();</span>
<span class="fc" id="L748"> options.setUserName(rmd.getMsgContext().getOptions().getUserName());</span>
<span class="fc" id="L749"> options.setPassword(rmd.getMsgContext().getOptions().getPassword());</span>
<span class="pc bpc" id="L751" title="1 of 2 branches missed."> if (msgContext.getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER) != null) {</span>
<span class="nc" id="L752"> Protocol protocolHandler =</span>
(Protocol)msgContext.getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);;
<span class="nc" id="L754"> options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, protocolHandler); </span>
}
<span class="pc bpc" id="L757" title="1 of 2 branches missed."> if (msgContext.getParameter(WSHandlerConstants.PW_CALLBACK_REF) != null ) {</span>
<span class="nc" id="L758"> Parameter pwCallback = msgContext.getParameter(WSHandlerConstants.PW_CALLBACK_REF);</span>
<span class="nc" id="L759"> client.addParameter(pwCallback);</span>
}
<span class="fc" id="L762"> client.setOptions(options);</span>
//Set soap version
<span class="fc bfc" id="L765" title="All 2 branches covered."> if (msgContext.isSOAP11()) {</span>
<span class="fc" id="L766"> client.setSoapVersion(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);</span>
} else {
<span class="fc" id="L768"> client.setSoapVersion(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);</span>
}
//Make the request
<span class="fc" id="L773"> org.apache.rahas.Token rst = </span>
client.requestSecurityToken(servicePolicy,
issuerEpr,
issuerPolicy,
servceEprAddress);
//Add the token to token storage
<span class="fc" id="L780"> rst.setState(Token.ISSUED);</span>
<span class="fc" id="L781"> rmd.getTokenStorage().add(rst);</span>
<span class="fc" id="L782"> Axis2Util.useDOOM(true);</span>
<span class="fc" id="L783"> return rst.getId();</span>
}
<span class="nc" id="L785"> } catch (Exception e) {</span>
<span class="nc" id="L786"> throw new RampartException(&quot;errorInObtainingToken&quot;, e);</span>
}
}
public static String getSoapBodyId(SOAPEnvelope env) {
<span class="nc" id="L791"> return addWsuIdToElement(env.getBody());</span>
}
public static String addWsuIdToElement(OMElement elem) {
String id;
//first try to get the Id attr
<span class="fc" id="L798"> OMAttribute idAttr = elem.getAttribute(new QName(&quot;Id&quot;));</span>
<span class="fc bfc" id="L799" title="All 2 branches covered."> if(idAttr == null) {</span>
//then try the wsu:Id value
<span class="fc" id="L801"> idAttr = elem.getAttribute(new QName(WSConstants.WSU_NS, &quot;Id&quot;));</span>
}
<span class="fc bfc" id="L804" title="All 2 branches covered."> if(idAttr != null) {</span>
<span class="fc" id="L805"> id = idAttr.getAttributeValue();</span>
} else {
//Add an id
<span class="fc" id="L808"> OMNamespace ns = elem.getOMFactory().createOMNamespace(</span>
WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
<span class="fc" id="L810"> id = &quot;Id-&quot; + elem.hashCode();</span>
<span class="fc" id="L811"> idAttr = elem.getOMFactory().createOMAttribute(&quot;Id&quot;, ns, id);</span>
<span class="fc" id="L812"> elem.addAttribute(idAttr);</span>
}
<span class="fc" id="L815"> return id;</span>
}
/**
* Change the owner document of the given node. The method first attempts to move the node using
* {@link Document#adoptNode(Node)}. If that fails, it will import the node into the target
* document using {@link Document#importNode(Node, boolean)}.
*
* @param targetDocument
* the target document
* @param node
* the node to adopt or import
* @return the adopted or imported node
*/
public static Node adoptNode(Document targetDocument, Node node) {
<span class="fc" id="L830"> Node result = targetDocument.adoptNode(node);</span>
<span class="pc bpc" id="L831" title="1 of 2 branches missed."> if (result == null) {</span>
<span class="nc" id="L832"> result = targetDocument.importNode(node, true);</span>
}
<span class="fc" id="L834"> return result;</span>
}
public static Element appendChildToSecHeader(RampartMessageData rmd,
OMElement elem) {
<span class="fc" id="L839"> return appendChildToSecHeader(rmd, (Element)elem);</span>
}
public static Element appendChildToSecHeader(RampartMessageData rmd,
Element elem) {
<span class="fc" id="L844"> Element secHeaderElem = rmd.getSecHeader().getSecurityHeader();</span>
<span class="fc" id="L845"> Node node = adoptNode(secHeaderElem.getOwnerDocument(), elem);</span>
<span class="fc" id="L846"> return (Element)secHeaderElem.appendChild(node);</span>
}
public static Element insertSiblingAfter(RampartMessageData rmd,
Element child, Element sibling) {
<span class="fc bfc" id="L851" title="All 2 branches covered."> if (child == null) {</span>
<span class="fc" id="L852"> return appendChildToSecHeader(rmd, sibling);</span>
} else {
<span class="fc bfc" id="L854" title="All 2 branches covered."> if (child.getOwnerDocument().equals(sibling.getOwnerDocument())) {</span>
<span class="pc bpc" id="L856" title="3 of 4 branches missed."> if (child.getParentNode() == null</span>
&amp;&amp; !child.getLocalName().equals(&quot;UsernameToken&quot;)) {
<span class="nc" id="L858"> rmd.getSecHeader().getSecurityHeader().appendChild(child);</span>
}
<span class="fc" id="L860"> ((OMElement) child).insertSiblingAfter((OMElement) sibling);</span>
<span class="fc" id="L861"> return sibling;</span>
} else {
<span class="fc" id="L863"> Element newSib = (Element) child.getOwnerDocument().importNode(</span>
sibling, true);
<span class="fc" id="L865"> ((OMElement) child).insertSiblingAfter((OMElement) newSib);</span>
<span class="fc" id="L866"> return newSib;</span>
}
}
}
public static Element insertSiblingBefore(RampartMessageData rmd, Element child, Element sibling) {
<span class="pc bpc" id="L872" title="1 of 2 branches missed."> if(child == null) {</span>
<span class="nc" id="L873"> return appendChildToSecHeader(rmd, sibling);</span>
} else {
<span class="pc bpc" id="L875" title="1 of 2 branches missed."> if(child.getOwnerDocument().equals(sibling.getOwnerDocument())) {</span>
<span class="fc" id="L876"> ((OMElement)child).insertSiblingBefore((OMElement)sibling);</span>
<span class="fc" id="L877"> return sibling;</span>
} else {
<span class="nc" id="L879"> Element newSib = (Element)child.getOwnerDocument().importNode(sibling, true);</span>
<span class="nc" id="L880"> ((OMElement)child).insertSiblingBefore((OMElement)newSib);</span>
<span class="nc" id="L881"> return newSib;</span>
}
}
}
public static List&lt;WSEncryptionPart&gt; getEncryptedParts(RampartMessageData rmd) {
<span class="fc" id="L888"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="fc" id="L889"> SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();</span>
<span class="pc bpc" id="L890" title="1 of 4 branches missed."> List&lt;WSEncryptionPart&gt; encryptedPartsElements = getPartsAndElements(false, envelope,</span>
rpd.isEncryptBody() &amp;&amp; !rpd.isEncryptBodyOptional(), rpd
.getEncryptedParts(), rpd.getEncryptedElements(), rpd
.getDeclaredNamespaces());
<span class="fc" id="L894"> return getContentEncryptedElements(encryptedPartsElements, envelope,</span>
rpd.getContentEncryptedElements(), rpd.getDeclaredNamespaces());
}
public static List&lt;WSEncryptionPart&gt; getSignedParts(RampartMessageData rmd) {
<span class="fc" id="L899"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="fc" id="L900"> SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();</span>
//&quot;signAllHeaders&quot; indicates that all the headers should be signed.
<span class="fc bfc" id="L903" title="All 2 branches covered."> if (rpd.isSignAllHeaders()) {</span>
<span class="fc" id="L904"> Iterator childHeaders = envelope.getHeader().getChildElements();</span>
<span class="fc bfc" id="L905" title="All 2 branches covered."> while (childHeaders.hasNext()) {</span>
<span class="fc" id="L906"> OMElement hb = (OMElement) childHeaders.next();</span>
<span class="pc bpc" id="L907" title="1 of 4 branches missed."> if (!(hb.getLocalName().equals(WSConstants.WSSE_LN)</span>
&amp;&amp; hb.getNamespace().getNamespaceURI().equals(WSConstants.WSSE_NS))) {
<span class="fc" id="L909"> rpd.addSignedPart(hb.getNamespace().getNamespaceURI(),hb.getLocalName());</span>
}
<span class="fc" id="L911"> }</span>
}
<span class="pc bpc" id="L914" title="1 of 4 branches missed."> return getPartsAndElements(true, envelope, rpd.isSignBody()</span>
&amp;&amp; !rpd.isSignBodyOptional(), rpd.getSignedParts(), rpd
.getSignedElements(), rpd.getDeclaredNamespaces());
}
public static List&lt;WSEncryptionPart&gt; getSupportingEncryptedParts(RampartMessageData rmd,
SupportingPolicyData rpd) {
<span class="fc" id="L921"> SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();</span>
<span class="pc bpc" id="L922" title="3 of 4 branches missed."> return getPartsAndElements(false, envelope, rpd.isEncryptBody()</span>
&amp;&amp; !rpd.isEncryptBodyOptional(), rpd.getEncryptedParts(), rpd
.getEncryptedElements(), rpd.getDeclaredNamespaces());
}
public static List&lt;WSEncryptionPart&gt; getSupportingSignedParts(RampartMessageData rmd,
SupportingPolicyData rpd) {
<span class="fc" id="L929"> SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();</span>
<span class="pc bpc" id="L930" title="3 of 4 branches missed."> return getPartsAndElements(true, envelope, rpd.isSignBody()</span>
&amp;&amp; !rpd.isSignBodyOptional(), rpd.getSignedParts(), rpd
.getSignedElements(), rpd.getDeclaredNamespaces());
}
public static Set findAllPrefixNamespaces(OMElement currentElement, HashMap decNamespacess)
{
<span class="fc" id="L937"> Set&lt;OMNamespace&gt; results = new HashSet&lt;OMNamespace&gt;();</span>
//Find declared namespaces
<span class="fc" id="L940"> findPrefixNamespaces(currentElement,results);</span>
//Get all default namespaces
<span class="fc" id="L943"> List defaultNamespaces = getDefaultPrefixNamespaces(currentElement.getOMFactory());</span>
<span class="fc bfc" id="L944" title="All 2 branches covered."> for (Object defaultNamespace : defaultNamespaces) {</span>
<span class="fc" id="L945"> OMNamespace ns = (OMNamespace) defaultNamespace;</span>
<span class="fc" id="L946"> results.add(ns);</span>
<span class="fc" id="L947"> }</span>
<span class="fc bfc" id="L949" title="All 2 branches covered."> for (Object o : decNamespacess.keySet()) {</span>
<span class="fc" id="L950"> String prefix = (String) o;</span>
<span class="fc" id="L951"> String ns = (String) decNamespacess.get(prefix);</span>
<span class="fc" id="L952"> OMFactory omFactory = currentElement.getOMFactory();</span>
<span class="fc" id="L953"> OMNamespace namespace = omFactory.createOMNamespace(ns, prefix);</span>
<span class="fc" id="L954"> results.add(namespace);</span>
<span class="fc" id="L956"> }</span>
<span class="fc" id="L958"> return results;</span>
}
private static void findPrefixNamespaces(OMElement e, Set&lt;OMNamespace&gt; results) {
<span class="fc" id="L963"> Iterator iterator = e.getAllDeclaredNamespaces();</span>
<span class="pc bpc" id="L965" title="1 of 2 branches missed."> if (iterator != null) {</span>
<span class="fc bfc" id="L966" title="All 2 branches covered."> while (iterator.hasNext())</span>
<span class="fc" id="L967"> results.add((OMNamespace)iterator.next());</span>
}
<span class="fc" id="L970"> Iterator children = e.getChildElements();</span>
<span class="fc bfc" id="L972" title="All 2 branches covered."> while (children.hasNext()) {</span>
<span class="fc" id="L973"> findPrefixNamespaces((OMElement) children.next(), results);</span>
}
<span class="fc" id="L975"> }</span>
private static List getDefaultPrefixNamespaces(OMFactory factory)
{
<span class="fc" id="L979"> List&lt;OMNamespace&gt; namespaces = new ArrayList&lt;OMNamespace&gt;();</span>
// put default namespaces here (sp, soapenv, wsu, etc...)
<span class="fc" id="L982"> namespaces.add(factory.createOMNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX));</span>
<span class="fc" id="L983"> namespaces.add(factory.createOMNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX));</span>
<span class="fc" id="L984"> namespaces.add(factory.createOMNamespace(WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX));</span>
<span class="fc" id="L985"> namespaces.add(factory.createOMNamespace(WSConstants.WSU_NS, WSConstants.WSU_PREFIX));</span>
<span class="fc" id="L987"> return namespaces;</span>
}
public static List&lt;WSEncryptionPart&gt; getContentEncryptedElements (List&lt;WSEncryptionPart&gt; encryptedPartsElements,
SOAPEnvelope envelope,List&lt;String&gt; elements, HashMap decNamespaces ) {
<span class="fc" id="L994"> Set namespaces = findAllPrefixNamespaces(envelope, decNamespaces);</span>
<span class="fc bfc" id="L996" title="All 2 branches covered."> for (String expression : elements) {</span>
try {
<span class="fc" id="L998"> XPath xp = new AXIOMXPath(expression);</span>
<span class="fc bfc" id="L1000" title="All 2 branches covered."> for (Object objectNamespace : namespaces) {</span>
<span class="fc" id="L1001"> OMNamespace tmpNs = (OMNamespace) objectNamespace;</span>
<span class="fc" id="L1002"> xp.addNamespace(tmpNs.getPrefix(), tmpNs.getNamespaceURI());</span>
<span class="fc" id="L1003"> }</span>
<span class="fc" id="L1005"> List selectedNodes = xp.selectNodes(envelope);</span>
<span class="fc bfc" id="L1007" title="All 2 branches covered."> for (Object selectedNode : selectedNodes) {</span>
<span class="fc" id="L1008"> OMElement e = (OMElement) selectedNode;</span>
<span class="fc" id="L1010"> String localName = e.getLocalName();</span>
<span class="pc bpc" id="L1011" title="1 of 2 branches missed."> String namespace = e.getNamespace() != null ? e.getNamespace().getNamespaceURI() : null;</span>
<span class="fc" id="L1013"> OMAttribute wsuIdAttribute = e.getAttribute(new QName(WSConstants.WSU_NS, &quot;Id&quot;));</span>
<span class="fc" id="L1015"> String wsuId = null;</span>
<span class="pc bpc" id="L1016" title="1 of 2 branches missed."> if (wsuIdAttribute != null) {</span>
<span class="nc" id="L1017"> wsuId = wsuIdAttribute.getAttributeValue();</span>
}
<span class="fc" id="L1020"> encryptedPartsElements.add(createEncryptionPart(localName,</span>
wsuId, namespace, &quot;Content&quot;, expression));
<span class="fc" id="L1023"> }</span>
<span class="nc" id="L1025"> } catch (JaxenException e) {</span>
// This has to be changed to propagate an instance of a RampartException up
<span class="nc" id="L1027"> throw new RuntimeException(e);</span>
<span class="fc" id="L1028"> }</span>
<span class="fc" id="L1029"> }</span>
<span class="fc" id="L1032"> return encryptedPartsElements;</span>
}
/**
* Creates an Encryption or Signature paert with given name and id. Name must not be null.
* @param name The name of the part
* @param id The id of the part.
* @return WSEncryptionPart.
*/
public static WSEncryptionPart createEncryptionPart (String name, String id) {
<span class="fc" id="L1045"> return createEncryptionPart(name, id, null, null, null);</span>
}
/**
* Creates an encryption part. Could be a part or could be an element pointed through xpath expression.
* @param name Name of the element.
* @param id The id of the element
* @param namespace Namespace of the element.
* @param modifier Modifier &quot;Content&quot; or &quot;Element&quot;
* @return A WSEncryptionPart
*/
public static WSEncryptionPart createEncryptionPart(String name, String id,
String namespace, String modifier) {
<span class="fc" id="L1059"> return createEncryptionPart(name, id, namespace, modifier, null);</span>
}
/**
* Creates an encryption part. Could be a part or could be an element pointed through xpath expression.
* @param name Name of the element.
* @param id The id of the element
* @param namespace Namespace of the element.
* @param modifier Modifier &quot;Content&quot; or &quot;Element&quot;
* @param xPath The xPath expression
* @return A WSEncryptionPart
*/
public static WSEncryptionPart createEncryptionPart(String name, String id,
String namespace, String modifier,String xPath) {
// The part name must not be null !!
<span class="pc bpc" id="L1075" title="1 of 4 branches missed."> assert name != null;</span>
<span class="fc" id="L1077"> WSEncryptionPart wsEncryptionPart = new WSEncryptionPart(name, namespace, modifier);</span>
<span class="fc" id="L1078"> wsEncryptionPart.setId(id);</span>
<span class="fc" id="L1079"> wsEncryptionPart.setXpath(xPath);</span>
<span class="fc" id="L1081"> return wsEncryptionPart;</span>
}
public static List&lt;WSEncryptionPart&gt; getPartsAndElements(boolean sign, SOAPEnvelope envelope, boolean includeBody,
List&lt;WSEncryptionPart&gt; parts, List&lt;String&gt; elements,
HashMap decNamespaces) {
<span class="fc" id="L1088"> List&lt;OMElement&gt; found = new ArrayList&lt;OMElement&gt;();</span>
<span class="fc" id="L1089"> List&lt;WSEncryptionPart&gt; result = new ArrayList&lt;WSEncryptionPart&gt;();</span>
// check body
<span class="fc bfc" id="L1092" title="All 2 branches covered."> if(includeBody) {</span>
<span class="fc" id="L1094"> String wsuId = addWsuIdToElement(envelope.getBody());</span>
<span class="fc bfc" id="L1096" title="All 2 branches covered."> if( sign ) {</span>
<span class="fc" id="L1097"> result.add(createEncryptionPart(envelope.getBody().getLocalName(), wsuId,</span>
null, null));
} else {
<span class="fc" id="L1100"> result.add(createEncryptionPart(envelope.getBody().getLocalName(), wsuId, null, &quot;Content&quot;));</span>
}
// TODO can we remove this ?
<span class="fc" id="L1104"> found.add( envelope.getBody() );</span>
}
// Search envelope header for 'parts' from Policy (SignedParts/EncryptedParts)
<span class="fc" id="L1109"> SOAPHeader header = envelope.getHeader();</span>
<span class="fc bfc" id="L1111" title="All 2 branches covered."> for (WSEncryptionPart part : parts) {</span>
<span class="pc bpc" id="L1112" title="1 of 2 branches missed."> if (part.getName() == null) {</span>
// NO name - search by namespace
<span class="nc" id="L1114"> ArrayList headerList = header.getHeaderBlocksWithNSURI(part.getNamespace());</span>
<span class="nc bnc" id="L1116" title="All 2 branches missed."> for (Object aHeaderList : headerList) {</span>
<span class="nc" id="L1117"> SOAPHeaderBlock shb = (SOAPHeaderBlock) aHeaderList;</span>
// find reference in envelope
<span class="nc" id="L1120"> OMElement e = header.getFirstChildWithName(shb.getQName());</span>
<span class="nc bnc" id="L1122" title="All 2 branches missed."> if (!found.contains(e)) {</span>
// found new
<span class="nc" id="L1124"> found.add(e);</span>
<span class="nc bnc" id="L1126" title="All 2 branches missed."> if (sign) {</span>
<span class="nc" id="L1127"> result.add(createEncryptionPart(e.getLocalName(), null,</span>
part.getNamespace(), &quot;Content&quot;));
} else {
<span class="nc" id="L1131"> OMAttribute wsuIdAttribute = e.getAttribute(new QName(WSConstants.WSU_NS, &quot;Id&quot;));</span>
<span class="nc" id="L1133"> String wsuId = null;</span>
<span class="nc bnc" id="L1134" title="All 2 branches missed."> if (wsuIdAttribute != null) {</span>
<span class="nc" id="L1135"> wsuId = wsuIdAttribute.getAttributeValue();</span>
}
<span class="nc" id="L1138"> result.add(createEncryptionPart(e.getLocalName(),wsuId,</span>
part.getNamespace(), &quot;Element&quot;));
}
}
<span class="nc" id="L1142"> }</span>
<span class="nc" id="L1143"> } else {</span>
// try to find
<span class="fc" id="L1145"> OMElement e = header.getFirstChildWithName(new QName(part.getNamespace(), part.getName()));</span>
<span class="fc bfc" id="L1146" title="All 2 branches covered."> if (e != null) {</span>
<span class="pc bpc" id="L1147" title="1 of 2 branches missed."> if (!found.contains(e)) {</span>
// found new (reuse wsep)
<span class="fc" id="L1149"> found.add(e);</span>
<span class="fc" id="L1150"> OMAttribute wsuId = e.getAttribute(new QName(WSConstants.WSU_NS, &quot;Id&quot;));</span>
<span class="fc bfc" id="L1152" title="All 2 branches covered."> if (wsuId != null) {</span>
<span class="fc" id="L1153"> part.setEncId(wsuId.getAttributeValue());</span>
}
<span class="fc" id="L1156"> result.add(part);</span>
}
}
}
<span class="fc" id="L1160"> }</span>
// ?? Search for 'Elements' here
// decide what exactly is going to be used - only the default namespaces, or the list of all declared namespaces in the message !
<span class="fc" id="L1165"> Set namespaces = findAllPrefixNamespaces(envelope, decNamespaces);</span>
<span class="fc bfc" id="L1167" title="All 2 branches covered."> for (String expression : elements) {</span>
try {
<span class="fc" id="L1169"> XPath xp = new AXIOMXPath(expression);</span>
<span class="fc bfc" id="L1171" title="All 2 branches covered."> for (Object objectNamespace : namespaces) {</span>
<span class="fc" id="L1172"> OMNamespace tmpNs = (OMNamespace) objectNamespace;</span>
<span class="fc" id="L1173"> xp.addNamespace(tmpNs.getPrefix(), tmpNs.getNamespaceURI());</span>
<span class="fc" id="L1174"> }</span>
<span class="fc" id="L1176"> List selectedNodes = xp.selectNodes(envelope);</span>
<span class="fc bfc" id="L1178" title="All 2 branches covered."> for (Object selectedNode : selectedNodes) {</span>
<span class="fc" id="L1179"> OMElement e = (OMElement) selectedNode;</span>
<span class="fc" id="L1180"> String localName = e.getLocalName();</span>
<span class="pc bpc" id="L1181" title="1 of 2 branches missed."> String namespace = e.getNamespace() != null ? e.getNamespace().getNamespaceURI() : null;</span>
<span class="fc bfc" id="L1183" title="All 2 branches covered."> if (sign) {</span>
<span class="fc" id="L1185"> result.add(createEncryptionPart(localName, null, namespace, &quot;Content&quot;, expression));</span>
} else {
<span class="fc" id="L1189"> OMAttribute wsuIdAttribute = e.getAttribute(new QName(WSConstants.WSU_NS, &quot;Id&quot;));</span>
<span class="fc" id="L1191"> String wsuId = null;</span>
<span class="fc bfc" id="L1192" title="All 2 branches covered."> if (wsuIdAttribute != null) {</span>
<span class="fc" id="L1193"> wsuId = wsuIdAttribute.getAttributeValue();</span>
}
<span class="fc" id="L1196"> result.add(createEncryptionPart(localName, wsuId, namespace, &quot;Element&quot;, expression));</span>
}
<span class="fc" id="L1198"> }</span>
<span class="nc" id="L1200"> } catch (JaxenException e) {</span>
// This has to be changed to propagate an instance of a RampartException up
<span class="nc" id="L1202"> throw new RuntimeException(e);</span>
<span class="fc" id="L1203"> }</span>
<span class="fc" id="L1204"> }</span>
<span class="fc" id="L1206"> return result;</span>
}
/**
* Get a element for SOAP
* @param envelope SOAP Envelope of which we should check required elements
* @param decNamespaces Declared namespaces in RequiredElements assertion
* @param expression XPATH expression of required elements
* @return
*/
public static boolean checkRequiredElements(SOAPEnvelope envelope, HashMap decNamespaces, String expression) {
// The XPath expression must be evaluated against the SOAP header
// http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/ws-securitypolicy-1.2-spec-os.html#_Toc161826519
<span class="fc" id="L1220"> SOAPHeader header = envelope.getHeader();</span>
<span class="fc" id="L1221"> Set namespaces = findAllPrefixNamespaces(header, decNamespaces);</span>
try {
<span class="fc" id="L1224"> XPath xp = new AXIOMXPath(expression);</span>
<span class="fc bfc" id="L1226" title="All 2 branches covered."> for (Object namespace : namespaces) {</span>
<span class="fc" id="L1227"> OMNamespace tmpNs = (OMNamespace) namespace;</span>
<span class="fc" id="L1228"> xp.addNamespace(tmpNs.getPrefix(), tmpNs.getNamespaceURI());</span>
<span class="fc" id="L1229"> }</span>
<span class="fc" id="L1231"> List selectedNodes = xp.selectNodes(header);</span>
<span class="fc bfc" id="L1233" title="All 2 branches covered."> if (selectedNodes.size() == 0) {</span>
<span class="fc" id="L1234"> return false;</span>
}
<span class="nc" id="L1237"> } catch (JaxenException e) {</span>
// This has to be changed to propagate an instance of a RampartException up
<span class="nc" id="L1239"> throw new RuntimeException(e);</span>
<span class="fc" id="L1240"> }</span>
<span class="fc" id="L1242"> return true;</span>
}
public static KeyGenerator getEncryptionKeyGenerator(String symEncrAlgo) throws WSSecurityException {
KeyGenerator keyGen;
try {
/*
* Assume AES as default, so initialize it
*/
<span class="nc" id="L1252"> keyGen = KeyGenerator.getInstance(&quot;AES&quot;);</span>
<span class="nc bnc" id="L1253" title="All 2 branches missed."> if (symEncrAlgo.equalsIgnoreCase(WSConstants.TRIPLE_DES)) {</span>
<span class="nc" id="L1254"> keyGen = KeyGenerator.getInstance(&quot;DESede&quot;);</span>
<span class="nc bnc" id="L1255" title="All 2 branches missed."> } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_128)) {</span>
<span class="nc" id="L1256"> keyGen.init(128);</span>
<span class="nc bnc" id="L1257" title="All 2 branches missed."> } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_192)) {</span>
<span class="nc" id="L1258"> keyGen.init(192);</span>
<span class="nc bnc" id="L1259" title="All 2 branches missed."> } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_256)) {</span>
<span class="nc" id="L1260"> keyGen.init(256);</span>
} else {
<span class="nc" id="L1262"> return null;</span>
}
<span class="nc" id="L1264"> } catch (NoSuchAlgorithmException e) {</span>
<span class="nc" id="L1265"> throw new WSSecurityException(</span>
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
<span class="nc" id="L1267"> }</span>
<span class="nc" id="L1268"> return keyGen;</span>
}
/**
* Creates the unique (reproducible) id for to hold the context identifier
* of the message exchange.
* @return Id to hold the context identifier in the message context
*/
public static String getContextIdentifierKey(MessageContext msgContext) {
<span class="fc" id="L1277"> return msgContext.getAxisService().getName();</span>
}
/**
* Returns the map of security context token identifiers
* @return the map of security context token identifiers
*/
public static Hashtable getContextMap(MessageContext msgContext) {
//Fist check whether its there
<span class="fc" id="L1287"> Object map = msgContext.getConfigurationContext().getProperty(</span>
ConversationConstants.KEY_CONTEXT_MAP);
<span class="fc bfc" id="L1290" title="All 2 branches covered."> if(map == null) {</span>
//If not create a new one
<span class="fc" id="L1292"> map = new Hashtable();</span>
//Set the map globally
<span class="fc" id="L1294"> msgContext.getConfigurationContext().setProperty(</span>
ConversationConstants.KEY_CONTEXT_MAP, map);
}
<span class="fc" id="L1298"> return (Hashtable)map;</span>
}
public static boolean isTokenValid(RampartMessageData rmd, String id) throws RampartException {
try {
<span class="fc" id="L1303"> org.apache.rahas.Token token = rmd.getTokenStorage().getToken(id);</span>
<span class="pc bpc" id="L1304" title="1 of 4 branches missed."> return token!= null &amp;&amp; token.getState() == org.apache.rahas.Token.ISSUED;</span>
<span class="nc" id="L1305"> } catch (TrustException e) {</span>
<span class="nc" id="L1306"> throw new RampartException(&quot;errorExtractingToken&quot;);</span>
}
}
public static void setEncryptionUser(RampartMessageData rmd, WSSecEncryptedKey encrKeyBuilder)
throws RampartException {
<span class="fc" id="L1312"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="fc" id="L1313"> String encrUser = rpd.getRampartConfig().getEncryptionUser();</span>
<span class="fc" id="L1314"> setEncryptionUser(rmd, encrKeyBuilder, encrUser);</span>
<span class="fc" id="L1315"> }</span>
public static void setEncryptionUser(RampartMessageData rmd, WSSecEncryptedKey encrKeyBuilder,
String encrUser) throws RampartException {
<span class="fc" id="L1319"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="pc bpc" id="L1321" title="1 of 2 branches missed."> if (encrUser == null) {</span>
<span class="nc" id="L1322"> encrUser = rpd.getRampartConfig().getEncryptionUser();</span>
}
<span class="pc bpc" id="L1325" title="2 of 4 branches missed."> if (encrUser == null || &quot;&quot;.equals(encrUser)) {</span>
<span class="nc" id="L1326"> throw new RampartException(&quot;missingEncryptionUser&quot;);</span>
}
<span class="fc bfc" id="L1328" title="All 2 branches covered."> if(encrUser.equals(WSHandlerConstants.USE_REQ_SIG_CERT)) {</span>
<span class="fc" id="L1329"> List&lt;WSHandlerResult&gt; resultsObj</span>
= (List&lt;WSHandlerResult&gt;)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
<span class="pc bpc" id="L1331" title="1 of 2 branches missed."> if(resultsObj != null) {</span>
<span class="fc" id="L1332"> encrKeyBuilder.setUseThisCert(getReqSigCert(resultsObj));</span>
//TODO This is a hack, this should not come under USE_REQ_SIG_CERT
<span class="pc bpc" id="L1335" title="1 of 2 branches missed."> if(encrKeyBuilder.isCertSet()) {</span>
<span class="fc" id="L1336"> encrKeyBuilder.setUserInfo(getUsername(resultsObj));</span>
}
} else {
<span class="nc" id="L1341"> throw new RampartException(&quot;noSecurityResults&quot;);</span>
}
<span class="fc" id="L1343"> } else {</span>
<span class="fc" id="L1344"> encrKeyBuilder.setUserInfo(encrUser);</span>
}
<span class="fc" id="L1346"> }</span>
/**
* Sets the keyIdentifierType of &lt;code&gt;WSSecSignature&lt;/code&gt; or &lt;code&gt;WSSecEncryptedKey&lt;/code&gt;
* according to the given &lt;code&gt;Token&lt;/code&gt; and &lt;code&gt;RampartPolicyData&lt;/code&gt;
* First check the requirements specified under Token Assertion and if not found check
* the WSS11 and WSS10 assertions
*/
public static void setKeyIdentifierType(RampartMessageData rmd, WSSecBase secBase,org.apache.ws.secpolicy.model.Token token) {
// Use a reference rather than the binary security token if: the policy never allows the token to be
// included; or this is the recipient and the token should only be included in requests; or this is
// the initiator and the token should only be included in responses.
<span class="pc bpc" id="L1360" title="3 of 10 branches missed."> final boolean useReference = token.getInclusion() == SPConstants.INCLUDE_TOKEN_NEVER</span>
|| !rmd.isInitiator() &amp;&amp; token.getInclusion() == SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT
|| rmd.isInitiator() &amp;&amp; token.getInclusion() == SPConstants.INCLUDE_TOEKN_ALWAYS_TO_INITIATOR;
<span class="fc bfc" id="L1363" title="All 2 branches covered."> if (useReference) {</span>
<span class="fc" id="L1365"> boolean tokenTypeSet = false;</span>
<span class="pc bpc" id="L1367" title="1 of 2 branches missed."> if(token instanceof X509Token) {</span>
<span class="fc" id="L1368"> X509Token x509Token = (X509Token)token;</span>
<span class="pc bpc" id="L1370" title="1 of 2 branches missed."> if(x509Token.isRequireIssuerSerialReference()) {</span>
<span class="nc" id="L1371"> secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);</span>
<span class="nc" id="L1372"> tokenTypeSet = true;</span>
<span class="fc bfc" id="L1373" title="All 2 branches covered."> } else if (x509Token.isRequireKeyIdentifierReference()) {</span>
<span class="fc" id="L1374"> secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER);</span>
<span class="fc" id="L1375"> tokenTypeSet = true;</span>
<span class="fc bfc" id="L1376" title="All 2 branches covered."> } else if (x509Token.isRequireThumbprintReference()) {</span>
<span class="fc" id="L1377"> secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);</span>
<span class="fc" id="L1378"> tokenTypeSet = true;</span>
}
}
<span class="fc bfc" id="L1382" title="All 2 branches covered."> if (!tokenTypeSet) {</span>
<span class="fc" id="L1383"> final RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="fc" id="L1384"> Wss10 wss = rpd.getWss11();</span>
<span class="pc bpc" id="L1385" title="1 of 2 branches missed."> if (wss == null) {</span>
<span class="fc" id="L1386"> wss = rpd.getWss10();</span>
}
<span class="fc bfc" id="L1389" title="All 2 branches covered."> if (wss.isMustSupportRefKeyIdentifier()) {</span>
<span class="fc" id="L1390"> secBase.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER);</span>
<span class="pc bpc" id="L1391" title="1 of 2 branches missed."> } else if (wss.isMustSupportRefIssuerSerial()) {</span>
<span class="nc" id="L1392"> secBase.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);</span>
<span class="pc bpc" id="L1393" title="3 of 4 branches missed."> } else if (wss instanceof Wss11</span>
&amp;&amp; ((Wss11) wss).isMustSupportRefThumbprint()) {
<span class="nc" id="L1395"> secBase.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);</span>
}
}
<span class="fc" id="L1399"> } else {</span>
<span class="fc" id="L1400"> secBase.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);</span>
}
<span class="fc" id="L1402"> }</span>
private static X509Certificate getReqSigCert(List&lt;WSHandlerResult&gt; results) {
/*
* Scan the results for a matching actor. Use results only if the
* receiving Actor and the sending Actor match.
*/
<span class="pc bpc" id="L1409" title="1 of 2 branches missed."> for (WSHandlerResult result : results) {</span>
<span class="fc" id="L1411"> List&lt;WSSecurityEngineResult&gt; wsSecEngineResults = result.getResults();</span>
/*
* Scan the results for the first Signature action. Use the
* certificate of this Signature to set the certificate for the
* encryption action :-).
*/
<span class="pc bpc" id="L1417" title="1 of 2 branches missed."> for (WSSecurityEngineResult wsSecEngineResult : wsSecEngineResults) {</span>
<span class="fc" id="L1418"> Integer actInt = (Integer) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);</span>
<span class="pc bpc" id="L1419" title="1 of 2 branches missed."> if (actInt == WSConstants.SIGN) {</span>
<span class="fc" id="L1420"> return (X509Certificate) wsSecEngineResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);</span>
}
<span class="nc" id="L1422"> }</span>
<span class="nc" id="L1423"> }</span>
<span class="nc" id="L1425"> return null;</span>
}
/**
* Scan through {@link WSHandlerResult} list for a Username token and return
* the username if a Username Token found
* @param results
* @return
*/
public static String getUsername(List&lt;WSHandlerResult&gt; results) {
/*
* Scan the results for a matching actor. Use results only if the
* receiving Actor and the sending Actor match.
*/
<span class="fc bfc" id="L1440" title="All 2 branches covered."> for (WSHandlerResult result : results) {</span>
<span class="fc" id="L1442"> List&lt;WSSecurityEngineResult&gt; wsSecEngineResults = result.getResults();</span>
/*
* Scan the results for a username token. Use the username
* of this token to set the alias for the encryption user
*/
<span class="fc bfc" id="L1447" title="All 2 branches covered."> for (WSSecurityEngineResult wsSecEngineResult : wsSecEngineResults) {</span>
<span class="fc" id="L1448"> Integer actInt = (Integer) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);</span>
<span class="pc bpc" id="L1449" title="1 of 2 branches missed."> if (actInt == WSConstants.UT) {</span>
<span class="nc" id="L1450"> WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) wsSecEngineResult.</span>
get(WSSecurityEngineResult.TAG_PRINCIPAL);
<span class="nc" id="L1452"> return principal.getName();</span>
}
<span class="fc" id="L1454"> }</span>
<span class="fc" id="L1455"> }</span>
<span class="fc" id="L1457"> return null;</span>
}
public static String getRequestEncryptedKeyId(List&lt;WSHandlerResult&gt; results) {
<span class="pc bpc" id="L1462" title="1 of 2 branches missed."> for (WSHandlerResult result : results) {</span>
<span class="fc" id="L1464"> List&lt;WSSecurityEngineResult&gt; wsSecEngineResults = result.getResults();</span>
/*
* Scan the results for the first Signature action. Use the
* certificate of this Signature to set the certificate for the
* encryption action :-).
*/
<span class="pc bpc" id="L1470" title="1 of 2 branches missed."> for (WSSecurityEngineResult wsSecEngineResult : wsSecEngineResults) {</span>
<span class="fc" id="L1471"> Integer actInt = (Integer) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);</span>
<span class="fc" id="L1472"> String encrKeyId = (String) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ID);</span>
<span class="pc bpc" id="L1473" title="1 of 4 branches missed."> if (actInt == WSConstants.ENCR &amp;&amp;</span>
encrKeyId != null) {
<span class="fc bfc" id="L1475" title="All 2 branches covered."> if (encrKeyId.length() &gt; 0) {</span>
<span class="fc" id="L1476"> return encrKeyId;</span>
}
<span class="pc bpc" id="L1478" title="1 of 2 branches missed."> else if (log.isDebugEnabled()) {</span>
<span class="nc" id="L1479"> log.debug(&quot;Found encryption security processing result with empty id, skipping it: &quot; + wsSecEngineResult);</span>
}
}
<span class="fc" id="L1482"> }</span>
<span class="nc" id="L1483"> }</span>
<span class="nc" id="L1485"> return null;</span>
}
public static byte[] getRequestEncryptedKeyValue(List&lt;WSHandlerResult&gt; results) {
<span class="pc bpc" id="L1490" title="1 of 2 branches missed."> for (WSHandlerResult result : results) {</span>
<span class="fc" id="L1492"> List&lt;WSSecurityEngineResult&gt; wsSecEngineResults = result.getResults();</span>
/*
* Scan the results for the first Signature action. Use the
* certificate of this Signature to set the certificate for the
* encryption action :-).
*/
<span class="pc bpc" id="L1498" title="1 of 2 branches missed."> for (WSSecurityEngineResult wsSecEngineResult : wsSecEngineResults) {</span>
<span class="fc" id="L1499"> Integer actInt = (Integer) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);</span>
<span class="fc" id="L1500"> byte[] decryptedKey = (byte[]) wsSecEngineResult.get(WSSecurityEngineResult.TAG_SECRET);</span>
<span class="fc bfc" id="L1501" title="All 4 branches covered."> if (actInt == WSConstants.ENCR &amp;&amp;</span>
decryptedKey != null) {
<span class="fc" id="L1503"> return decryptedKey;</span>
}
<span class="fc" id="L1505"> }</span>
<span class="nc" id="L1506"> }</span>
<span class="nc" id="L1508"> return null;</span>
}
/**
* If the child is present insert the element as a sibling after him.
*
* If the child is null, then prepend the element.
*
* @param rmd
* @param child
* @param elem - element mentioned above
* @return
*/
public static Element insertSiblingAfterOrPrepend(RampartMessageData rmd, Element child, Element elem) {
<span class="fc" id="L1522"> Element retElem = null;</span>
<span class="fc bfc" id="L1523" title="All 2 branches covered."> if (child != null) { // child is not null so insert sibling after</span>
<span class="fc" id="L1524"> retElem = RampartUtil.insertSiblingAfter(rmd, child, elem);</span>
} else { //Prepend
<span class="fc" id="L1526"> retElem = prependSecHeader(rmd, elem);</span>
}
<span class="fc" id="L1529"> return retElem;</span>
}
public static Element insertSiblingBeforeOrPrepend(RampartMessageData rmd, Element child, Element elem) {
<span class="fc" id="L1533"> Element retElem = null;</span>
<span class="fc bfc" id="L1534" title="All 4 branches covered."> if (child != null &amp;&amp; child.getPreviousSibling() != null) {</span>
<span class="fc" id="L1535"> retElem = RampartUtil.insertSiblingBefore(rmd, child, elem);</span>
} else { //Prepend
<span class="fc" id="L1537"> retElem = prependSecHeader(rmd, elem);</span>
}
<span class="fc" id="L1540"> return retElem;</span>
}
private static Element prependSecHeader(RampartMessageData rmd, Element elem) {
<span class="fc" id="L1544"> Element retElem = null;</span>
<span class="fc" id="L1546"> Element secHeaderElem = rmd.getSecHeader().getSecurityHeader();</span>
<span class="fc" id="L1547"> Node node = secHeaderElem.getOwnerDocument().importNode(</span>
elem, true);
<span class="fc" id="L1549"> Element firstElem = (Element) secHeaderElem.getFirstChild();</span>
<span class="fc bfc" id="L1551" title="All 2 branches covered."> if (firstElem == null) {</span>
<span class="fc" id="L1552"> retElem = (Element) secHeaderElem.appendChild(node);</span>
} else {
<span class="pc bpc" id="L1554" title="1 of 2 branches missed."> if (firstElem.getOwnerDocument().equals(elem.getOwnerDocument())) {</span>
<span class="fc" id="L1555"> ((OMElement) firstElem).insertSiblingBefore((OMElement) elem);</span>
<span class="fc" id="L1556"> retElem = elem;</span>
} else {
<span class="nc" id="L1558"> Element newSib = (Element) firstElem.getOwnerDocument().importNode(elem, true);</span>
<span class="nc" id="L1559"> ((OMElement) firstElem).insertSiblingBefore((OMElement) newSib);</span>
<span class="nc" id="L1560"> retElem = newSib;</span>
}
}
<span class="fc" id="L1564"> return retElem;</span>
}
/**
* Method to check whether security header is required in incoming message
* @param rpd
* @return true if a security header is required in the incoming message
*/
public static boolean isSecHeaderRequired(RampartPolicyData rpd, boolean initiator,
boolean inflow ) {
// Checking for time stamp
<span class="fc bfc" id="L1576" title="All 2 branches covered."> if ( rpd.isIncludeTimestamp() ) {</span>
<span class="fc" id="L1577"> return true;</span>
}
// Checking for signed parts and elements
<span class="pc bpc" id="L1581" title="2 of 6 branches missed."> if (rpd.isSignBody() || rpd.getSignedParts().size() != 0 || </span>
rpd.getSignedElements().size() != 0) {
<span class="fc" id="L1583"> return true;</span>
}
// Checking for encrypted parts and elements
<span class="pc bpc" id="L1587" title="1 of 6 branches missed."> if (rpd.isEncryptBody() || rpd.getEncryptedParts().size() != 0 || </span>
rpd.getEncryptedElements().size() != 0 ) {
<span class="fc" id="L1589"> return true;</span>
}
// Checking for supporting tokens
SupportingToken supportingTokens;
<span class="pc bpc" id="L1595" title="3 of 8 branches missed."> if (!initiator &amp;&amp; inflow || initiator &amp;&amp; !inflow ) {</span>
<span class="fc" id="L1597"> List&lt;SupportingToken&gt; supportingToks = rpd.getSupportingTokensList();</span>
<span class="pc bpc" id="L1598" title="1 of 2 branches missed."> for (SupportingToken supportingTok : supportingToks) {</span>
<span class="nc bnc" id="L1599" title="All 4 branches missed."> if (supportingTok != null &amp;&amp; supportingTok.getTokens().size() != 0) {</span>
<span class="nc" id="L1600"> return true;</span>
}
<span class="nc" id="L1602"> }</span>
<span class="fc" id="L1604"> supportingTokens = rpd.getSignedSupportingTokens();</span>
<span class="pc bpc" id="L1605" title="2 of 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="fc" id="L1606"> return true;</span>
}
<span class="nc" id="L1609"> supportingTokens = rpd.getEndorsingSupportingTokens();</span>
<span class="nc bnc" id="L1610" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1611"> return true;</span>
}
<span class="nc" id="L1614"> supportingTokens = rpd.getSignedEndorsingSupportingTokens();</span>
<span class="nc bnc" id="L1615" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1616"> return true;</span>
}
<span class="nc" id="L1619"> supportingTokens = rpd.getEncryptedSupportingTokens();</span>
<span class="nc bnc" id="L1620" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1621"> return true;</span>
}
<span class="nc" id="L1624"> supportingTokens = rpd.getSignedEncryptedSupportingTokens();</span>
<span class="nc bnc" id="L1625" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1626"> return true;</span>
}
<span class="nc" id="L1629"> supportingTokens = rpd.getEndorsingEncryptedSupportingTokens();</span>
<span class="nc bnc" id="L1630" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1631"> return true;</span>
}
<span class="nc" id="L1634"> supportingTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();</span>
<span class="nc bnc" id="L1635" title="All 4 branches missed."> if (supportingTokens != null &amp;&amp; supportingTokens.getTokens().size() != 0) {</span>
<span class="nc" id="L1636"> return true;</span>
}
}
<span class="nc" id="L1640"> return false;</span>
}
public static void handleEncryptedSignedHeaders(List&lt;WSEncryptionPart&gt; encryptedParts,
List&lt;WSEncryptionPart&gt; signedParts, Document doc) {
//TODO Is there a more efficient way to do this ? better search algorithm
<span class="fc bfc" id="L1648" title="All 2 branches covered."> for (WSEncryptionPart signedPart : signedParts) {</span>
//This signed part is not a header
<span class="pc bpc" id="L1650" title="1 of 4 branches missed."> if (signedPart.getNamespace() == null || signedPart.getName() == null) {</span>
<span class="nc" id="L1651"> continue;</span>
}
<span class="fc bfc" id="L1654" title="All 2 branches covered."> for (WSEncryptionPart encryptedPart : encryptedParts) {</span>
<span class="pc bpc" id="L1656" title="1 of 4 branches missed."> if (encryptedPart.getNamespace() == null || encryptedPart.getName() == null) {</span>
<span class="nc" id="L1657"> continue;</span>
}
<span class="pc bpc" id="L1660" title="2 of 4 branches missed."> if (signedPart.getName().equals(encryptedPart.getName()) &amp;&amp;</span>
signedPart.getNamespace().equals(encryptedPart.getNamespace())) {
<span class="fc" id="L1663"> String encDataID = encryptedPart.getEncId();</span>
// TODO Do we need to go through the whole tree to find element by id ? Verify
<span class="fc" id="L1666"> Element encDataElem = WSSecurityUtil.findElementById(doc.getDocumentElement(), encDataID, false);</span>
<span class="pc bpc" id="L1668" title="1 of 2 branches missed."> if (encDataElem != null) {</span>
<span class="fc" id="L1669"> Element encHeader = (Element) encDataElem.getParentNode();</span>
<span class="fc" id="L1670"> String encHeaderId = encHeader.getAttributeNS(WSConstants.WSU_NS, &quot;Id&quot;);</span>
//For some reason the id might not be available
// so the part/element with empty/null id won't be recognized afterwards.
<span class="pc bpc" id="L1674" title="2 of 4 branches missed."> if (encHeaderId != null &amp;&amp; !&quot;&quot;.equals(encHeaderId.trim())) {</span>
<span class="fc" id="L1675"> signedParts.remove(signedPart);</span>
<span class="fc" id="L1677"> signedParts.add(createEncryptionPart(signedPart.getName(), encHeaderId,</span>
signedPart.getNamespace(),
signedPart.getEncModifier(), signedPart.getXpath()));
}
}
}
<span class="fc" id="L1684"> }</span>
<span class="fc" id="L1687"> }</span>
<span class="fc" id="L1689"> }</span>
public static String getSigElementId(RampartMessageData rmd) {
<span class="fc" id="L1693"> SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();</span>
<span class="fc" id="L1695"> SOAPHeader header = envelope.getHeader();</span>
<span class="pc bpc" id="L1697" title="1 of 2 branches missed."> if (header == null ) {</span>
<span class="nc" id="L1698"> return null;</span>
}
<span class="fc" id="L1701"> ArrayList secHeaders = header.getHeaderBlocksWithNSURI(WSConstants.WSSE_NS);</span>
<span class="pc bpc" id="L1703" title="2 of 4 branches missed."> if (secHeaders != null &amp;&amp; secHeaders.size() &gt; 0) {</span>
<span class="fc" id="L1704"> QName sigQName = new QName(Constants.SignatureSpecNS,Constants._TAG_SIGNATURE);</span>
<span class="fc" id="L1705"> QName wsuIdQName = new QName(WSConstants.WSU_NS,&quot;Id&quot;);</span>
<span class="fc" id="L1706"> OMElement sigElem = ((SOAPHeaderBlock)secHeaders.get(0)).getFirstChildWithName(sigQName);</span>
<span class="fc" id="L1707"> OMAttribute wsuId = sigElem.getAttribute(wsuIdQName);</span>
<span class="pc bpc" id="L1709" title="1 of 2 branches missed."> if (wsuId != null) {</span>
<span class="nc" id="L1710"> return wsuId.getAttributeValue();</span>
}
<span class="fc" id="L1713"> wsuId = sigElem.getAttribute(new QName(&quot;Id&quot;));</span>
<span class="pc bpc" id="L1715" title="1 of 2 branches missed."> if (wsuId != null) {</span>
<span class="fc" id="L1716"> return wsuId.getAttributeValue();</span>
}
}
<span class="nc" id="L1722"> return null;</span>
}
/**
* We use this method to prevent the singleton behavior of WSSConfig
* @return WSSConfig object with the latest settings.
*/
public static WSSConfig getWSSConfigInstance() {
<span class="nc" id="L1732"> WSSConfig defaultWssConfig = WSSConfig.getNewInstance();</span>
<span class="nc" id="L1733"> WSSConfig wssConfig = WSSConfig.getNewInstance();</span>
<span class="nc" id="L1735"> wssConfig.setEnableSignatureConfirmation(defaultWssConfig.isEnableSignatureConfirmation());</span>
<span class="nc" id="L1736"> wssConfig.setTimeStampStrict(defaultWssConfig.isTimeStampStrict());</span>
<span class="nc" id="L1737"> wssConfig.setWsiBSPCompliant(defaultWssConfig.isWsiBSPCompliant());</span>
<span class="nc" id="L1738"> wssConfig.setPrecisionInMilliSeconds(defaultWssConfig.isPrecisionInMilliSeconds());</span>
<span class="nc" id="L1740"> return wssConfig;</span>
}
public static void validateTransport(RampartMessageData rmd) throws RampartException {
<span class="fc" id="L1746"> RampartPolicyData rpd = rmd.getPolicyData();</span>
<span class="pc bpc" id="L1748" title="1 of 2 branches missed."> if (rpd == null) {</span>
<span class="nc" id="L1749"> return;</span>
}
<span class="fc bfc" id="L1752" title="All 4 branches covered."> if (rpd.isTransportBinding() &amp;&amp; !rmd.isInitiator()) {</span>
<span class="fc bfc" id="L1753" title="All 2 branches covered."> if (rpd.getTransportToken() instanceof HttpsToken) {</span>
<span class="fc" id="L1754"> String incomingTransport = rmd.getMsgContext().getIncomingTransportName();</span>
<span class="pc bpc" id="L1755" title="1 of 2 branches missed."> if (!incomingTransport.equals(org.apache.axis2.Constants.TRANSPORT_HTTPS)) {</span>
<span class="nc" id="L1756"> throw new RampartException(&quot;invalidTransport&quot;,</span>
new String[]{incomingTransport});
}
<span class="pc bpc" id="L1759" title="1 of 2 branches missed."> if (((HttpsToken) rpd.getTransportToken()).isRequireClientCertificate()) {</span>
<span class="nc" id="L1761"> MessageContext messageContext = rmd.getMsgContext();</span>
<span class="nc" id="L1762"> HttpServletRequest request = ((HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST));</span>
<span class="nc bnc" id="L1763" title="All 4 branches missed."> if (request == null || request.getAttribute(&quot;javax.servlet.request.X509Certificate&quot;) == null) {</span>
<span class="nc" id="L1764"> throw new RampartException(&quot;clientAuthRequired&quot;);</span>
}
}
}
}
<span class="fc" id="L1770"> }</span>
private static Crypto retrieveCryptoFromCache(String cryptoKey, String refreshInterval) {
// cache hit
<span class="fc bfc" id="L1774" title="All 2 branches covered."> if (cryptoStore.containsKey(cryptoKey)) {</span>
<span class="fc" id="L1775"> CachedCrypto cachedCrypto = cryptoStore.get(cryptoKey);</span>
<span class="pc bpc" id="L1776" title="1 of 2 branches missed."> if (refreshInterval != null) {</span>
<span class="nc bnc" id="L1777" title="All 2 branches missed."> if (cachedCrypto.creationTime + new Long(refreshInterval).longValue() &gt; Calendar</span>
.getInstance().getTimeInMillis()) {
<span class="nc" id="L1779"> log.debug(&quot;Cache Hit : Crypto Object was found in cache.&quot;);</span>
<span class="nc" id="L1780"> return cachedCrypto.crypto;</span>
} else {
<span class="nc" id="L1782"> log.debug(&quot;Cache Miss : Crypto Object found in cache is expired.&quot;);</span>
<span class="nc" id="L1783"> return null;</span>
}
} else {
<span class="fc" id="L1786"> log.debug(&quot;Cache Hit : Crypto Object was found in cache.&quot;);</span>
<span class="fc" id="L1787"> return cachedCrypto.crypto;</span>
}
}
// cache miss
else {
<span class="fc" id="L1792"> log.debug(&quot;Cache Miss : Crypto Object was not found in cache.&quot;);</span>
<span class="fc" id="L1793"> return null;</span>
}
}
private static void cacheCrypto(String cryptoKey, Crypto crypto) {
<span class="fc" id="L1798"> cryptoStore.put(cryptoKey, new CachedCrypto(crypto, Calendar.getInstance()</span>
.getTimeInMillis()));
<span class="fc" id="L1800"> log.debug(&quot;Crypto object is inserted into the Cache.&quot;);</span>
<span class="fc" id="L1802"> }</span>
/**
* Returns SAML10 Assertion namespace. As follows,
* http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID
* @return SAML10 assertion namespace.
*/
public static String getSAML10AssertionNamespace() {
<span class="nc" id="L1811"> StringBuilder stringBuilder = new StringBuilder(WSConstants.SAMLTOKEN_NS);</span>
<span class="nc" id="L1812"> stringBuilder.append(&quot;#&quot;).append(WSConstants.SAML_ASSERTION_ID);</span>
<span class="nc" id="L1814"> return stringBuilder.toString();</span>
}
/**
* Sets encryption crypto file or crypto reference key to signature crypto file or signature
* crypto reference.
* @param msgContext The message context to get signature crypto properties and encryption properties
* will be set to same message context.
*/
public static void setEncryptionCrypto(MessageContext msgContext) {
<span class="nc" id="L1825"> setEncryptionCryptoFileProperty(msgContext);</span>
<span class="nc" id="L1826"> setEncryptionCryptoReferenceProperty(msgContext);</span>
<span class="nc" id="L1827"> }</span>
/**
* Sets decryption crypto file or crypto reference key to signature crypto file or signature
* crypto reference.
* @param msgContext The message context to get signature crypto properties and decryption properties
* will be set to same message context.
*/
public static void setDecryptionCrypto(MessageContext msgContext) {
<span class="nc" id="L1836"> setDecryptionCryptoFileProperty(msgContext);</span>
<span class="nc" id="L1837"> setDecryptionCryptoReferenceProperty(msgContext);</span>
<span class="nc" id="L1838"> }</span>
/**
* Sets encryption crypto property reference id.- WSHandlerConstants.ENC_PROP_REF_ID
* @param msgContext The message context.
*/
private static void setEncryptionCryptoReferenceProperty (MessageContext msgContext) {
<span class="nc" id="L1845"> setCryptoProperty(msgContext, WSHandlerConstants.SIG_PROP_REF_ID, WSHandlerConstants.ENC_PROP_REF_ID);</span>
<span class="nc" id="L1846"> }</span>
/**
* Sets encryption crypto property file.- WSHandlerConstants.DEC_PROP_REF_ID
* @param msgContext The message context.
*/
private static void setDecryptionCryptoReferenceProperty (MessageContext msgContext) {
<span class="nc" id="L1853"> setCryptoProperty(msgContext, WSHandlerConstants.SIG_PROP_REF_ID, WSHandlerConstants.DEC_PROP_REF_ID);</span>
<span class="nc" id="L1854"> }</span>
/**
* Sets encryption crypto property file.- WSHandlerConstants.ENC_PROP_FILE
* @param msgContext The message context.
*/
private static void setEncryptionCryptoFileProperty (MessageContext msgContext) {
<span class="nc" id="L1861"> setCryptoProperty(msgContext, WSHandlerConstants.SIG_PROP_FILE, WSHandlerConstants.ENC_PROP_FILE);</span>
<span class="nc" id="L1862"> }</span>
/**
* Sets encryption crypto property file.- WSHandlerConstants.DEC_PROP_FILE
* @param msgContext The message context.
*/
private static void setDecryptionCryptoFileProperty (MessageContext msgContext) {
<span class="nc" id="L1869"> setCryptoProperty(msgContext, WSHandlerConstants.SIG_PROP_FILE, WSHandlerConstants.DEC_PROP_FILE);</span>
<span class="nc" id="L1870"> }</span>
private static void setCryptoProperty(MessageContext msgContext, String signaturePropertyName,
String cryptoPropertyName){
/**
* Encryption Crypto is loaded using WSHandlerConstants.ENC_PROP_FILE. If this is not
* set in the message context set WSHandlerConstants.SIG_PROP_FILE as WSHandlerConstants.ENC_PROP_FILE.
*/
<span class="nc bnc" id="L1879" title="All 2 branches missed."> if (msgContext.getProperty(cryptoPropertyName) == null) {</span>
<span class="nc" id="L1882"> String signaturePropertyFile = (String)msgContext.getProperty(signaturePropertyName);</span>
<span class="nc bnc" id="L1884" title="All 2 branches missed."> if (signaturePropertyFile == null) {</span>
<span class="nc bnc" id="L1886" title="All 2 branches missed."> if (log.isDebugEnabled()) {</span>
<span class="nc" id="L1887"> log.debug(&quot;Signature crypto property file is not set. Property file key - &quot;</span>
+ WSHandlerConstants.SIG_PROP_FILE);
}
} else {
<span class="nc" id="L1891"> msgContext.setProperty(cryptoPropertyName, signaturePropertyFile);</span>
}
}
<span class="nc" id="L1894"> }</span>
/**
* Returns true if needed to encrypt first.
* @param rpd Rampart policy data
* @return true if policy says we need to encrypt first else false.
*/
public static boolean encryptFirst(RampartPolicyData rpd) {
<span class="fc" id="L1902"> return SPConstants.ENCRYPT_BEFORE_SIGNING.equals(rpd.getProtectionOrder());</span>
}
/**
* Check if the given SOAP fault reports a security fault.
*
* @param fault
* the SOAP fault; must not be &lt;code&gt;null&lt;/code&gt;
* @return &lt;code&gt;true&lt;/code&gt; if the fault is a security fault; &lt;code&gt;false&lt;/code&gt; otherwise
*/
public static boolean isSecurityFault(SOAPFault fault) {
<span class="fc" id="L1913"> String soapVersionURI = fault.getNamespaceURI();</span>
<span class="fc" id="L1914"> SOAPFaultCode code = fault.getCode();</span>
<span class="pc bpc" id="L1915" title="1 of 2 branches missed."> if (code == null) {</span>
// If no fault code is given, then it can't be security fault
<span class="nc" id="L1917"> return false;</span>
<span class="fc bfc" id="L1918" title="All 2 branches covered."> } else if (soapVersionURI.equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {</span>
<span class="fc" id="L1919"> return isSecurityFaultCode(code);</span>
} else {
// For SOAP 1.2 security faults, the fault code is env:Sender, and the security fault code is
// specified in the subcode
<span class="fc" id="L1923"> SOAPFaultSubCode subCode = code.getSubCode();</span>
<span class="pc bpc" id="L1924" title="1 of 2 branches missed."> return subCode == null ? false : isSecurityFaultCode(subCode);</span>
}
}
private static boolean isSecurityFaultCode(SOAPFaultClassifier code) {
<span class="fc" id="L1929"> QName value = code.getValueAsQName();</span>
<span class="fc bfc" id="L1930" title="All 2 branches covered."> return value == null ? false : value.getNamespaceURI().equals(WSConstants.WSSE_NS);</span>
}
/**
* @param rpd Rampart policy data instance. Must not be null.
* @return A collection of all {@link UsernameToken} supporting token assertions in the specified Rampart policy instance. The method will check the following lists:
* &lt;ul&gt;
* &lt;li&gt;{@link RampartPolicyData#getSupportingTokensList()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getSignedSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getSignedEndorsingSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getEndorsingSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getEncryptedSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getSignedEncryptedSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getEndorsingEncryptedSupportingTokens()}&lt;/li&gt;
* &lt;li&gt;{@link RampartPolicyData#getSignedEndorsingEncryptedSupportingTokens()}&lt;/li&gt;
* &lt;/ul&gt;
*/
public static Collection&lt;UsernameToken&gt; getUsernameTokens(RampartPolicyData rpd) {
<span class="fc" id="L1948"> Collection&lt;UsernameToken&gt; usernameTokens = new ArrayList&lt;UsernameToken&gt;();</span>
<span class="fc" id="L1950"> List&lt;SupportingToken&gt; supportingToks = rpd.getSupportingTokensList();</span>
<span class="fc bfc" id="L1951" title="All 2 branches covered."> for (SupportingToken suppTok : supportingToks) {</span>
<span class="fc" id="L1952"> usernameTokens.addAll(getUsernameTokens(suppTok));</span>
<span class="fc" id="L1953"> }</span>
<span class="fc" id="L1955"> usernameTokens.addAll(getUsernameTokens(rpd.getSignedSupportingTokens()));</span>
<span class="fc" id="L1956"> usernameTokens.addAll(getUsernameTokens(rpd.getSignedEndorsingSupportingTokens()));</span>
<span class="fc" id="L1957"> usernameTokens.addAll(getUsernameTokens(rpd.getEndorsingSupportingTokens()));</span>
<span class="fc" id="L1958"> usernameTokens.addAll(getUsernameTokens(rpd.getEncryptedSupportingTokens()));</span>
<span class="fc" id="L1959"> usernameTokens.addAll(getUsernameTokens(rpd.getSignedEncryptedSupportingTokens()));</span>
<span class="fc" id="L1960"> usernameTokens.addAll(getUsernameTokens(rpd.getEndorsingEncryptedSupportingTokens()));</span>
<span class="fc" id="L1961"> usernameTokens.addAll(getUsernameTokens(rpd.getSignedEndorsingEncryptedSupportingTokens()));</span>
<span class="fc" id="L1963"> return usernameTokens;</span>
}
/**
* @param suppTok The {@link SupportingToken} assertion to check for username tokens.
* @return A collection of all tokens in the specified &lt;code&gt;suppTok&lt;/code&gt; SupportingToken assertion which are instances of {@link UsernameToken}.
* If the specified &lt;code&gt;suppTok&lt;/code&gt; SupportingToken assertion is &lt;code&gt;null&lt;/code&gt;, an empty collection will be returned.
*/
public static Collection&lt;UsernameToken&gt; getUsernameTokens(SupportingToken suppTok) {
<span class="fc bfc" id="L1973" title="All 2 branches covered."> if (suppTok == null) {</span>
<span class="fc" id="L1974"> return new ArrayList&lt;UsernameToken&gt;();</span>
}
<span class="fc" id="L1977"> Collection&lt;UsernameToken&gt; usernameTokens = new ArrayList&lt;UsernameToken&gt;();</span>
<span class="fc" id="L1978"> ArrayList tokens = suppTok.getTokens();</span>
<span class="fc bfc" id="L1979" title="All 2 branches covered."> for (Iterator iter = tokens.iterator(); iter.hasNext();) {</span>
<span class="fc" id="L1980"> org.apache.ws.secpolicy.model.Token token = (org.apache.ws.secpolicy.model.Token) iter.next();</span>
<span class="fc bfc" id="L1981" title="All 2 branches covered."> if (token instanceof UsernameToken) {</span>
<span class="fc" id="L1982"> usernameTokens.add((UsernameToken)token);</span>
}
<span class="fc" id="L1984"> }</span>
<span class="fc" id="L1986"> return usernameTokens;</span>
}
}
</pre><div class="footer"><span class="right">Created with <a href="http://www.eclemma.org/jacoco">JaCoCo</a> 0.7.5.201505241946</span></div></body></html>