Home » rampart-dist-1.4-src » org.apache » rampart » builder » [javadoc | source]

    1   /*
    2    * Copyright 2004,2005 The Apache Software Foundation.
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License");
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *      http://www.apache.org/licenses/LICENSE-2.0
    9    *
   10    * Unless required by applicable law or agreed to in writing, software
   11    * distributed under the License is distributed on an "AS IS" BASIS,
   12    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   13    * See the License for the specific language governing permissions and
   14    * limitations under the License.
   15    */
   16   
   17   package org.apache.rampart.builder;
   18   
   19   import org.apache.axiom.om.OMElement;
   20   import org.apache.axis2.client.Options;
   21   import org.apache.commons.logging.Log;
   22   import org.apache.commons.logging.LogFactory;
   23   import org.apache.rahas.EncryptedKeyToken;
   24   import org.apache.rahas.SimpleTokenStore;
   25   import org.apache.rahas.TrustException;
   26   import org.apache.rampart.RampartException;
   27   import org.apache.rampart.RampartMessageData;
   28   import org.apache.rampart.policy.RampartPolicyData;
   29   import org.apache.rampart.util.RampartUtil;
   30   import org.apache.ws.secpolicy.Constants;
   31   import org.apache.ws.secpolicy.SPConstants;
   32   import org.apache.ws.secpolicy.model.IssuedToken;
   33   import org.apache.ws.secpolicy.model.SecureConversationToken;
   34   import org.apache.ws.secpolicy.model.SupportingToken;
   35   import org.apache.ws.secpolicy.model.Token;
   36   import org.apache.ws.secpolicy.model.UsernameToken;
   37   import org.apache.ws.secpolicy.model.X509Token;
   38   import org.apache.ws.security.WSConstants;
   39   import org.apache.ws.security.WSEncryptionPart;
   40   import org.apache.ws.security.WSPasswordCallback;
   41   import org.apache.ws.security.WSSecurityEngineResult;
   42   import org.apache.ws.security.WSSecurityException;
   43   import org.apache.ws.security.conversation.ConversationException;
   44   import org.apache.ws.security.handler.WSHandlerConstants;
   45   import org.apache.ws.security.handler.WSHandlerResult;
   46   import org.apache.ws.security.message.WSSecDKSign;
   47   import org.apache.ws.security.message.WSSecEncryptedKey;
   48   import org.apache.ws.security.message.WSSecSignature;
   49   import org.apache.ws.security.message.WSSecSignatureConfirmation;
   50   import org.apache.ws.security.message.WSSecTimestamp;
   51   import org.apache.ws.security.message.WSSecUsernameToken;
   52   import org.apache.ws.security.message.token.SecurityTokenReference;
   53   import org.apache.ws.security.util.WSSecurityUtil;
   54   import org.w3c.dom.Document;
   55   import org.w3c.dom.Element;
   56   
   57   import javax.security.auth.callback.CallbackHandler;
   58   import javax.security.auth.callback.UnsupportedCallbackException;
   59   
   60   import java.io.IOException;
   61   import java.util.ArrayList;
   62   import java.util.Date;
   63   import java.util.HashMap;
   64   import java.util.Iterator;
   65   import java.util.Set;
   66   import java.util.Vector;
   67   import java.util.Map.Entry;
   68   
   69   public abstract class BindingBuilder {
   70       private static Log log = LogFactory.getLog(BindingBuilder.class);
   71               
   72       private Element insertionLocation;
   73       
   74       protected String mainSigId = null;
   75       
   76       protected ArrayList encryptedTokensIdList = new ArrayList();
   77       
   78       protected Element timestampElement;
   79       
   80       protected Element mainRefListElement;
   81       
   82       
   83       /**
   84        * @param rmd
   85        */
   86       protected void addTimestamp(RampartMessageData rmd) {
   87           log.debug("Adding timestamp");
   88           
   89           WSSecTimestamp timestampBuilder = new WSSecTimestamp();
   90           timestampBuilder.setWsConfig(rmd.getConfig());
   91   
   92           timestampBuilder.setTimeToLive(RampartUtil.getTimeToLive(rmd));
   93           
   94           // add the Timestamp to the SOAP Enevelope
   95   
   96           timestampBuilder.build(rmd.getDocument(), rmd
   97                   .getSecHeader());
   98           
   99           log.debug("Timestamp id: " + timestampBuilder.getId());
  100   
  101           rmd.setTimestampId(timestampBuilder.getId());
  102           
  103           this.timestampElement = timestampBuilder.getElement();
  104           log.debug("Adding timestamp: DONE");
  105       }
  106       
  107       /**
  108        * Add a UsernameToken to the security header
  109        * @param rmd
  110        * @return The <code>WSSecUsernameToken</code> instance
  111        * @throws RampartException
  112        */
  113       protected WSSecUsernameToken addUsernameToken(RampartMessageData rmd, UsernameToken token) throws RampartException {
  114          
  115           log.debug("Adding a UsernameToken");
  116           
  117           RampartPolicyData rpd = rmd.getPolicyData();
  118           
  119           //Get the user
  120           //First try options
  121           Options options = rmd.getMsgContext().getOptions();
  122           String user = options.getUserName();
  123           if(user == null || user.length() == 0) {
  124               //Then try RampartConfig
  125               if(rpd.getRampartConfig() != null) {
  126                   user = rpd.getRampartConfig().getUser();
  127               }
  128           }
  129           
  130           if(user != null && !"".equals(user)) {
  131               log.debug("User : " + user);
  132               
  133               // If NoPassword property is set we don't need to set the password
  134               if (token.isNoPassword()) {
  135                   WSSecUsernameToken utBuilder = new WSSecUsernameToken();
  136                   utBuilder.setUserInfo(user, null);
  137                   utBuilder.setPasswordType(null);
  138                   if (rmd.getConfig() != null) {
  139                       utBuilder.setWsConfig(rmd.getConfig());
  140                   }
  141                   return utBuilder;
  142               }
  143               
  144               //Get the password
  145   
  146               //First check options object for a password
  147               String password = options.getPassword();
  148               
  149               if(password == null || password.length() == 0) {
  150                   
  151                   //Then try to get the password from the given callback handler
  152                   CallbackHandler handler = RampartUtil.getPasswordCB(rmd);
  153               
  154                   if(handler == null) {
  155                       //If the callback handler is missing
  156                       throw new RampartException("cbHandlerMissing");
  157                   }
  158                   
  159                   WSPasswordCallback[] cb = { new WSPasswordCallback(user,
  160                           WSPasswordCallback.USERNAME_TOKEN) };
  161                   try {
  162                       handler.handle(cb);
  163                   } catch (Exception e) {
  164                       throw new RampartException("errorInGettingPasswordForUser", 
  165                               new String[]{user}, e);
  166                   }
  167                   
  168                   //get the password
  169                   password = cb[0].getPassword();
  170               }
  171               
  172               log.debug("Password : " + password);
  173               
  174               if(password != null && !"".equals(password)) {
  175                   //If the password is available then build the token
  176                   
  177                   WSSecUsernameToken utBuilder = new WSSecUsernameToken();
  178                   if(rmd.getConfig() != null) {
  179                       utBuilder.setWsConfig(rmd.getConfig());
  180                   }
  181                   if (token.isHashPassword()) {
  182                       utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);  
  183                   } else {
  184                       utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
  185                   }
  186                   
  187                   utBuilder.setUserInfo(user, password);
  188                   
  189                   return utBuilder;
  190               } else {
  191                   //If there's no password then throw an exception
  192                   throw new RampartException("noPasswordForUser", 
  193                           new String[]{user});
  194               }
  195               
  196           } else {
  197               log.debug("No user value specified in the configuration");
  198               throw new RampartException("userMissing");
  199           }
  200           
  201       }
  202       
  203       
  204       /**
  205        * @param rmd
  206        * @param token
  207        * @return
  208        * @throws WSSecurityException
  209        * @throws RampartException
  210        */
  211       protected WSSecEncryptedKey getEncryptedKeyBuilder(RampartMessageData rmd, Token token) throws RampartException {
  212           
  213           RampartPolicyData rpd = rmd.getPolicyData();
  214           Document doc = rmd.getDocument();
  215           
  216           WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
  217           
  218           try {
  219               RampartUtil.setKeyIdentifierType(rpd, encrKey, token);
  220               RampartUtil.setEncryptionUser(rmd, encrKey);
  221               encrKey.setKeySize(rpd.getAlgorithmSuite().getMaximumSymmetricKeyLength());
  222               encrKey.setKeyEncAlgo(rpd.getAlgorithmSuite().getAsymmetricKeyWrap());
  223               
  224               encrKey.prepare(doc, RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));
  225               
  226               return encrKey;
  227           } catch (WSSecurityException e) {
  228               throw new RampartException("errorCreatingEncryptedKey", e);
  229           }
  230       }
  231       
  232       
  233       protected WSSecSignature getSignatureBuider(RampartMessageData rmd, Token token) throws RampartException {
  234   
  235           RampartPolicyData rpd = rmd.getPolicyData();
  236           
  237           WSSecSignature sig = new WSSecSignature();
  238           checkForX509PkiPath(sig, token);
  239           sig.setWsConfig(rmd.getConfig());
  240           
  241           log.debug("Token inclusion: " + token.getInclusion());
  242           
  243           RampartUtil.setKeyIdentifierType(rpd, sig, token);
  244   
  245           String user = null;
  246           
  247           // Get the user - First check whether userCertAlias present
  248           user = rpd.getRampartConfig().getUserCertAlias();
  249           
  250           // If userCertAlias is not present, use user property as Alias
  251           
  252           if (user == null) {
  253               user = rpd.getRampartConfig().getUser();
  254           }
  255               
  256           String password = null;
  257   
  258           if(user != null && !"".equals(user)) {
  259               log.debug("User : " + user);
  260               
  261               //Get the password
  262               CallbackHandler handler = RampartUtil.getPasswordCB(rmd);
  263               
  264               if(handler == null) {
  265                   //If the callback handler is missing
  266                   throw new RampartException("cbHandlerMissing");
  267               }
  268               
  269               WSPasswordCallback[] cb = { new WSPasswordCallback(user,
  270                       WSPasswordCallback.SIGNATURE) };
  271               
  272               try {
  273                   handler.handle(cb);
  274                   if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
  275                       password = cb[0].getPassword();
  276                       log.debug("Password : " + password);
  277                   } else {
  278                       //If there's no password then throw an exception
  279                       throw new RampartException("noPasswordForUser", 
  280                               new String[]{user});
  281                   }
  282               } catch (IOException e) {
  283                   throw new RampartException("errorInGettingPasswordForUser", 
  284                           new String[]{user}, e);
  285               } catch (UnsupportedCallbackException e) {
  286                   throw new RampartException("errorInGettingPasswordForUser", 
  287                           new String[]{user}, e);
  288               }
  289               
  290           } else {
  291               log.debug("No user value specified in the configuration");
  292               throw new RampartException("userMissing");
  293           }
  294           
  295           sig.setUserInfo(user, password);
  296           sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
  297           sig.setSigCanonicalization(rpd.getAlgorithmSuite().getInclusiveC14n());
  298           
  299           try {
  300               sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
  301                       .getRampartConfig(), rmd.getCustomClassLoader()), 
  302                       rmd.getSecHeader());
  303           } catch (WSSecurityException e) {
  304               throw new RampartException("errorInSignatureWithX509Token", e);
  305           }
  306           
  307           return sig;
  308       }
  309       
  310       /**
  311        * @param rmd
  312        * @param suppTokens
  313        * @throws RampartException
  314        */
  315       protected HashMap handleSupportingTokens(RampartMessageData rmd, SupportingToken suppTokens)
  316               throws RampartException {
  317           
  318           //Create the list to hold the tokens
  319           HashMap endSuppTokMap = new HashMap();
  320           
  321           if(suppTokens != null && suppTokens.getTokens() != null &&
  322                   suppTokens.getTokens().size() > 0) {
  323               log.debug("Processing supporting tokens");
  324               
  325               ArrayList tokens = suppTokens.getTokens();
  326               for (Iterator iter = tokens.iterator(); iter.hasNext();) {
  327                   Token token = (Token) iter.next();
  328                   org.apache.rahas.Token endSuppTok = null;
  329                   if(token instanceof IssuedToken && rmd.isInitiator()){
  330                       String id = RampartUtil.getIssuedToken(rmd, (IssuedToken)token);
  331                       try {
  332                           endSuppTok = rmd.getTokenStorage().getToken(id);
  333                       } catch (TrustException e) {
  334                           throw new RampartException("errorInRetrievingTokenId", 
  335                                   new String[]{id}, e);
  336                       }
  337                       
  338                       if(endSuppTok == null) {
  339                           throw new RampartException("errorInRetrievingTokenId", 
  340                                   new String[]{id});
  341                       }
  342                       
  343                       //Add the token to the header
  344                       Element siblingElem = RampartUtil
  345                               .insertSiblingAfter(rmd, this.getInsertionLocation(),
  346                                       (Element) endSuppTok.getToken());
  347                       this.setInsertionLocation(siblingElem);
  348                       
  349                       if (suppTokens.isEncryptedToken()) {
  350                           this.encryptedTokensIdList.add(endSuppTok.getId());
  351                       }
  352                       
  353                       //Add the extracted token
  354                       endSuppTokMap.put(token, endSuppTok);
  355                       
  356                   } else if(token instanceof X509Token) {
  357   
  358                           //We have to use a cert
  359                           //Prepare X509 signature
  360                           WSSecSignature sig = this.getSignatureBuider(rmd, token);
  361                           Element bstElem = sig.getBinarySecurityTokenElement();
  362                           if(bstElem != null) {   
  363                               bstElem = RampartUtil.insertSiblingAfter(rmd, 
  364                                       this.getInsertionLocation(), bstElem);
  365                               this.setInsertionLocation(bstElem);
  366                               
  367                               if (suppTokens.isEncryptedToken()) {
  368                                   this.encryptedTokensIdList.add(sig.getBSTTokenId());
  369                               }
  370                           }
  371                           endSuppTokMap.put(token, sig);
  372                           
  373                   } else if(token instanceof UsernameToken) {
  374                       WSSecUsernameToken utBuilder = addUsernameToken(rmd, (UsernameToken)token);
  375                       
  376                       utBuilder.prepare(rmd.getDocument());
  377                       
  378                       //Add the UT
  379                       Element elem = utBuilder.getUsernameTokenElement();
  380                       RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(), elem);
  381                       
  382                       encryptedTokensIdList.add(utBuilder.getId());
  383                       
  384                       //Move the insert location to the next element
  385                       this.setInsertionLocation(elem);
  386                       Date now = new Date();
  387                       try {
  388                           org.apache.rahas.Token tempTok = new org.apache.rahas.Token(
  389                                   utBuilder.getId(), (OMElement) elem, now,
  390                                   new Date(now.getTime() + 300000));
  391                           endSuppTokMap.put(token, tempTok);
  392                       } catch (TrustException e) {
  393                           throw new RampartException("errorCreatingRahasToken", e);
  394                       }
  395                   }
  396               }
  397           }
  398           
  399           return endSuppTokMap;
  400       }
  401       /**
  402        * @param tokenMap
  403        * @param sigParts
  404        * @throws RampartException
  405        */
  406       protected Vector addSignatureParts(HashMap tokenMap, Vector sigParts) throws RampartException {
  407       	
  408           Set entrySet = tokenMap.entrySet();
  409           
  410           for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
  411               Object tempTok =  ((Entry)iter.next()).getValue();
  412               WSEncryptionPart part = null;
  413               
  414               if(tempTok instanceof org.apache.rahas.Token) {
  415               	
  416                   part = new WSEncryptionPart(
  417                           ((org.apache.rahas.Token) tempTok).getId());
  418                   
  419               } else if(tempTok instanceof WSSecSignature) {
  420                   WSSecSignature tempSig = (WSSecSignature) tempTok;
  421                   if(tempSig.getBSTTokenId() != null) {
  422                       part = new WSEncryptionPart(tempSig.getBSTTokenId());
  423                   }
  424               } else {
  425               	
  426                 throw new RampartException("UnsupportedTokenInSupportingToken");  
  427               }
  428               sigParts.add(part);
  429           }
  430                   
  431           return sigParts;
  432       }
  433   
  434       
  435       public Element getInsertionLocation() {
  436           return insertionLocation;
  437       }
  438   
  439       public void setInsertionLocation(Element insertionLocation) {
  440           this.insertionLocation = insertionLocation;
  441       }
  442       
  443       
  444       protected Vector doEndorsedSignatures(RampartMessageData rmd, HashMap tokenMap) throws RampartException {
  445           
  446           Set tokenSet = tokenMap.keySet();
  447           
  448           Vector sigValues = new Vector();
  449           
  450           for (Iterator iter = tokenSet.iterator(); iter.hasNext();) {
  451               
  452               Token token = (Token)iter.next();
  453               
  454               Object tempTok = tokenMap.get(token);
  455               
  456               Vector sigParts = new Vector();
  457               sigParts.add(new WSEncryptionPart(this.mainSigId));
  458               
  459               if (tempTok instanceof org.apache.rahas.Token) {
  460                   org.apache.rahas.Token tok = (org.apache.rahas.Token)tempTok;
  461                   if(rmd.getPolicyData().isTokenProtection()) {
  462                       sigParts.add(new WSEncryptionPart(tok.getId()));
  463                   }
  464                   
  465                   this.doSymmSignature(rmd, token, (org.apache.rahas.Token)tempTok, sigParts);
  466                   
  467               } else if (tempTok instanceof WSSecSignature) {
  468                   WSSecSignature sig = (WSSecSignature)tempTok;
  469                   if(rmd.getPolicyData().isTokenProtection() &&
  470                           sig.getBSTTokenId() != null) {
  471                       sigParts.add(new WSEncryptionPart(sig.getBSTTokenId()));
  472                   }
  473                   
  474                   try {
  475                       sig.addReferencesToSign(sigParts, rmd.getSecHeader());
  476                       sig.computeSignature();
  477                       
  478                       this.setInsertionLocation(RampartUtil.insertSiblingAfter(
  479                               rmd, 
  480                               this.getInsertionLocation(), 
  481                               sig.getSignatureElement()));
  482                       
  483                   } catch (WSSecurityException e) {
  484                       throw new RampartException("errorInSignatureWithX509Token", e);
  485                   }
  486                   sigValues.add(sig.getSignatureValue());
  487               }
  488           } 
  489   
  490           return sigValues;
  491               
  492       }
  493       
  494       
  495       protected byte[] doSymmSignature(RampartMessageData rmd, Token policyToken, org.apache.rahas.Token tok, Vector sigParts) throws RampartException {
  496           
  497           Document doc = rmd.getDocument();
  498           
  499           RampartPolicyData rpd = rmd.getPolicyData();
  500           
  501           if(policyToken.isDerivedKeys()) {
  502               try {
  503                   WSSecDKSign dkSign = new WSSecDKSign();
  504                                 
  505                   //Check for whether the token is attached in the message or not
  506                   boolean attached = false;
  507                   
  508                   if (SPConstants.INCLUDE_TOEKN_ALWAYS == policyToken.getInclusion() ||
  509                       SPConstants.INCLUDE_TOKEN_ONCE == policyToken.getInclusion() ||
  510                       (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT 
  511                               == policyToken.getInclusion())) {
  512                       attached = true;
  513                   }
  514                   
  515                   // Setting the AttachedReference or the UnattachedReference according to the flag
  516                   OMElement ref;
  517                   if (attached == true) {
  518                       ref = tok.getAttachedReference();
  519                   } else {
  520                       ref = tok.getUnattachedReference();
  521                   }
  522                   
  523                   if(ref != null) {
  524                       dkSign.setExternalKey(tok.getSecret(), (Element) 
  525                               doc.importNode((Element) ref, true));
  526                   } else if (!rmd.isInitiator() && policyToken.isDerivedKeys()) { 
  527                   	
  528                   	// If the Encrypted key used to create the derived key is not
  529                   	// attached use key identifier as defined in WSS1.1 section
  530                   	// 7.7 Encrypted Key reference
  531                   	SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
  532                   	if(tok instanceof EncryptedKeyToken) {
  533                   	    tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken)tok).getSHA1());;
  534                   	}
  535                   	dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
  536                   
  537                   } else {
  538                       dkSign.setExternalKey(tok.getSecret(), tok.getId());
  539                   }
  540   
  541                   //Set the algo info
  542                   dkSign.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
  543                   dkSign.setDerivedKeyLength(rpd.getAlgorithmSuite().getSignatureDerivedKeyLength()/8);
  544                   if(tok instanceof EncryptedKeyToken) {
  545                       //Set the value type of the reference
  546                       dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
  547                           + WSConstants.ENC_KEY_VALUE_TYPE);
  548                   }
  549                   
  550                   dkSign.prepare(doc, rmd.getSecHeader());
  551                   
  552                   if(rpd.isTokenProtection()) {
  553   
  554                       //Hack to handle reference id issues
  555                       //TODO Need a better fix
  556                       String sigTokId = tok.getId();
  557                       if(sigTokId.startsWith("#")) {
  558                           sigTokId = sigTokId.substring(1);
  559                       }
  560                       sigParts.add(new WSEncryptionPart(sigTokId));
  561                   }
  562                   
  563                   dkSign.setParts(sigParts);
  564                   
  565                   dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
  566                   
  567                   //Do signature
  568                   dkSign.computeSignature();
  569   
  570                   //Add elements to header
  571                   
  572                   if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
  573                           this.getInsertionLocation() == null ) {
  574                       this.setInsertionLocation(RampartUtil
  575                               
  576                               .insertSiblingBefore(rmd, 
  577                                       this.mainRefListElement,
  578                                       dkSign.getdktElement()));
  579   
  580                           this.setInsertionLocation(RampartUtil.insertSiblingAfter(
  581                                   rmd, 
  582                                   this.getInsertionLocation(), 
  583                                   dkSign.getSignatureElement()));                
  584                   } else {
  585                       this.setInsertionLocation(RampartUtil
  586                   
  587                           .insertSiblingAfter(rmd, 
  588                                   this.getInsertionLocation(),
  589                                   dkSign.getdktElement()));
  590   
  591                       this.setInsertionLocation(RampartUtil.insertSiblingAfter(
  592                               rmd, 
  593                               this.getInsertionLocation(), 
  594                               dkSign.getSignatureElement()));
  595                   }
  596   
  597                   return dkSign.getSignatureValue();
  598                   
  599               } catch (ConversationException e) {
  600                   throw new RampartException(
  601                           "errorInDerivedKeyTokenSignature", e);
  602               } catch (WSSecurityException e) {
  603                   throw new RampartException(
  604                           "errorInDerivedKeyTokenSignature", e);
  605               }
  606           } else {
  607               try {
  608                   WSSecSignature sig = new WSSecSignature();
  609                   sig.setWsConfig(rmd.getConfig());
  610                   
  611                   // If a EncryptedKeyToken is used, set the correct value type to
  612                   // be used in the wsse:Reference in ds:KeyInfo
  613                   if(policyToken instanceof X509Token) {
  614                   	if (rmd.isInitiator()) {
  615   	                    sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS
  616   	                                          + WSConstants.ENC_KEY_VALUE_TYPE);
  617   	                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
  618                   	} else {
  619                   	    //the tok has to be an EncryptedKey token
  620                   	    sig.setEncrKeySha1value(((EncryptedKeyToken)tok).getSHA1());
  621                   		sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
  622                   	}
  623                       
  624                   } else {
  625   				    sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS
  626                                             + WSConstants.SAML_ASSERTION_ID);
  627   	                sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
  628                   }
  629                   
  630                   String sigTokId; 
  631                   
  632                   if ( policyToken instanceof SecureConversationToken) {
  633                       OMElement ref = tok.getAttachedReference();
  634                       if(ref == null) {
  635                           ref = tok.getUnattachedReference();
  636                       }
  637                       
  638                       if (ref != null) {
  639                           sigTokId = SimpleTokenStore.getIdFromSTR(ref);
  640                       } else {
  641                           sigTokId = tok.getId();
  642                       }
  643                   } else {
  644                       sigTokId = tok.getId();
  645                   }
  646                                  
  647                   //Hack to handle reference id issues
  648                   //TODO Need a better fix
  649                   if(sigTokId.startsWith("#")) {
  650                       sigTokId = sigTokId.substring(1);
  651                   }
  652                   
  653                   sig.setCustomTokenId(sigTokId);
  654                   sig.setSecretKey(tok.getSecret());
  655                   sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
  656                   sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
  657                   sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
  658                           .getRampartConfig(), rmd.getCustomClassLoader()),
  659                           rmd.getSecHeader());
  660   
  661                   sig.setParts(sigParts);
  662                   sig.addReferencesToSign(sigParts, rmd.getSecHeader());
  663   
  664                   //Do signature
  665                   sig.computeSignature();
  666   
  667                   if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
  668                           this.getInsertionLocation() == null) {
  669                       this.setInsertionLocation(RampartUtil.insertSiblingBefore(
  670                               rmd,
  671                               this.mainRefListElement,
  672                               sig.getSignatureElement()));                    
  673                   } else {
  674                       this.setInsertionLocation(RampartUtil.insertSiblingAfter(
  675                               rmd,
  676                               this.getInsertionLocation(),
  677                               sig.getSignatureElement()));     
  678                   }
  679   
  680                   return sig.getSignatureValue();
  681                   
  682               } catch (WSSecurityException e) {
  683                   throw new RampartException("errorInSignatureWithACustomToken", e);
  684               }
  685   
  686           }
  687       }
  688       
  689       
  690       /**
  691        * Get hold of the token from the token storage
  692        * @param rmd
  693        * @param tokenId
  694        * @return token from the token storage
  695        * @throws RampartException
  696        */
  697       protected org.apache.rahas.Token getToken(RampartMessageData rmd, 
  698                       String tokenId) throws RampartException {
  699           org.apache.rahas.Token tok = null;
  700           try {
  701               tok = rmd.getTokenStorage().getToken(tokenId);
  702           } catch (TrustException e) {
  703               throw new RampartException("errorInRetrievingTokenId", 
  704                       new String[]{tokenId}, e);
  705           }
  706           
  707           if(tok == null) {
  708               throw new RampartException("errorInRetrievingTokenId", 
  709                       new String[]{tokenId});
  710           }
  711           return tok;
  712       }
  713       
  714   
  715       protected void addSignatureConfirmation(RampartMessageData rmd, Vector sigParts) {
  716           
  717           if(!rmd.getPolicyData().isSignatureConfirmation()) {
  718               
  719               //If we don't require sig confirmation simply go back :-)
  720               return;
  721           }
  722           
  723           Document doc = rmd.getDocument();
  724           
  725           Vector results = (Vector)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
  726           /*
  727            * loop over all results gathered by all handlers in the chain. For each
  728            * handler result get the various actions. After that loop we have all
  729            * signature results in the signatureActions vector
  730            */
  731           Vector signatureActions = new Vector();
  732           for (int i = 0; i < results.size(); i++) {
  733               WSHandlerResult wshResult = (WSHandlerResult) results.get(i);
  734   
  735               WSSecurityUtil.fetchAllActionResults(wshResult.getResults(),
  736                       WSConstants.SIGN, signatureActions);
  737               WSSecurityUtil.fetchAllActionResults(wshResult.getResults(),
  738                       WSConstants.ST_SIGNED, signatureActions);
  739               WSSecurityUtil.fetchAllActionResults(wshResult.getResults(),
  740                       WSConstants.UT_SIGN, signatureActions);
  741           }
  742           
  743           // prepare a SignatureConfirmation token
  744           WSSecSignatureConfirmation wsc = new WSSecSignatureConfirmation();
  745           if (signatureActions.size() > 0) {
  746               if (log.isDebugEnabled()) {
  747                   log.debug("Signature Confirmation: number of Signature results: "
  748                           + signatureActions.size());
  749               }
  750               for (int i = 0; i < signatureActions.size(); i++) {
  751                   WSSecurityEngineResult wsr = (WSSecurityEngineResult) signatureActions
  752                           .get(i);
  753                   byte[] sigVal = (byte[]) wsr.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE);
  754                   wsc.setSignatureValue(sigVal);
  755                   wsc.prepare(doc);
  756                   RampartUtil.appendChildToSecHeader(rmd, wsc.getSignatureConfirmationElement());
  757                   if(sigParts != null) {
  758                       sigParts.add(new WSEncryptionPart(wsc.getId()));
  759                   }
  760               }
  761           } else {
  762               //No Sig value
  763               wsc.prepare(doc);
  764               RampartUtil.appendChildToSecHeader(rmd, wsc.getSignatureConfirmationElement());
  765               if(sigParts != null) {
  766                   sigParts.add(new WSEncryptionPart(wsc.getId()));
  767               }
  768           }
  769       }
  770       private void checkForX509PkiPath(WSSecSignature sig, Token token){
  771           if (token instanceof X509Token) {
  772               X509Token x509Token = (X509Token) token;
  773               if (x509Token.getTokenVersionAndType().equals(Constants.WSS_X509_PKI_PATH_V1_TOKEN10)
  774                       || x509Token.getTokenVersionAndType().equals(Constants.WSS_X509_PKI_PATH_V1_TOKEN11)) {
  775                   sig.setUseSingleCertificate(false);
  776               }
  777           }
  778       }
  779   
  780       
  781   }

Home » rampart-dist-1.4-src » org.apache » rampart » builder » [javadoc | source]