0001: /*
0002: * The contents of this file are subject to the terms
0003: * of the Common Development and Distribution License
0004: * (the License). You may not use this file except in
0005: * compliance with the License.
0006: *
0007: * You can obtain a copy of the license at
0008: * https://glassfish.dev.java.net/public/CDDLv1.0.html.
0009: * See the License for the specific language governing
0010: * permissions and limitations under the License.
0011: *
0012: * When distributing Covered Code, include this CDDL
0013: * Header Notice in each file and include the License file
0014: * at https://glassfish.dev.java.net/public/CDDLv1.0.html.
0015: * If applicable, add the following below the CDDL Header,
0016: * with the fields enclosed by brackets [] replaced by
0017: * you own identifying information:
0018: * "Portions Copyrighted [year] [name of copyright owner]"
0019: *
0020: * Copyright 2006 Sun Microsystems Inc. All Rights Reserved
0021: */
0022:
0023: /*
0024: * WSSPolicyConsumerImpl.java
0025: *
0026: * Created on January 18, 2005, 1:50 PM
0027: */
0028:
0029: package com.sun.xml.wss.impl.dsig;
0030:
0031: import com.sun.xml.wss.impl.FilterProcessingContext;
0032: import com.sun.xml.wss.impl.MessageConstants;
0033: import com.sun.xml.wss.impl.SecurableSoapMessage;
0034: import com.sun.xml.wss.core.SecurityTokenReference;
0035: import com.sun.xml.wss.impl.XMLUtil;
0036: import com.sun.xml.wss.XWSSecurityException;
0037: import com.sun.xml.wss.impl.PolicyTypeUtil;
0038: import com.sun.xml.wss.util.NodeListImpl;
0039: import com.sun.xml.wss.impl.policy.MLSPolicy;
0040: import com.sun.xml.wss.impl.policy.PolicyGenerationException;
0041: import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0042: import com.sun.xml.wss.impl.policy.mls.DerivedTokenKeyBinding;
0043: import com.sun.xml.wss.impl.policy.mls.Parameter;
0044: import com.sun.xml.wss.impl.policy.mls.SymmetricKeyBinding;
0045:
0046: import com.sun.xml.wss.impl.policy.mls.SignaturePolicy;
0047: import com.sun.xml.wss.impl.policy.mls.SignatureTarget;
0048:
0049: import com.sun.xml.wss.impl.policy.mls.WSSPolicy;
0050: import com.sun.xml.wss.logging.LogDomainConstants;
0051: import java.security.AccessController;
0052: import java.security.InvalidAlgorithmParameterException;
0053: import java.security.NoSuchAlgorithmException;
0054: import java.security.Provider;
0055: import java.security.Security;
0056: import javax.xml.crypto.URIDereferencer;
0057: import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;
0058: import java.security.spec.AlgorithmParameterSpec;
0059: import java.util.Collections;
0060: import java.util.HashMap;
0061: import java.util.Iterator;
0062: import java.util.ArrayList;
0063: import java.util.List;
0064: import java.util.ListIterator;
0065: import java.util.Map;
0066: import java.util.logging.Level;
0067: import java.util.logging.Logger;
0068: import javax.xml.crypto.XMLStructure;
0069: import javax.xml.crypto.dom.DOMStructure;
0070: import javax.xml.crypto.dsig.CanonicalizationMethod;
0071: import javax.xml.crypto.dsig.DigestMethod;
0072: import javax.xml.crypto.dsig.Reference;
0073: import javax.xml.crypto.dsig.SignatureMethod;
0074: import javax.xml.crypto.dsig.SignedInfo;
0075: import javax.xml.crypto.dsig.Transform;
0076: import javax.xml.crypto.dsig.XMLSignature;
0077: import javax.xml.crypto.dsig.XMLSignatureFactory;
0078: import javax.xml.crypto.dsig.keyinfo.KeyInfo;
0079: import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
0080: import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
0081: import javax.xml.crypto.dsig.spec.TransformParameterSpec;
0082: import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec;
0083: import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
0084: import javax.xml.namespace.QName;
0085: import javax.xml.soap.SOAPElement;
0086: import javax.xml.soap.SOAPHeader;
0087: import javax.xml.soap.SOAPException;
0088: import javax.xml.transform.dom.DOMSource;
0089: import org.w3c.dom.NodeList;
0090: import org.w3c.dom.NamedNodeMap;
0091:
0092: import javax.xml.xpath.*;
0093: import javax.xml.parsers.DocumentBuilderFactory;
0094: import javax.xml.soap.AttachmentPart;
0095: import javax.xml.soap.SOAPMessage;
0096: import javax.xml.transform.OutputKeys;
0097: import javax.xml.transform.Transformer;
0098: import javax.xml.transform.TransformerFactory;
0099: import javax.xml.transform.TransformerException;
0100: import javax.xml.transform.stream.StreamResult;
0101: import org.w3c.dom.Document;
0102: import org.w3c.dom.Element;
0103: import org.w3c.dom.Node;
0104:
0105: import java.io.ByteArrayOutputStream;
0106: import java.io.OutputStream;
0107:
0108: /**
0109: *
0110: * @author K.venugopal@sun.com
0111: */
0112:
0113: /*
0114: * WSSPolicyConsumerImpl is to be used as a helper class to construct JSR105 objects from signaturePolicy.
0115: * To see if document templates are more efficient
0116: */
0117: public class WSSPolicyConsumerImpl {
0118: private static Logger logger = Logger.getLogger(
0119: LogDomainConstants.IMPL_SIGNATURE_DOMAIN_BUNDLE,
0120: LogDomainConstants.IMPL_SIGNATURE_DOMAIN_BUNDLE);
0121: public static final String defaultJSR105Provider = "org.jcp.xml.dsig.internal.dom.XMLDSigRI";
0122: private String providerName = null;
0123: private String pMT = null;
0124: private static volatile WSSPolicyConsumerImpl wpcInstance = null;
0125: private URIDereferencer externalURIResolver = null;
0126: private Provider provider = null;
0127:
0128: /** Creates a new instance of WSSPolicyConsumerImpl */
0129: private WSSPolicyConsumerImpl() { //for now.
0130: providerName = System.getProperty("jsr105Provider",
0131: defaultJSR105Provider);
0132: pMT = System.getProperty("jsr105MechanismType", "DOM");
0133: /*
0134: try{
0135: provider = (Provider) Class.forName(providerName).newInstance();
0136: }catch(Exception ex){
0137: logger.log(Level.SEVERE,"WSS1324.dsig.factory",ex);
0138: }
0139: */
0140: try {
0141: ClassLoader tccl = Thread.currentThread()
0142: .getContextClassLoader();
0143: ClassLoader loader = null;
0144: if (tccl == null) {
0145: loader = this .getClass().getClassLoader();
0146: } else {
0147: loader = tccl;
0148: }
0149: Class providerClass = Class.forName(providerName, true,
0150: loader);
0151: provider = (Provider) providerClass.newInstance();
0152: } catch (Exception ex) {
0153: logger.log(Level.SEVERE, "WSS1324.dsig.factory", ex);
0154: }
0155:
0156: if (logger.isLoggable(Level.FINEST)) {
0157: logger.log(Level.FINEST, "JSR 105 provider is : "
0158: + providerName);
0159: logger.log(Level.FINEST, "JSR 105 provider mechanism is : "
0160: + pMT);
0161: }
0162: AccessController
0163: .doPrivileged(new java.security.PrivilegedAction() {
0164: public Object run() {
0165: Security.addProvider(provider);
0166: Security.addProvider(new WSSProvider());
0167: return null;
0168: }
0169: });
0170: }
0171:
0172: /**
0173: * @return instance of WSSPolicyConsumerImpl
0174: */
0175: public static WSSPolicyConsumerImpl getInstance() {
0176: if (wpcInstance == null) {
0177: synchronized (WSSPolicyConsumerImpl.class) {
0178: if (wpcInstance == null) {
0179: wpcInstance = new WSSPolicyConsumerImpl();
0180: }
0181: }
0182: }
0183: return wpcInstance;
0184: }
0185:
0186: /**
0187: *
0188: * @return
0189: * @throws PolicyGenerationException
0190: * @throws NoSuchAlgorithmException
0191: * @throws InvalidAlgorithmParameterException
0192: * @throws XWSSecurityException
0193: */
0194: public SignedInfo constructSignedInfo(
0195: FilterProcessingContext fpContext)
0196: throws PolicyGenerationException, NoSuchAlgorithmException,
0197: InvalidAlgorithmParameterException, XWSSecurityException {
0198:
0199: if (PolicyTypeUtil.signaturePolicy(fpContext
0200: .getSecurityPolicy())) {
0201: SignedInfo signInfo = generateSignedInfo(fpContext);
0202: return signInfo;
0203: }
0204: return null;
0205: }
0206:
0207: /**
0208: *
0209: * @param signInfo
0210: * @param keyInfo
0211: * @return XMLSignature
0212: */
0213: public XMLSignature constructSignature(SignedInfo signInfo,
0214: KeyInfo keyInfo) {
0215: return getSignatureFactory().newXMLSignature(signInfo, keyInfo);
0216: }
0217:
0218: /**
0219: *
0220: * @param signInfo
0221: * @param keyInfo
0222: * @param id
0223: * @return XMLSignature
0224: */
0225: public XMLSignature constructSignature(SignedInfo signInfo,
0226: KeyInfo keyInfo, String id) {
0227: return getSignatureFactory().newXMLSignature(signInfo, keyInfo,
0228: null, id, null);
0229: }
0230:
0231: /**
0232: *
0233: * @param signaturePolicy
0234: * @param reference
0235: * @throws PolicyGenerationException
0236: * @throws SOAPException
0237: * @throws XWSSecurityException
0238: * @return KeyInfo
0239: */
0240: public KeyInfo constructKeyInfo(MLSPolicy signaturePolicy,
0241: SecurityTokenReference reference)
0242: throws PolicyGenerationException, SOAPException,
0243: XWSSecurityException {
0244:
0245: if (PolicyTypeUtil.signaturePolicy(signaturePolicy)) {
0246: //SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
0247: //WSSPolicy keyBinding =(WSSPolicy) signaturePolicy.getKeyBinding();
0248: KeyInfoFactory keyFactory = getKeyInfoFactory();
0249:
0250: DOMStructure domKeyInfo = new DOMStructure(reference
0251: .getAsSoapElement());
0252:
0253: KeyInfo keyInfo = keyFactory.newKeyInfo(Collections
0254: .singletonList(domKeyInfo));
0255: return keyInfo;
0256:
0257: }
0258:
0259: return null;
0260:
0261: }
0262:
0263: /**
0264: *
0265: * @param signaturePolicy
0266: * @param KeyName
0267: * @throws PolicyGenerationException
0268: * @throws SOAPException
0269: * @throws XWSSecurityException
0270: * @return KeyInfo
0271: */
0272: public KeyInfo constructKeyInfo(MLSPolicy signaturePolicy,
0273: String KeyName) throws PolicyGenerationException,
0274: SOAPException, XWSSecurityException {
0275:
0276: if (PolicyTypeUtil.signaturePolicy(signaturePolicy)) {
0277: //SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
0278: //WSSPolicy keyBinding =(WSSPolicy) signaturePolicy.getKeyBinding();
0279: KeyInfoFactory keyFactory = getKeyInfoFactory();
0280: javax.xml.crypto.dsig.keyinfo.KeyName keyName = keyFactory
0281: .newKeyName(KeyName);
0282: java.util.List list = new java.util.ArrayList();
0283: list.add(keyName);
0284:
0285: KeyInfo keyInfo = keyFactory.newKeyInfo(list);
0286:
0287: return keyInfo;
0288:
0289: }
0290:
0291: return null;
0292:
0293: }
0294:
0295: /**
0296: *
0297: * @return XMLSignatureFactory
0298: */
0299: public XMLSignatureFactory getSignatureFactory() {
0300: try {
0301:
0302: return XMLSignatureFactory.getInstance("DOM", provider);
0303: //XMLSignatureFactory.getInstance (pMT,providerName);
0304: } catch (Exception ex) {
0305: logger.log(Level.SEVERE, "WSS1324.dsig.factory", ex);
0306: throw new RuntimeException(ex);
0307: }
0308: }
0309:
0310: /**
0311: *
0312: * @return KeyInfoFactory
0313: */
0314: public KeyInfoFactory getKeyInfoFactory() {
0315: try {
0316: return getSignatureFactory().getKeyInfoFactory();
0317: } catch (Exception ex) {
0318: logger
0319: .log(Level.SEVERE, "WSS1323.dsig.keyinfo.factory",
0320: ex);
0321: throw new RuntimeException(ex);
0322: }
0323: }
0324:
0325: /**
0326: * @param signedInfo
0327: * @return SignaturePolicy
0328: */
0329: public SignaturePolicy constructSignaturePolicy(
0330: SignedInfo signedInfo, boolean isBSP) {
0331: SignaturePolicy policy = new SignaturePolicy();
0332: constructSignaturePolicy(signedInfo, isBSP, policy);
0333: return policy;
0334: }
0335:
0336: public void constructSignaturePolicy(SignedInfo signedInfo,
0337: boolean isBSP, SignaturePolicy policy) {
0338: List referencesList = signedInfo.getReferences();
0339: //SignatureMethod sm = signedInfo.getSignatureMethod();
0340: CanonicalizationMethod cm = signedInfo
0341: .getCanonicalizationMethod();
0342:
0343: policy.isBSP(isBSP);
0344: SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding) policy
0345: .getFeatureBinding();
0346: featureBinding.setCanonicalizationAlgorithm(cm.getAlgorithm());
0347: Iterator itr = referencesList.iterator();
0348: while (itr.hasNext()) {
0349: Reference ref = (Reference) itr.next();
0350: SignatureTarget.Transform transform = getSignatureTransform(ref);
0351: SignatureTarget target = new SignatureTarget();
0352: target.isBSP(isBSP);
0353: if (transform != null) {
0354: target.addTransform(transform);
0355: }
0356: target.setDigestAlgorithm(ref.getDigestMethod()
0357: .getAlgorithm());
0358: if (ref.getURI().length() > 0) {
0359: target.setValue(SecurableSoapMessage
0360: .getIdFromFragmentRef(ref.getURI()));
0361: } else {
0362: target.setValue(ref.getURI());
0363: }
0364: target.setType(SignatureTarget.TARGET_TYPE_VALUE_URI);
0365: featureBinding.addTargetBinding(target);
0366: }
0367: }
0368:
0369: public void constructSignaturePolicy(SignedInfo signedInfo,
0370: SignaturePolicy policy, SecurableSoapMessage secMsg)
0371: throws XWSSecurityException {
0372: List referencesList = signedInfo.getReferences();
0373: //SignatureMethod sm = signedInfo.getSignatureMethod();
0374: CanonicalizationMethod cm = signedInfo
0375: .getCanonicalizationMethod();
0376:
0377: //policy.isBSP(isBSP);
0378: SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding) policy
0379: .getFeatureBinding();
0380: featureBinding.setCanonicalizationAlgorithm(cm.getAlgorithm());
0381: Iterator itr = referencesList.iterator();
0382: while (itr.hasNext()) {
0383: Reference ref = (Reference) itr.next();
0384: SignatureTarget.Transform transform = getSignatureTransform(ref);
0385: SignatureTarget target = new SignatureTarget();
0386: //target.isBSP(isBSP);
0387: if (transform != null) {
0388: target.addTransform(transform);
0389: }
0390: target.setDigestAlgorithm(ref.getDigestMethod()
0391: .getAlgorithm());
0392: if (ref.getURI().length() > 0) {
0393: String Id = SecurableSoapMessage
0394: .getIdFromFragmentRef(ref.getURI());
0395: //SOAPElement se = secMsg.getElementByWsuId(Id);
0396: SOAPElement se = null;
0397: try {
0398: se = (SOAPElement) XMLUtil.getElementById(secMsg
0399: .getSOAPPart(), Id);
0400: } catch (javax.xml.transform.TransformerException tex) {
0401: //do nothing
0402: }
0403: if (se != null) {
0404: if (se.getNamespaceURI().equals(
0405: MessageConstants.WSSE_NS)
0406: || se.getNamespaceURI().equals(
0407: MessageConstants.WSSE11_NS)
0408: || se.getNamespaceURI().equals(
0409: MessageConstants.WSSC_NS)
0410: || se.getNamespaceURI().equals(
0411: MessageConstants.WSU_NS)) {
0412: target.setValue("#" + Id);
0413: target
0414: .setType(SignatureTarget.TARGET_TYPE_VALUE_URI);
0415:
0416: } else {
0417: QName qname = new QName(se.getNamespaceURI(),
0418: se.getLocalName());
0419: target.setQName(qname);
0420: target
0421: .setType(SignatureTarget.TARGET_TYPE_VALUE_QNAME);
0422: }
0423: } else {
0424: logger
0425: .log(Level.SEVERE,
0426: "WSS1376.failed.verify.policy.noElementbyID");
0427: throw new XWSSecurityException(
0428: "Policy verification for Signature failed: Element with Id: "
0429: + Id + "not found in message");
0430: }
0431: }
0432:
0433: featureBinding.addTargetBinding(target);
0434: }
0435: }
0436:
0437: /**
0438: *
0439: * @param reference
0440: * @return Transform
0441: */
0442: public SignatureTarget.Transform getSignatureTransform(
0443: Reference reference) {
0444: List transformList = reference.getTransforms();
0445: Iterator transformItr = transformList.iterator();
0446: SignatureTarget.Transform transform = null;
0447: while (transformItr.hasNext()) {
0448: Transform trObj = (Transform) transformItr.next();
0449: String algorithm = trObj.getAlgorithm();
0450: transform = new SignatureTarget.Transform();
0451: transform.setTransform(algorithm);
0452: AlgorithmParameterSpec paramSpec = trObj.getParameterSpec();
0453: // ArrayList paramList = new HashMap();
0454: // addCanonicalizationParams(paramSpec,paramList);
0455: transform.setAlgorithmParameters(paramSpec);
0456: }
0457: return transform;
0458: }
0459:
0460: /**
0461: *
0462: * @param algoSpec
0463: * @param paramList
0464: */
0465: public void addCanonicalizationParams(
0466: AlgorithmParameterSpec algoSpec, HashMap paramList) {
0467: //TODO::FixMe: Fill this appropriately.
0468: if (algoSpec instanceof XPathFilterParameterSpec) {
0469: XPathFilterParameterSpec spec = (XPathFilterParameterSpec) algoSpec;
0470: paramList.put("XPATH", spec.getXPath());
0471: } else if (algoSpec instanceof XPathFilter2ParameterSpec) {
0472: XPathFilter2ParameterSpec spec = (XPathFilter2ParameterSpec) algoSpec;
0473: paramList.put("XPATH2", spec.getXPathList());
0474: }
0475: }
0476:
0477: private SignedInfo generateSignedInfo(
0478: FilterProcessingContext fpContext)
0479: throws PolicyGenerationException, NoSuchAlgorithmException,
0480: InvalidAlgorithmParameterException, XWSSecurityException {
0481: SignaturePolicy signaturePolicy = (SignaturePolicy) fpContext
0482: .getSecurityPolicy();
0483: SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding) signaturePolicy
0484: .getFeatureBinding();
0485: MLSPolicy keyBinding = signaturePolicy.getKeyBinding();
0486: XMLSignatureFactory signatureFactory = getSignatureFactory();
0487: SecurableSoapMessage secureMessage = fpContext
0488: .getSecurableSoapMessage();
0489: String canonicalAlgo = featureBinding
0490: .getCanonicalizationAlgorithm();
0491: boolean disableInclusivePrefix = featureBinding
0492: .getDisableInclusivePrefix();
0493: //String digestAlgo = featureBinding.getDigestAlgorithm();
0494: ArrayList targetList = featureBinding.getTargetBindings();
0495: String keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
0496:
0497: if (PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
0498: AuthenticationTokenPolicy.X509CertificateBinding certificateBinding = (AuthenticationTokenPolicy.X509CertificateBinding) keyBinding;
0499: if (!"".equals(certificateBinding.getKeyAlgorithm())) {
0500: keyAlgo = certificateBinding.getKeyAlgorithm();
0501: }
0502: } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
0503: AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) keyBinding;
0504: if (!"".equals(samlBinding.getKeyAlgorithm())) {
0505: keyAlgo = samlBinding.getKeyAlgorithm();
0506: }
0507: } else if (PolicyTypeUtil.symmetricKeyBinding(keyBinding)) {
0508: SymmetricKeyBinding symmetricKeybinding = (SymmetricKeyBinding) keyBinding;
0509: if (!"".equals(symmetricKeybinding.getKeyAlgorithm())) {
0510: keyAlgo = symmetricKeybinding.getKeyAlgorithm();
0511: } else {
0512: keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
0513: }
0514: } else if (PolicyTypeUtil
0515: .secureConversationTokenKeyBinding(keyBinding)) {
0516: keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
0517: } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
0518: keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
0519: if (PolicyTypeUtil
0520: .issuedTokenKeyBinding(((DerivedTokenKeyBinding) keyBinding)
0521: .getOriginalKeyBinding())) {
0522: if (fpContext.getTrustContext().getProofKey() == null) {
0523: keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
0524: }
0525: }
0526: } else if (PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
0527: //TODO: verify if this is always correct
0528: keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
0529: if (fpContext.getTrustContext().getProofKey() == null) {
0530: keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
0531: }
0532: } else {
0533: logger.log(Level.SEVERE,
0534: "WSS1335.unsupported.keybinding.signaturepolicy");
0535: throw new XWSSecurityException(
0536: "Unsupported KeyBinding for SignaturePolicy");
0537: }
0538:
0539: C14NMethodParameterSpec spec = null;
0540: if (MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS
0541: .equalsIgnoreCase(canonicalAlgo)) {
0542: //List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
0543: //spec = new ExcC14NParameterSpec(inc);
0544: //NOTE: looking at BSP flag on sending side just for
0545: //ExC14N parameterList. Because XWSS11(xmlsec.jar) cannot
0546: //process the PrefixList, thereby breaking BC
0547: if (featureBinding.isBSP() || !disableInclusivePrefix) {
0548: List inc = getInclusiveNamespacePrefixes(secureMessage
0549: .findSecurityHeader(), false);
0550: spec = new ExcC14NParameterSpec(inc);
0551: } else {
0552: spec = null;
0553: }
0554:
0555: }
0556: CanonicalizationMethod canonicalMethod = signatureFactory
0557: .newCanonicalizationMethod(canonicalAlgo, spec);
0558:
0559: SignatureMethod signatureMethod = signatureFactory
0560: .newSignatureMethod(keyAlgo, null);
0561: //Note : Signature algorithm parameters null for now , fix me.
0562: SignedInfo signedInfo = signatureFactory.newSignedInfo(
0563: canonicalMethod, signatureMethod,
0564: generateReferenceList(targetList, signatureFactory,
0565: secureMessage, fpContext, false, featureBinding
0566: .isEndorsingSignature()), null);
0567: //Note : Id is now null , check ?,
0568: return signedInfo;
0569: }
0570:
0571: /*
0572: * Calculate the list of inclusive namespace prefixes.
0573: * Inclusive Prefixes are those that are not not visibly utilized.
0574: */
0575: public static List getInclusiveNamespacePrefixes(Element target,
0576: boolean excludeVisiblePrefixes) {
0577: ArrayList result = new ArrayList();
0578: NamedNodeMap attributes;
0579: Node attribute;
0580: Node parent = target;
0581:
0582: while (!(parent instanceof Document)) {
0583: attributes = parent.getAttributes();
0584: for (int i = 0; i < attributes.getLength(); i++) {
0585: attribute = attributes.item(i);
0586: if (attribute.getNamespaceURI() != null
0587: && attribute.getNamespaceURI().equals(
0588: MessageConstants.NAMESPACES_NS)) {
0589: result.add(attribute.getLocalName());
0590: }
0591: }
0592: parent = parent.getParentNode();
0593: }
0594: /*
0595: if (excludeVisiblePrefixes == true) {
0596: attributes = target.getAttributes();
0597: for (int i = 0; i < attributes.getLength(); i++) {
0598: attribute = attributes.item(i);
0599: if (attribute.getNamespaceURI() != null &&
0600: attribute.getNamespaceURI().equals(MessageConstants.NAMESPACES_NS)) {
0601: result.remove(attribute.getLocalName());
0602: }
0603: if (attribute.getPrefix() != null) {
0604: result.remove(attribute.getLocalName());
0605: }
0606: }
0607:
0608: if (target.getPrefix() == null) {
0609: result.remove(MessageConstants.XMLNS_TAG);
0610: } else {
0611: result.remove(target.getPrefix());
0612: }
0613: }
0614: */
0615: return result;
0616: }
0617:
0618: /*
0619: * Calculate the list of visible namespace prefixes in target.
0620: * to be included in ds:Reference.
0621: */
0622: public static List getReferenceNamespacePrefixes(Node target) {
0623: ArrayList result = new ArrayList();
0624:
0625: traverseSubtree(target, result);
0626:
0627: return result;
0628: }
0629:
0630: private static void traverseSubtree(Node node, List result) {
0631: SOAPElement element = (SOAPElement) node;
0632: Iterator visible = element.getVisibleNamespacePrefixes();
0633:
0634: while (visible.hasNext()) {
0635: String prefix = (String) visible.next();
0636: if (!result.contains(prefix)) {
0637: result.add(prefix);
0638: }
0639: }
0640: Iterator children = element.getChildElements();
0641:
0642: while (children.hasNext()) {
0643: Node child = (Node) children.next();
0644: if (!(child instanceof javax.xml.soap.Text)) {
0645: traverseSubtree(child, result);
0646: }
0647: }
0648: }
0649:
0650: public List generateReferenceList(List targetList,
0651: SecurableSoapMessage secureMessage,
0652: FilterProcessingContext fpContext, boolean verify,
0653: boolean isEndorsing) throws PolicyGenerationException,
0654: NoSuchAlgorithmException,
0655: InvalidAlgorithmParameterException, XWSSecurityException {
0656: XMLSignatureFactory factory = getSignatureFactory();
0657: return generateReferenceList(targetList, factory,
0658: secureMessage, fpContext, verify, isEndorsing);
0659: }
0660:
0661: //Time to refactor this method
0662: //bloated toomuch.
0663: private List generateReferenceList(List targetList,
0664: XMLSignatureFactory signatureFactory,
0665: SecurableSoapMessage secureMessage,
0666: FilterProcessingContext fpContext, boolean verify,
0667: boolean isEndorsing) throws PolicyGenerationException,
0668: NoSuchAlgorithmException,
0669: InvalidAlgorithmParameterException, XWSSecurityException {
0670:
0671: SignaturePolicy signaturePolicy = (SignaturePolicy) fpContext
0672: .getSecurityPolicy();
0673: SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding) signaturePolicy
0674: .getFeatureBinding();
0675: ListIterator iterator = targetList.listIterator();
0676: ArrayList references = new ArrayList();
0677: if (logger.isLoggable(Level.FINEST)) {
0678: logger.log(Level.FINEST, "Number of Targets is"
0679: + targetList.size());
0680: }
0681:
0682: while (iterator.hasNext()) {
0683:
0684: SignatureTarget signatureTarget = (SignatureTarget) iterator
0685: .next();
0686: String digestAlgo = signatureTarget.getDigestAlgorithm();
0687: if (logger.isLoggable(Level.FINEST)) {
0688: logger.log(Level.FINEST, "Digest Algorithm is "
0689: + digestAlgo);
0690: logger.log(Level.FINEST, "Targets is"
0691: + signatureTarget.getValue());
0692: }
0693: DigestMethod digestMethod = null;
0694: try {
0695: digestMethod = signatureFactory.newDigestMethod(
0696: digestAlgo, null);
0697: } catch (Exception ex) {
0698: logger.log(Level.SEVERE, "WSS1301.invalid.digest.algo",
0699: digestAlgo);
0700: throw new XWSSecurityException(ex.getMessage());
0701: }
0702:
0703: boolean exclTransformToBeAdded = false;
0704: ArrayList transforms = signatureTarget.getTransforms();
0705: ListIterator transformIterator = transforms.listIterator();
0706: ArrayList transformList = new ArrayList(2);
0707: boolean disableInclusivePrefix = false;
0708: while (transformIterator.hasNext()) {
0709: SignatureTarget.Transform transformInfo = (SignatureTarget.Transform) transformIterator
0710: .next();
0711: String transformAlgo = transformInfo.getTransform();
0712: Transform transform = null;
0713:
0714: if (logger.isLoggable(Level.FINEST))
0715: logger.log(Level.FINEST, "Transform Algorithm is "
0716: + transformAlgo);
0717: if (transformAlgo == Transform.XPATH
0718: || transformAlgo.equals(Transform.XPATH)) {
0719: TransformParameterSpec spec = (TransformParameterSpec) transformInfo
0720: .getAlgorithmParameters();
0721: //XPathFilterParameterSpec spec = null;
0722:
0723: if (spec == null) {
0724: logger.log(Level.SEVERE,
0725: "WSS1367.illegal.xpath");
0726: throw new XWSSecurityException(
0727: "XPATH parameters cannot be null");
0728:
0729: }
0730: //XPATH2,XSLTC , ..
0731: transform = signatureFactory.newTransform(
0732: transformAlgo, spec);
0733:
0734: } else if (transformAlgo == Transform.XPATH2
0735: || transformAlgo.equals(Transform.XPATH2)) {
0736: TransformParameterSpec transformParams = (TransformParameterSpec) transformInfo
0737: .getAlgorithmParameters();
0738: transform = signatureFactory.newTransform(
0739: transformAlgo, transformParams);
0740: } else if (transformAlgo == MessageConstants.STR_TRANSFORM_URI
0741: || transformAlgo
0742: .equals(MessageConstants.STR_TRANSFORM_URI)) {
0743: Parameter transformParams = (Parameter) transformInfo
0744: .getAlgorithmParameters();
0745: String algo = null;
0746: if (transformParams.getParamName().equals(
0747: "CanonicalizationMethod")) {
0748: algo = transformParams.getParamValue();
0749: }
0750: if (algo == null) {
0751: logger.log(Level.SEVERE,
0752: "WSS1368.illegal.str.canoncalization");
0753: throw new XWSSecurityException(
0754: "STR Transform must have a"
0755: + "canonicalization method specified");
0756: }
0757: if (logger.isLoggable(Level.FINEST)) {
0758: logger.log(Level.FINEST,
0759: "CanonicalizationMethod is " + algo);
0760: }
0761: CanonicalizationMethod cm = null;
0762: C14NMethodParameterSpec spec = null;
0763: try {
0764: Document doc = DocumentBuilderFactory
0765: .newInstance().newDocumentBuilder()
0766: .newDocument();
0767: Element tp = doc.createElementNS(
0768: MessageConstants.WSSE_NS,
0769: "wsse:TransformationParameters");
0770: Element cem = doc.createElementNS(
0771: MessageConstants.DSIG_NS,
0772: "ds:CanonicalizationMethod");
0773: tp.appendChild(cem);
0774: cem.setAttribute("Algorithm", algo);
0775: doc.appendChild(tp);
0776: XMLStructure transformSpec = new DOMStructure(
0777: tp);
0778: transform = signatureFactory.newTransform(
0779: transformAlgo, transformSpec);
0780: } catch (Exception ex) {
0781: logger.log(Level.SEVERE,
0782: "WSS1300.dsig.transform_param.error",
0783: ex);
0784: throw new XWSSecurityException(ex.getMessage());
0785: }
0786: } else if (MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS
0787: .equalsIgnoreCase(transformAlgo)) {
0788: // should be there by default...
0789: // As per R 5412, last child of ds:Transforms must be either excl-c14n, or attachment-content only or attachment-complete transform
0790: exclTransformToBeAdded = true;
0791: disableInclusivePrefix = transformInfo
0792: .getDisableInclusivePrefix();
0793: } else {
0794: // XMLStructure transformSpec = null;
0795: // transform = signatureFactory.newTransform(transformAlgo,transformSpec);
0796: // Workaround for JSR105 bug
0797: transform = signatureFactory.newTransform(
0798: transformAlgo,
0799: (TransformParameterSpec) null);
0800: }
0801: if (!MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS
0802: .equalsIgnoreCase(transformAlgo)) {
0803: // will add c14n transform in the end; later
0804: transformList.add(transform);
0805: }
0806: }
0807: String targetURI = "";
0808: String signatureType = signatureTarget.getType();
0809: SOAPMessage msg = secureMessage.getSOAPMessage();
0810: boolean headersOnly = signatureTarget.isSOAPHeadersOnly();
0811: if (signatureType
0812: .equals(SignatureTarget.TARGET_TYPE_VALUE_QNAME)
0813: || signatureType
0814: .equals(SignatureTarget.TARGET_TYPE_VALUE_XPATH)) {
0815:
0816: String expr = null;
0817: NodeList nodes = null;
0818: if (signatureType == SignatureTarget.TARGET_TYPE_VALUE_QNAME) {
0819: String targetValue = signatureTarget.getValue();
0820: boolean optimized = false;
0821: if (fpContext.getConfigType() == MessageConstants.SIGN_BODY
0822: || fpContext.getConfigType() == MessageConstants.SIGN_ENCRYPT_BODY) {
0823: optimized = true;
0824: }
0825: // if(targetValue.equals(SignatureTarget.BODY) && optimized){
0826: // Reference ref = new JAXWSDigestProcessor(fpContext,signatureTarget , digestMethod, signatureFactory).handleJAXWSSOAPBody();
0827: // references.add(ref);
0828: // continue;
0829: // }
0830:
0831: if (targetValue.equals(SignatureTarget.BODY)) {
0832: try {
0833:
0834: final SOAPElement se = msg.getSOAPBody();
0835:
0836: nodes = new NodeList() {
0837: Node node = se;
0838:
0839: public int getLength() {
0840: if (node == null) {
0841: return 0;
0842: } else {
0843: return 1;
0844: }
0845: }
0846:
0847: public Node item(int num) {
0848: if (num == 0) {
0849: return node;
0850: } else {
0851: return null;
0852: }
0853: }
0854: };
0855: } catch (SOAPException se) {
0856: logger
0857: .log(Level.SEVERE,
0858: "WSS1369.unable.get.signatureTarget.by.URI");
0859: throw new XWSSecurityException(
0860: "SignatureTarget with URI "
0861: + targetValue
0862: + " is not in the message");
0863: //logger.log(
0864: // Level.WARNING, "Signed Part with QName " + targetValue + " is not in the message");
0865: //continue;
0866: }
0867: } else {
0868:
0869: QName name = QName.valueOf(targetValue);
0870: if (!headersOnly) {
0871: if ("".equals(name.getNamespaceURI())) {
0872: nodes = msg.getSOAPPart()
0873: .getElementsByTagName(
0874: name.getLocalPart());
0875: } else {
0876: if (!"".equals(name.getLocalPart()))
0877: nodes = msg
0878: .getSOAPPart()
0879: .getElementsByTagNameNS(
0880: name
0881: .getNamespaceURI(),
0882: name.getLocalPart());
0883: else
0884: nodes = msg
0885: .getSOAPPart()
0886: .getElementsByTagNameNS(
0887: name
0888: .getNamespaceURI(),
0889: "*");
0890: }
0891: } else {
0892: //process headers of soap message
0893: try {
0894: nodes = new NodeListImpl();
0895: NodeList hdrChilds = msg
0896: .getSOAPHeader()
0897: .getChildNodes();
0898: for (int i = 0; i < hdrChilds
0899: .getLength(); i++) {
0900: Node child = hdrChilds.item(i);
0901: if (child.getNodeType() == Node.ELEMENT_NODE) {
0902: if ("".equals(name
0903: .getNamespaceURI())) {
0904: if (name
0905: .getLocalPart()
0906: .equals(
0907: child
0908: .getLocalName()))
0909: ((NodeListImpl) nodes)
0910: .add(child);
0911: } else {
0912: // FIXME: Hack to get addressing members from both namespaces, as microsoft uses both of them in a soap message
0913: if (name
0914: .getNamespaceURI()
0915: .equals(
0916: MessageConstants.ADDRESSING_MEMBER_SUBMISSION_NAMESPACE)
0917: || name
0918: .getNamespaceURI()
0919: .equals(
0920: MessageConstants.ADDRESSING_W3C_NAMESPACE)) {
0921: if ((child
0922: .getNamespaceURI()
0923: .equals(
0924: MessageConstants.ADDRESSING_MEMBER_SUBMISSION_NAMESPACE) || child
0925: .getNamespaceURI()
0926: .equals(
0927: MessageConstants.ADDRESSING_W3C_NAMESPACE))) {
0928: if (!""
0929: .equals(name
0930: .getLocalPart())) {
0931: if (name
0932: .getLocalPart()
0933: .equals(
0934: child
0935: .getLocalName()))
0936: ((NodeListImpl) nodes)
0937: .add(child);
0938: } else {
0939: ((NodeListImpl) nodes)
0940: .add(child);
0941: }
0942: }
0943: } else {
0944: if (!""
0945: .equals(name
0946: .getLocalPart())) {
0947: if (name
0948: .getNamespaceURI()
0949: .equals(
0950: child
0951: .getNamespaceURI())
0952: && name
0953: .getLocalPart()
0954: .equals(
0955: child
0956: .getLocalName()))
0957: ((NodeListImpl) nodes)
0958: .add(child);
0959: } else {
0960: if (name
0961: .getNamespaceURI()
0962: .equals(
0963: child
0964: .getNamespaceURI()))
0965: ((NodeListImpl) nodes)
0966: .add(child);
0967: }
0968: }
0969: }
0970: }
0971: }
0972: } catch (SOAPException se) {
0973: logger
0974: .log(Level.SEVERE,
0975: "WSS1370.failed.process.header");
0976: throw new XWSSecurityException(se);
0977: }
0978: }
0979: }
0980: } else {
0981:
0982: expr = signatureTarget.getValue();
0983:
0984: try {
0985: XPathFactory xpathFactory = XPathFactory
0986: .newInstance();
0987: XPath xpath = xpathFactory.newXPath();
0988: xpath.setNamespaceContext(secureMessage
0989: .getNamespaceContext());
0990: // XPathExpression expr = xpath.compile("//*[@wsu:Id]");
0991: //XPathExpression expr = xpath.compile("//*");
0992: XPathExpression xpathExpr = xpath.compile(expr);
0993: if (logger.isLoggable(Level.FINEST)) {
0994: logger.log(Level.FINEST,
0995: "++++++++++++++++++++++++++++++");
0996: logger.log(Level.FINEST, "Expr is " + expr);
0997: printDocument((Node) secureMessage
0998: .getSOAPPart());
0999: }
1000: nodes = (NodeList) xpathExpr.evaluate(
1001: (Object) secureMessage.getSOAPPart(),
1002: XPathConstants.NODESET);
1003: } catch (XPathExpressionException xpe) {
1004: logger.log(Level.SEVERE,
1005: "WSS1371.failed.resolve.XPath" + expr,
1006: xpe);
1007: throw new XWSSecurityException(xpe);
1008: }
1009: }
1010: int i = 0;
1011: if (nodes == null || nodes.getLength() <= 0) {
1012: if (signatureTarget.getEnforce()) {
1013: logger
1014: .log(Level.SEVERE,
1015: "WSS1369.unable.get.signatureTarget.by.URI");
1016: throw new XWSSecurityException(
1017: "SignatureTarget with URI "
1018: + signatureTarget.getValue()
1019: + " is not in the message");
1020: } else {
1021: continue;
1022: }
1023:
1024: // we dont throw error since WSSecurityPolicy allows this
1025: //logger.log(Level.WARNING, "Signed Part with QName/XPath " + signatureTarget.getValue() +
1026: // " is not in the message");
1027: //continue;
1028: }
1029: if (logger.isLoggable(Level.FINEST)) {
1030: logger.log(Level.FINEST, "Number of nodes "
1031: + nodes.getLength());
1032: logger.log(Level.FINEST,
1033: "+++++++++++++++END+++++++++++++++");
1034: }
1035: HashMap elementCache = null;
1036: if (fpContext != null) {
1037: elementCache = fpContext.getElementCache();
1038: }
1039: while (i < nodes.getLength()) {
1040: if (logger.isLoggable(Level.FINEST))
1041: logger.log(Level.FINEST, "Nodes is "
1042: + nodes.item(i));
1043: Node nodeRef = nodes.item(i++);
1044: if (nodeRef.getNodeType() != Node.ELEMENT_NODE) {
1045: logger.log(Level.SEVERE,
1046: "WSS1371.failed.resolve.XPath");
1047: throw new XWSSecurityException(
1048: "XPath does not correspond to a DOM Element");
1049: }
1050: ArrayList clonedTransformList = (ArrayList) transformList
1051: .clone();
1052: if (exclTransformToBeAdded) {
1053: // exc-14-nl must be one of the last transforms under ReferenceList by default.
1054: String transformAlgo = MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
1055: ExcC14NParameterSpec spec = null;
1056: if ((featureBinding != null && featureBinding
1057: .isBSP())
1058: || !disableInclusivePrefix) {
1059: spec = new ExcC14NParameterSpec(
1060: getReferenceNamespacePrefixes(nodeRef));
1061: }
1062: Transform transform = signatureFactory
1063: .newTransform(transformAlgo, spec);
1064: clonedTransformList.add(transform);
1065: }
1066: boolean w3cElem = false;
1067: // Assume only elements with wsu:Id are signed
1068: String id = ((Element) nodeRef).getAttributeNS(
1069: MessageConstants.WSU_NS, "Id");
1070: if (id == null || id.equals("")) {
1071: if (nodeRef.getNamespaceURI() == MessageConstants.DSIG_NS
1072: || nodeRef.getNamespaceURI() == MessageConstants.XENC_NS) {
1073: w3cElem = true;
1074: id = ((Element) nodeRef).getAttribute("Id");
1075: }
1076:
1077: }
1078:
1079: if (id == null || id.equals("")) {
1080: id = secureMessage.generateId();
1081: if (!verify) {
1082: if (w3cElem) {
1083: XMLUtil
1084: .setIdAttr((Element) nodeRef,
1085: id);
1086: } else {
1087: XMLUtil.setWsuIdAttr((Element) nodeRef,
1088: id);
1089: }
1090: } else {
1091: //add to context. dont modify the message.
1092: elementCache.put(id, nodeRef);
1093: }
1094: }
1095:
1096: if (logger.isLoggable(Level.FINEST))
1097: logger.log(Level.FINEST, "SignedInfo val id "
1098: + id);
1099:
1100: targetURI = "#" + id;
1101:
1102: byte[] digestValue = fpContext.getDigestValue();
1103: Reference reference = null;
1104: if (!verify && digestValue != null) {
1105: reference = signatureFactory.newReference(
1106: targetURI, digestMethod,
1107: clonedTransformList, null, null,
1108: digestValue);
1109: } else {
1110: reference = signatureFactory.newReference(
1111: targetURI, digestMethod,
1112: clonedTransformList, null, null);
1113: }
1114: references.add(reference);
1115: }
1116: continue;
1117: } else if (signatureType == SignatureTarget.TARGET_TYPE_VALUE_URI) {
1118: targetURI = signatureTarget.getValue();
1119:
1120: if (targetURI == null) {
1121: targetURI = "";
1122: }
1123: if (targetURI == MessageConstants.PROCESS_ALL_ATTACHMENTS) {
1124: Iterator itr = secureMessage.getAttachments();
1125: if (!itr.hasNext()) {
1126: logger.log(Level.SEVERE,
1127: "WSS1372.no.attachmentFound");
1128: throw new XWSSecurityException(
1129: "No attachment present in the message");
1130: //logger.log(Level.WARNING, "No Attachment Part present in the message to be secured");
1131: //continue;
1132: }
1133: while (itr.hasNext()) {
1134: String cid = null;
1135: AttachmentPart ap = (AttachmentPart) itr.next();
1136: String _cid = ap.getContentId();
1137: if (_cid.charAt(0) == '<'
1138: && _cid.charAt(_cid.length() - 1) == '>') {
1139: int lindex = _cid.lastIndexOf('>');
1140: int sindex = _cid.indexOf('<');
1141: if (lindex < sindex || lindex == sindex) {
1142: //log error
1143: logger.log(Level.SEVERE,
1144: "WSS1303.cid_error");
1145: }
1146: cid = "cid:"
1147: + _cid
1148: .substring(sindex + 1,
1149: lindex);
1150: } else {
1151: cid = "cid:" + _cid;
1152: }
1153: Reference reference = signatureFactory
1154: .newReference(cid, digestMethod,
1155: transformList, null, null);
1156: references.add(reference);
1157: }
1158: continue;
1159: } else {
1160: if (exclTransformToBeAdded) {
1161: // exc-14-n must be one of the last transforms under ReferenceList by default.
1162: // String transformAlgo = MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
1163: // ExcC14NParameterSpec spec = null;
1164: // Transform transform = signatureFactory.newTransform(transformAlgo,spec);
1165: // transformList.add(transform);
1166: SOAPElement dataElement = null;
1167: if (featureBinding != null
1168: && featureBinding.isBSP()) {
1169:
1170: try {
1171: String _uri = targetURI;
1172: if (targetURI.length() > 0
1173: && targetURI.charAt(0) == '#') {
1174: _uri = targetURI.substring(1);
1175: }
1176: dataElement = (SOAPElement) XMLUtil
1177: .getElementById(secureMessage
1178: .getSOAPPart(), _uri);
1179: } catch (TransformerException te) {
1180: logger
1181: .log(
1182: Level.SEVERE,
1183: "WSS1373.failedto.resolve.elementbyID",
1184: te);
1185: throw new XWSSecurityException(te
1186: .getMessage(), te);
1187: }
1188: }
1189: String transformAlgo = MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
1190: ExcC14NParameterSpec spec = null;
1191: if (dataElement != null
1192: && !disableInclusivePrefix) {
1193: spec = new ExcC14NParameterSpec(
1194: getReferenceNamespacePrefixes(dataElement));
1195: }
1196: Transform transform = signatureFactory
1197: .newTransform(transformAlgo, spec);
1198: transformList.add(transform);
1199: }
1200: if (targetURI
1201: .equals(SignatureTarget.ALL_MESSAGE_HEADERS)) {
1202: SOAPHeader soapHeader = null;
1203: try {
1204: soapHeader = secureMessage.getSOAPHeader();
1205: } catch (SOAPException se) {
1206: se.printStackTrace();
1207: }
1208: NodeList headers = soapHeader.getChildNodes();
1209: Reference reference = null;
1210: for (int i = 0; i < headers.getLength(); i++) {
1211: if (((Node) headers.item(i)).getNodeType() == Node.ELEMENT_NODE) {
1212: Element element = (Element) headers
1213: .item(i);
1214: if (!("Security".equals(element
1215: .getLocalName()) && MessageConstants.WSSE_NS
1216: .equals(element
1217: .getNamespaceURI()))) {
1218: reference = signatureFactory
1219: .newReference(
1220: "#"
1221: + generateReferenceID(
1222: element,
1223: secureMessage),
1224: digestMethod,
1225: transformList,
1226: null, null);
1227: references.add(reference);
1228: }
1229: }
1230: }
1231: continue;
1232: }
1233: }
1234: }
1235:
1236: byte[] digestValue = fpContext.getDigestValue();
1237: Reference reference = null;
1238: if (!verify && digestValue != null) {
1239: reference = signatureFactory.newReference(targetURI,
1240: digestMethod, transformList, null, null,
1241: digestValue);
1242: } else {
1243: reference = signatureFactory.newReference(targetURI,
1244: digestMethod, transformList, null, null);
1245: }
1246:
1247: //Note :: Id is null.
1248: references.add(reference);
1249: }
1250:
1251: if (references.isEmpty()) {
1252: if (logger.isLoggable(Level.WARNING)) {
1253: logger.log(Level.WARNING, "WSS1375.no.signedparts");
1254: }
1255: }
1256:
1257: return references;
1258: }
1259:
1260: /**
1261: *
1262: * @param Element
1263: * @param SecurableSoapMessage
1264: * @return String
1265: */
1266: private String generateReferenceID(Element secElement,
1267: SecurableSoapMessage securableSoapMessage) {
1268: String id = secElement.getAttributeNS(MessageConstants.WSU_NS,
1269: "Id");
1270: //((Element)secElement).getAttribute(MessageConstants.WSU_ID_QNAME);
1271: if (id == null || id.equals("")) {
1272: try {
1273: id = securableSoapMessage.generateId();
1274: } catch (XWSSecurityException xse) {
1275: xse.printStackTrace();
1276: }
1277: XMLUtil.setWsuIdAttr((Element) secElement, id);
1278: }
1279: if (logger.isLoggable(Level.FINE)) {
1280: logger
1281: .log(Level.FINE, "Element wsu:id attribute is: "
1282: + id);
1283: }
1284: return id;
1285: }
1286:
1287: public URIDereferencer getDefaultResolver() {
1288: if (externalURIResolver == null) {
1289: externalURIResolver = getSignatureFactory()
1290: .getURIDereferencer();
1291: }
1292: return externalURIResolver;
1293: }
1294:
1295: /**
1296: *
1297: * @param node
1298: */
1299: public static void printDocument(Node node) {
1300: try {
1301: if (logger.isLoggable(Level.FINEST)) {
1302: logger.log(Level.FINEST, "\n");
1303: }
1304: Transformer transformer = TransformerFactory.newInstance()
1305: .newTransformer();
1306: transformer.setOutputProperty(OutputKeys.INDENT, "yes");
1307: OutputStream baos = new ByteArrayOutputStream();
1308: transformer.transform(new DOMSource(node),
1309: new StreamResult(baos));
1310: byte[] bytes = ((ByteArrayOutputStream) baos).toByteArray();
1311: if (logger.isLoggable(Level.FINEST)) {
1312: logger.log(Level.FINEST, new String(bytes));
1313: logger.log(Level.FINEST, "\n");
1314: }
1315: } catch (Exception ex) {
1316: logger.log(Level.SEVERE, "WSS1374.failedto.print.document",
1317: ex);
1318: throw new RuntimeException(ex);
1319: }
1320: }
1321:
1322: // public class JAXWSDigestProcessor {
1323: //
1324: // FilterProcessingContext fpContext= null;
1325: // SignatureTarget target = null;
1326: // DigestMethod dm = null;
1327: // XMLSignatureFactory signatureFactory = null;
1328: // String targetURI = "";
1329: // SOAPMessage msg = null;
1330: // JAXWSDigestProcessor(FilterProcessingContext fc , SignatureTarget st, DigestMethod dm,XMLSignatureFactory sf){
1331: // this.fpContext = fc;
1332: // this.target = st;
1333: // this.dm = dm;
1334: // this.signatureFactory = sf;
1335: // this.msg = fpContext.getSOAPMessage();
1336: // }
1337: //
1338: // public Reference handleJAXWSSOAPBody()throws XWSSecurityException{
1339: // try{
1340: //
1341: // SOAPBody body = ((com.sun.xml.messaging.saaj.soap.ExpressMessage)msg).getEMBody();
1342: //
1343: // int optCase = fpContext.getConfigType();
1344: // switch(optCase){
1345: // case 1 : {
1346: // signBody(body);
1347: // break;
1348: // }
1349: // case 2 : {
1350: // signEncryptBody(body);
1351: // break;
1352: // }
1353: // default :
1354: // throw new XWSSecurityException("Invalid configuration option");
1355: // }
1356: // ArrayList transforms = target.getTransforms();
1357: // ListIterator transformIterator = transforms.listIterator();
1358: // ArrayList transformList = new ArrayList(1);
1359: // String transformAlgo = MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
1360: // String algo = dm.getAlgorithm();
1361: // MessageDigest digester = null;
1362: // if(algo == DigestMethod.SHA1){
1363: // digester = MessageDigest.getInstance("SHA");
1364: // }else{
1365: // //throw error
1366: // }
1367: //
1368: //
1369: // com.sun.xml.jaxws.JAXWSMessage jxm = ((com.sun.xml.messaging.saaj.soap.ExpressMessage)msg).getJAXWSMessage();
1370: // byte[] canonData = jxm.getCanonicalizedBody();
1371: // int len = jxm.getCBLength();
1372: // if(MessageConstants.SIGN_ENCRYPT_BODY == optCase ){
1373: // byte [] data = null;
1374: // jxm.setCanonicalizedBody(data,0);
1375: //
1376: // }
1377: // digester.update(canonData,0,len);
1378: // byte[] digestValue = digester.digest();
1379: //
1380: // ExcC14NParameterSpec spec = null;
1381: //
1382: // //new ExcC14NParameterSpec(getReferenceNamespacePrefixes(nodeRef));
1383: //
1384: // Transform transform = signatureFactory.newTransform(transformAlgo,spec);
1385: // transformList.add(transform);
1386: // Reference reference = signatureFactory.newReference(targetURI,dm,transformList,null,null,digestValue);
1387: // return reference;
1388: //
1389: //
1390: // }catch(Exception ex){
1391: // throw new RuntimeException(ex);
1392: // }
1393: // }
1394: //
1395: // private void signBody(SOAPBody body)throws IOException,XMLStreamException,XWSSecurityException,SOAPException{
1396: // com.sun.xml.wss.impl.c14n.StAXEXC14nCanonicalizerImpl canonicalizer = new com.sun.xml.wss.impl.c14n.StAXEXC14nCanonicalizerImpl();
1397: // UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
1398: // canonicalizer.setStream(baos);
1399: // com.sun.xml.jaxws.JAXWSMessage jxm = ((com.sun.xml.messaging.saaj.soap.ExpressMessage)msg).getJAXWSMessage();
1400: // cBodyTag(canonicalizer,body);
1401: // if(!jxm.isBodyUsed()){
1402: // jxm.writeJAXWSBody(canonicalizer);
1403: // }else{
1404: // //log error
1405: // }
1406: // canonicalizer.writeEndDocument();
1407: // byte [] data = baos.getBytes();
1408: // jxm.setCanonicalizedBody(data,baos.getLength());
1409: //
1410: // }
1411: //
1412: // private void signEncryptBody(SOAPBody body)throws IOException,XMLStreamException,XWSSecurityException,SOAPException{
1413: // com.sun.xml.wss.impl.c14n.StAXEXC14nCanonicalizerImpl canonicalizer = new com.sun.xml.wss.impl.c14n.StAXEXC14nCanonicalizerImpl();
1414: // UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
1415: // canonicalizer.setStream(baos);
1416: // com.sun.xml.jaxws.JAXWSMessage jxm = ((com.sun.xml.messaging.saaj.soap.ExpressMessage)msg).getJAXWSMessage();
1417: // cBodyTag(canonicalizer,body);
1418: // canonicalizer.writeCharacters("");
1419: // byte [] bodyTag = baos.toByteArray();
1420: // baos.reset();
1421: //
1422: // if(!jxm.isBodyUsed()){
1423: // jxm.writeJAXWSBody(canonicalizer);
1424: // // jxm.setBodyUsed(true);
1425: // }else{
1426: // //log error
1427: // }
1428: // byte [] bodyContent = baos.toByteArray();
1429: // baos.reset();
1430: // //System.out.println("Body Content "+new String(bodyContent));
1431: // canonicalizer.writeEndDocument();
1432: // byte [] endTag = baos.getBytes();
1433: // byte [] canonicalizedData = new byte[bodyTag.length+bodyContent.length+baos.getLength()];
1434: // System.arraycopy(bodyTag,0,canonicalizedData,0,bodyTag.length);
1435: // System.arraycopy(bodyContent,0,canonicalizedData,bodyTag.length,bodyContent.length);
1436: // System.arraycopy(endTag,0,canonicalizedData,bodyTag.length+bodyContent.length,baos.getLength());
1437: // jxm.setCanonicalizedBody(canonicalizedData,canonicalizedData.length);
1438: // fpContext.setCanonicalizedData(bodyContent);
1439: // // System.out.println("Canonicalized Data is "+new String(bodyContent ));
1440: // }
1441: //
1442: // private void cBodyTag(XMLStreamWriter canonicalizer,SOAPBody body)throws IOException,XMLStreamException,XWSSecurityException,SOAPException{
1443: // String id = body.getAttributeNS(MessageConstants.WSU_NS, "Id");
1444: //
1445: // if(id == null || id.length() == 0){
1446: // if(body.getNamespaceURI() == MessageConstants.DSIG_NS ||
1447: // body.getNamespaceURI() == MessageConstants.XENC_NS){
1448: //
1449: // id = (body).getAttribute("Id");
1450: // }
1451: // }
1452: //
1453: // if (id == null || id.equals("")) {
1454: // id = fpContext.getSecurableSoapMessage().generateId();
1455: // XMLUtil.setWsuIdAttr(body, id);
1456: // }
1457: // targetURI = "#"+id;
1458: // NamedNodeMap nodes = body.getAttributes();
1459: // Vector attrs = new Vector();
1460: // Vector attrsNS = new Vector();
1461: //
1462: // for(int i=0;i< nodes.getLength();i++){
1463: // Attr attr = (Attr)nodes.item(i);
1464: // //System.out.println("URI"+attr.getNamespaceURI());
1465: // //System.out.println("value"+attr.getNodeValue());
1466: // if(attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")){
1467: // attrsNS.add(attr);
1468: // } else{
1469: // attrs.add(attr);
1470: // }
1471: // }
1472: //
1473: // SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
1474: // NamedNodeMap parentAttrs = env.getAttributes();
1475: //
1476: //
1477: // for(int i=0;i< parentAttrs.getLength();i++){
1478: // Attr attr = (Attr)parentAttrs.item(i);
1479: // //System.out.println("URI"+attr.getNamespaceURI());
1480: // //System.out.println("value"+attr.getNodeValue());
1481: // if(attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")){
1482: // canonicalizer.writeNamespace(attr.getLocalName(),attr.getValue());
1483: // }
1484: // }
1485: //
1486: // canonicalizer.writeStartDocument();
1487: // canonicalizer.writeStartElement(body.getPrefix(),body.getLocalName(),body.getNamespaceURI());
1488: //
1489: //
1490: // Iterator nsItr = attrsNS.iterator();
1491: // while(nsItr.hasNext()){
1492: // Attr attr = (Attr)nsItr.next();
1493: // canonicalizer.writeNamespace(attr.getLocalName(),attr.getValue());
1494: // }
1495: // Iterator attrItr = attrs.iterator();
1496: // while(attrItr.hasNext()){
1497: // Attr attr = (Attr)attrItr.next();
1498: // canonicalizer.writeAttribute(attr.getPrefix(),attr.getNamespaceURI(),attr.getLocalName(),attr.getValue());
1499: // }
1500: // }
1501: // }
1502: //
1503: /**
1504: * Provider to register STRTransform,Attachment-Complete and Attachment-ContentOnly Transforms
1505: * into XMLDSIG implementation.
1506: *
1507: */
1508: public static final class WSSProvider extends Provider {
1509: private static final String INFO = "WSS_TRANSFORM "
1510: + "(DOM WSS_TRANSFORM_PROVIDER)";
1511:
1512: public WSSProvider() {
1513: /* We are the XMLDSig provider */
1514: super ("WSS_TRANSFORM", 1.0, INFO);
1515: final Map map = new HashMap();
1516: map
1517: .put(
1518: "TransformService."
1519: + MessageConstants.ATTACHMENT_COMPLETE_TRANSFORM_URI,
1520: "com.sun.xml.wss.impl.transform.ACTransform");
1521: map
1522: .put(
1523: "TransformService."
1524: + MessageConstants.ATTACHMENT_COMPLETE_TRANSFORM_URI
1525: + " MechanismType", "DOM");
1526:
1527: map.put("TransformService."
1528: + MessageConstants.STR_TRANSFORM_URI,
1529: "com.sun.xml.wss.impl.transform.DOMSTRTransform");
1530: map.put("TransformService."
1531: + MessageConstants.STR_TRANSFORM_URI
1532: + " MechanismType", "DOM");
1533: map
1534: .put(
1535: "TransformService."
1536: + MessageConstants.ATTACHMENT_CONTENT_ONLY_TRANSFORM_URI,
1537: "com.sun.xml.wss.impl.transform.ACOTransform");
1538: map
1539: .put(
1540: "TransformService."
1541: + MessageConstants.ATTACHMENT_CONTENT_ONLY_TRANSFORM_URI
1542: + " MechanismType", "DOM");
1543:
1544: putAll(map);
1545: }
1546: }
1547: }
|