Source Code Cross Referenced for KeySelectorImpl.java in  » 6.0-JDK-Modules-com.sun » xws-security » com » sun » xml » wss » impl » dsig » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules com.sun » xws security » com.sun.xml.wss.impl.dsig 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:         * KeySelectorImpl.java
0025:         *
0026:         * Created on February 25, 2005, 4:36 PM
0027:         */package com.sun.xml.wss.impl.dsig;
0028:
0029:        import com.sun.xml.wss.impl.FilterProcessingContext;
0030:        import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0031:        import com.sun.xml.wss.impl.policy.mls.SignaturePolicy;
0032:        import com.sun.xml.wss.logging.LogDomainConstants;
0033:        import com.sun.xml.wss.impl.MessageConstants;
0034:        import com.sun.xml.wss.impl.SecurableSoapMessage;
0035:        import com.sun.xml.wss.impl.XMLUtil;
0036:        import com.sun.xml.wss.XWSSecurityException;
0037:        import com.sun.xml.wss.saml.AssertionUtil;
0038:        import com.sun.xml.wss.saml.SAMLException;
0039:        import com.sun.xml.wss.core.ReferenceElement;
0040:        import com.sun.xml.wss.core.SecurityToken;
0041:        import com.sun.xml.wss.core.SecurityTokenReference;
0042:        import com.sun.xml.wss.core.X509SecurityToken;
0043:        import com.sun.xml.wss.core.reference.DirectReference;
0044:        import com.sun.xml.wss.core.reference.KeyIdentifier;
0045:        import com.sun.xml.wss.core.EncryptedKeyToken;
0046:        import com.sun.xml.wss.core.KeyInfoHeaderBlock;
0047:        import com.sun.xml.wss.core.SecurityContextTokenImpl;
0048:        import com.sun.xml.ws.security.SecurityContextToken;
0049:        import com.sun.xml.wss.core.DerivedKeyTokenHeaderBlock;
0050:        import com.sun.xml.ws.security.impl.DerivedKeyTokenImpl;
0051:        import com.sun.xml.ws.security.DerivedKeyToken;
0052:
0053:        import com.sun.xml.ws.security.IssuedTokenContext;
0054:
0055:        import com.sun.xml.wss.impl.misc.DefaultSecurityEnvironmentImpl;
0056:        import com.sun.xml.wss.impl.misc.Base64;
0057:
0058:        import com.sun.xml.wss.saml.Assertion;
0059:        import com.sun.xml.wss.saml.util.SAMLUtil;
0060:
0061:        import java.math.BigInteger;
0062:
0063:        import java.security.Key;
0064:        import java.security.KeyException;
0065:        import java.security.PublicKey;
0066:        import java.security.MessageDigest;
0067:        import java.security.cert.X509Certificate;
0068:
0069:        import java.util.HashMap;
0070:        import java.util.Iterator;
0071:        import java.util.List;
0072:        import java.util.logging.Level;
0073:        import java.util.logging.Logger;
0074:        import java.util.Enumeration;
0075:
0076:        import javax.xml.crypto.AlgorithmMethod;
0077:        import javax.xml.crypto.KeySelector;
0078:        import javax.xml.crypto.KeySelectorException;
0079:        import javax.xml.crypto.KeySelectorResult;
0080:        import javax.xml.crypto.MarshalException;
0081:        import javax.xml.crypto.NodeSetData;
0082:        import javax.xml.crypto.URIDereferencer;
0083:        import javax.xml.crypto.URIReference;
0084:        import javax.xml.crypto.URIReferenceException;
0085:        import javax.xml.crypto.XMLCryptoContext;
0086:        import javax.xml.crypto.XMLStructure;
0087:        import javax.xml.crypto.KeySelector.Purpose;
0088:        import javax.xml.crypto.dom.DOMStructure;
0089:        import javax.xml.crypto.dsig.SignatureMethod;
0090:        import javax.xml.crypto.dsig.keyinfo.KeyInfo;
0091:        import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
0092:        import javax.xml.crypto.dsig.keyinfo.KeyName;
0093:        import javax.xml.crypto.dsig.keyinfo.KeyValue;
0094:        import javax.xml.crypto.dsig.keyinfo.X509Data;
0095:        import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
0096:        import com.sun.xml.wss.impl.policy.MLSPolicy;
0097:        import com.sun.xml.wss.impl.policy.mls.DerivedTokenKeyBinding;
0098:        import com.sun.xml.wss.impl.policy.mls.SymmetricKeyBinding;
0099:        import com.sun.xml.wss.impl.policy.mls.SecureConversationTokenKeyBinding;
0100:        import com.sun.xml.wss.impl.policy.mls.IssuedTokenKeyBinding;
0101:
0102:        import javax.xml.soap.SOAPElement;
0103:        import javax.xml.namespace.QName;
0104:
0105:        import com.sun.xml.wss.impl.policy.SecurityPolicy;
0106:        import com.sun.xml.wss.impl.policy.mls.WSSPolicy;
0107:        import com.sun.xml.wss.impl.policy.mls.MessagePolicy;
0108:        import com.sun.xml.wss.impl.PolicyTypeUtil;
0109:
0110:        import org.w3c.dom.Element;
0111:        import org.w3c.dom.Node;
0112:        import org.w3c.dom.NodeList;
0113:
0114:        import javax.crypto.spec.SecretKeySpec;
0115:
0116:        import com.sun.xml.wss.impl.misc.SecurityUtil;
0117:        import com.sun.xml.wss.impl.AlgorithmSuite;
0118:
0119:        import com.sun.xml.ws.security.trust.elements.BinarySecret;
0120:        import com.sun.xml.ws.security.trust.WSTrustElementFactory;
0121:        import com.sun.xml.ws.api.security.trust.WSTrustException;
0122:
0123:        import com.sun.xml.wss.impl.misc.KeyResolver;
0124:        import javax.security.auth.Subject;
0125:
0126:        /**
0127:         * Implementation of JSR 105 KeySelector interface.
0128:         * Supports resolving Key information from
0129:         * SecurityTokenReference elements, KeyName,
0130:         * X509Data and KeyValue.
0131:         * @author K.Venugopal@sun.com,XWS-Security team
0132:         */
0133:        public class KeySelectorImpl extends KeySelector {
0134:            private static KeySelectorImpl keyResolver = null;
0135:            private static Logger logger = Logger.getLogger(
0136:                    LogDomainConstants.IMPL_SIGNATURE_DOMAIN,
0137:                    LogDomainConstants.IMPL_SIGNATURE_DOMAIN_BUNDLE);
0138:
0139:            /** Creates a new instance of KeySelectorImpl */
0140:            static {
0141:                keyResolver = new KeySelectorImpl();
0142:            }
0143:
0144:            private KeySelectorImpl() {
0145:
0146:            }
0147:
0148:            /**
0149:             *
0150:             * @return
0151:             */
0152:            public static KeySelector getInstance() {
0153:                return keyResolver;
0154:            }
0155:
0156:            /**
0157:             *
0158:             * @param keyInfo
0159:             * @param purpose
0160:             * @param method
0161:             * @param context
0162:             * @throws KeySelectorException
0163:             * @return
0164:             */
0165:            public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
0166:                    AlgorithmMethod method, XMLCryptoContext context)
0167:                    throws KeySelectorException {
0168:                if (keyInfo == null) {
0169:                    if (logger.getLevel() == Level.SEVERE) {
0170:                        logger.log(Level.SEVERE, "WSS1317.keyinfo.null");
0171:                    }
0172:                    throw new KeySelectorException("Null KeyInfo object!");
0173:                }
0174:
0175:                if (logger.isLoggable(Level.FINEST)) {
0176:                    logger.log(Level.FINEST,
0177:                            "KeySelectorResult::select Purpose =  " + purpose);
0178:                    logger.log(Level.FINEST,
0179:                            "KeySelectorResult::select Algorithm is "
0180:                                    + method.getAlgorithm());
0181:                    logger.log(Level.FINEST,
0182:                            "KeySelectorResult::select ParameterSpec is "
0183:                                    + method.getParameterSpec());
0184:                }
0185:                try {
0186:                    SignatureMethod sm = (SignatureMethod) method;
0187:                    List list = keyInfo.getContent();
0188:                    FilterProcessingContext wssContext = (FilterProcessingContext) context
0189:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0190:
0191:                    SecurityPolicy securityPolicy = wssContext
0192:                            .getSecurityPolicy();
0193:                    boolean isBSP = false;
0194:                    if (securityPolicy != null) {
0195:                        if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
0196:                            isBSP = ((MessagePolicy) securityPolicy).isBSP();
0197:                        } else {
0198:                            isBSP = ((WSSPolicy) securityPolicy).isBSP();
0199:                        }
0200:                    }
0201:
0202:                    if (isBSP && list.size() > 1) {
0203:                        logger.log(Level.SEVERE,
0204:                                "WSS1350.illegal.BSP.Violation.KeyInfo");
0205:                        throw SecurableSoapMessage
0206:                                .newSOAPFaultException(
0207:                                        MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
0208:                                        "BSP Violation of R5402: KeyInfo MUST have exactly one child",
0209:                                        null);
0210:                    }
0211:
0212:                    boolean isStr = false;
0213:
0214:                    for (int i = 0; i < list.size(); i++) {
0215:                        XMLStructure xmlStructure = (XMLStructure) list.get(i);
0216:                        if (xmlStructure instanceof  KeyValue) {
0217:                            PublicKey pk = null;
0218:                            try {
0219:                                pk = ((KeyValue) xmlStructure).getPublicKey();
0220:                            } catch (KeyException ke) {
0221:                                logger
0222:                                        .log(
0223:                                                Level.SEVERE,
0224:                                                "WSS1351.exception.keyselector.publickey",
0225:                                                ke);
0226:                                throw new KeySelectorException(ke);
0227:                            }
0228:                            // make sure algorithm is compatible with method
0229:                            if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
0230:                                return new SimpleKeySelectorResult(pk);
0231:                            }
0232:                        } else if (xmlStructure instanceof  DOMStructure) {
0233:                            SOAPElement reference = (SOAPElement) ((DOMStructure) xmlStructure)
0234:                                    .getNode();
0235:                            if (isSecurityTokenReference(reference)) {
0236:                                isStr = true;
0237:                                final Key key = resolve(reference, context,
0238:                                        purpose);
0239:                                return new KeySelectorResult() {
0240:                                    public Key getKey() {
0241:                                        return key;
0242:                                    }
0243:                                };
0244:                            }
0245:                        } else if (xmlStructure instanceof  KeyName) {
0246:                            KeyName keyName = (KeyName) xmlStructure;
0247:                            Key returnKey = wssContext.getSecurityEnvironment()
0248:                                    .getSecretKey(
0249:                                            wssContext
0250:                                                    .getExtraneousProperties(),
0251:                                            keyName.getName(), false);
0252:                            if (returnKey == null) {
0253:                                X509Certificate cert = wssContext
0254:                                        .getSecurityEnvironment()
0255:                                        .getCertificate(
0256:                                                wssContext
0257:                                                        .getExtraneousProperties(),
0258:                                                keyName.getName(), false);
0259:                                if (cert != null
0260:                                        && algEquals(sm.getAlgorithm(), cert
0261:                                                .getPublicKey().getAlgorithm())) {
0262:                                    //update other party subject here
0263:                                    wssContext
0264:                                            .getSecurityEnvironment()
0265:                                            .updateOtherPartySubject(
0266:                                                    DefaultSecurityEnvironmentImpl
0267:                                                            .getSubject(wssContext),
0268:                                                    cert);
0269:                                    return new SimpleKeySelectorResult(cert
0270:                                            .getPublicKey());
0271:                                }
0272:                            } else {
0273:                                return new SimpleKeySelectorResult(returnKey);
0274:                            }
0275:                        } else if (xmlStructure instanceof  X509Data) {
0276:                            Key key = resolveX509Data(wssContext,
0277:                                    (X509Data) xmlStructure, purpose);
0278:                            return new SimpleKeySelectorResult(key);
0279:                        }
0280:                    }
0281:
0282:                    if (isBSP && !isStr) {
0283:                        logger
0284:                                .log(Level.SEVERE,
0285:                                        "BSP Violation of R5409: Child element of KeyInfo MUST be a STR element");
0286:                        throw SecurableSoapMessage
0287:                                .newSOAPFaultException(
0288:                                        MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
0289:                                        "BSP Violation of R5409: Child element of KeyInfo MUST be a STR element",
0290:                                        null);
0291:                    }
0292:
0293:                } catch (KeySelectorException kse) {
0294:                    logger.log(Level.SEVERE, "WSS1352.exception.keyselector",
0295:                            kse);
0296:                    throw kse;
0297:                } catch (Exception ex) {
0298:                    logger.log(Level.SEVERE,
0299:                            "WSS1353.unable.resolve.keyInformation", ex
0300:                                    .getMessage());
0301:                    throw new KeySelectorException(ex);
0302:                }
0303:                logger.log(Level.SEVERE, "WSS1354.null.keyValue");
0304:                throw new KeySelectorException("No KeyValue element found!");
0305:            }
0306:
0307:            //@@@FIXME: this should also work for key types other than DSA/RSA
0308:            /**
0309:             *
0310:             * @param algURI
0311:             * @param algName
0312:             * @return
0313:             */
0314:            static boolean algEquals(String algURI, String algName) {
0315:                if (algName.equalsIgnoreCase("DSA")
0316:                        && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
0317:                    return true;
0318:                } else if (algName.equalsIgnoreCase("RSA")
0319:                        && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
0320:                    return true;
0321:                } else {
0322:                    return false;
0323:                }
0324:            }
0325:
0326:            private static class SimpleKeySelectorResult implements 
0327:                    KeySelectorResult {
0328:                private Key pk;
0329:
0330:                SimpleKeySelectorResult(Key pk) {
0331:                    this .pk = pk;
0332:                }
0333:
0334:                public Key getKey() {
0335:                    return pk;
0336:                }
0337:            }
0338:
0339:            private static Key resolve(SOAPElement securityTokenReference,
0340:                    XMLCryptoContext context, Purpose purpose)
0341:                    throws KeySelectorException {
0342:                try {
0343:                    FilterProcessingContext wssContext = (FilterProcessingContext) context
0344:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0345:                    SecurableSoapMessage secureMsg = wssContext
0346:                            .getSecurableSoapMessage();
0347:                    AlgorithmSuite algSuite = wssContext.getAlgorithmSuite();
0348:                    String encAlgo = null;
0349:                    boolean isPolicyRecipient = (wssContext.getMode() == FilterProcessingContext.WSDL_POLICY);
0350:                    if (algSuite != null) {
0351:                        encAlgo = algSuite.getEncryptionAlgorithm();
0352:                    }
0353:
0354:                    SecurityPolicy securityPolicy = wssContext
0355:                            .getSecurityPolicy();
0356:                    boolean isBSP = false;
0357:                    if (securityPolicy != null) {
0358:                        if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
0359:                            isBSP = ((MessagePolicy) securityPolicy).isBSP();
0360:                        } else {
0361:                            isBSP = ((WSSPolicy) securityPolicy).isBSP();
0362:                        }
0363:                    }
0364:
0365:                    SecurityTokenReference str = new SecurityTokenReference(
0366:                            securityTokenReference, isBSP);
0367:                    ReferenceElement refElement = str.getReference();
0368:                    HashMap tokenCache = wssContext.getTokenCache();
0369:                    HashMap insertedX509Cache = wssContext
0370:                            .getInsertedX509Cache();
0371:                    SignaturePolicy policy = (SignaturePolicy) wssContext
0372:                            .getInferredPolicy();
0373:                    SignaturePolicy inferredSignaturePolicy = null;
0374:                    if (isPolicyRecipient) {
0375:                        int i = wssContext.getInferredSecurityPolicy().size() - 1;
0376:                        //When we call SigProc.verifySignature for a SAMLAssertion from KeyResolver
0377:                        if (PolicyTypeUtil.signaturePolicy(wssContext
0378:                                .getInferredSecurityPolicy().get(i))) {
0379:                            inferredSignaturePolicy = (SignaturePolicy) wssContext
0380:                                    .getInferredSecurityPolicy().get(i);
0381:                        }
0382:                    }
0383:                    // will be only during verify.
0384:                    AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
0385:
0386:                    //TODO: what is this case here
0387:                    if (policy != null) {
0388:                        keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy
0389:                                .newX509CertificateKeyBinding();
0390:                    }
0391:
0392:                    Key returnKey = null;
0393:                    boolean isSymmetric = false;
0394:                    if (refElement instanceof  KeyIdentifier) {
0395:                        KeyIdentifier keyId = (KeyIdentifier) refElement;
0396:                        if (keyBinding != null) {
0397:                            keyBinding
0398:                                    .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0399:                            keyBinding.setValueType(keyId.getValueType());
0400:                        }
0401:
0402:                        if (MessageConstants.X509SubjectKeyIdentifier_NS
0403:                                .equals(keyId.getValueType())
0404:                                || MessageConstants.X509v3SubjectKeyIdentifier_NS
0405:                                        .equals(keyId.getValueType())) {
0406:                            if (isPolicyRecipient
0407:                                    && inferredSignaturePolicy != null) {
0408:                                MLSPolicy inferredKB = inferredSignaturePolicy
0409:                                        .getKeyBinding();
0410:                                AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0411:                                x509Binding
0412:                                        .setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
0413:                                x509Binding
0414:                                        .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0415:
0416:                                if (inferredKB == null) {
0417:                                    inferredSignaturePolicy
0418:                                            .setKeyBinding(x509Binding);
0419:                                } else if (PolicyTypeUtil
0420:                                        .symmetricKeyBinding(inferredKB)) {
0421:                                    ((SymmetricKeyBinding) inferredKB)
0422:                                            .setKeyBinding(x509Binding);
0423:                                    isSymmetric = true;
0424:                                } else if (PolicyTypeUtil
0425:                                        .derivedTokenKeyBinding(inferredKB)) {
0426:                                    DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0427:                                    if (dktBind.getOriginalKeyBinding() == null)
0428:                                        ((DerivedTokenKeyBinding) inferredKB)
0429:                                                .setOriginalKeyBinding(x509Binding);
0430:                                    else if (PolicyTypeUtil
0431:                                            .symmetricKeyBinding(dktBind
0432:                                                    .getOriginalKeyBinding())) {
0433:                                        dktBind.getOriginalKeyBinding()
0434:                                                .setKeyBinding(x509Binding);
0435:                                        isSymmetric = true;
0436:                                    }
0437:                                }
0438:
0439:                            }
0440:                            if (purpose == Purpose.VERIFY) {
0441:                                byte[] keyIdBytes = XMLUtil
0442:                                        .getDecodedBase64EncodedData(keyId
0443:                                                .getReferenceValue());
0444:                                wssContext.setExtraneousProperty(
0445:                                        MessageConstants.REQUESTER_KEYID,
0446:                                        new String(keyIdBytes));
0447:                                // add missing update to other party certificate
0448:                                X509Certificate cert = wssContext
0449:                                        .getSecurityEnvironment()
0450:                                        .getCertificate(
0451:                                                wssContext
0452:                                                        .getExtraneousProperties(),
0453:                                                keyIdBytes);
0454:                                if (!isSymmetric) {
0455:                                    wssContext
0456:                                            .getSecurityEnvironment()
0457:                                            .updateOtherPartySubject(
0458:                                                    DefaultSecurityEnvironmentImpl
0459:                                                            .getSubject(wssContext),
0460:                                                    cert);
0461:                                }
0462:                                returnKey = cert.getPublicKey();
0463:                            } else if (purpose == Purpose.SIGN) {
0464:                                returnKey = wssContext
0465:                                        .getSecurityEnvironment()
0466:                                        .getPrivateKey(
0467:                                                wssContext
0468:                                                        .getExtraneousProperties(),
0469:                                                XMLUtil
0470:                                                        .getDecodedBase64EncodedData(keyId
0471:                                                                .getReferenceValue()));
0472:                            }
0473:
0474:                        } else if (MessageConstants.ThumbPrintIdentifier_NS
0475:                                .equals(keyId.getValueType())) {
0476:                            if (isPolicyRecipient
0477:                                    && inferredSignaturePolicy != null) {
0478:                                MLSPolicy inferredKB = inferredSignaturePolicy
0479:                                        .getKeyBinding();
0480:                                AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0481:                                x509Binding
0482:                                        .setValueType(MessageConstants.ThumbPrintIdentifier_NS);
0483:                                x509Binding
0484:                                        .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0485:                                if (inferredKB == null) {
0486:                                    inferredSignaturePolicy
0487:                                            .setKeyBinding(x509Binding);
0488:                                } else if (PolicyTypeUtil
0489:                                        .symmetricKeyBinding(inferredKB)) {
0490:                                    ((SymmetricKeyBinding) inferredKB)
0491:                                            .setKeyBinding(x509Binding);
0492:                                    isSymmetric = true;
0493:                                } else if (PolicyTypeUtil
0494:                                        .derivedTokenKeyBinding(inferredKB)) {
0495:                                    DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0496:                                    if (dktBind.getOriginalKeyBinding() == null)
0497:                                        ((DerivedTokenKeyBinding) inferredKB)
0498:                                                .setOriginalKeyBinding(x509Binding);
0499:                                    else if (PolicyTypeUtil
0500:                                            .symmetricKeyBinding(dktBind
0501:                                                    .getOriginalKeyBinding())) {
0502:                                        dktBind.getOriginalKeyBinding()
0503:                                                .setKeyBinding(x509Binding);
0504:                                        isSymmetric = true;
0505:                                    }
0506:                                }
0507:
0508:                            }
0509:                            if (purpose == Purpose.VERIFY) {
0510:                                byte[] keyIdBytes = XMLUtil
0511:                                        .getDecodedBase64EncodedData(keyId
0512:                                                .getReferenceValue());
0513:                                wssContext.setExtraneousProperty(
0514:                                        MessageConstants.REQUESTER_KEYID,
0515:                                        new String(keyIdBytes));
0516:                                //update other party subject
0517:                                X509Certificate cert = wssContext
0518:                                        .getSecurityEnvironment()
0519:                                        .getCertificate(
0520:                                                wssContext
0521:                                                        .getExtraneousProperties(),
0522:                                                keyIdBytes,
0523:                                                MessageConstants.THUMB_PRINT_TYPE);
0524:                                if (!isSymmetric) {
0525:                                    wssContext
0526:                                            .getSecurityEnvironment()
0527:                                            .updateOtherPartySubject(
0528:                                                    DefaultSecurityEnvironmentImpl
0529:                                                            .getSubject(wssContext),
0530:                                                    cert);
0531:                                }
0532:                                returnKey = cert.getPublicKey();
0533:                            } else if (purpose == Purpose.SIGN) {
0534:                                returnKey = wssContext
0535:                                        .getSecurityEnvironment()
0536:                                        .getPrivateKey(
0537:                                                wssContext
0538:                                                        .getExtraneousProperties(),
0539:                                                XMLUtil
0540:                                                        .getDecodedBase64EncodedData(keyId
0541:                                                                .getReferenceValue()),
0542:                                                MessageConstants.THUMB_PRINT_TYPE);
0543:                            }
0544:
0545:                        } else if (MessageConstants.EncryptedKeyIdentifier_NS
0546:                                .equals(keyId.getValueType())) {
0547:                            if (isPolicyRecipient
0548:                                    && inferredSignaturePolicy != null) {
0549:                                MLSPolicy inferredKB = inferredSignaturePolicy
0550:                                        .getKeyBinding();
0551:                                SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
0552:                                AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0553:                                x509Binding
0554:                                        .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0555:                                skBinding.setKeyBinding(x509Binding);
0556:                                //TODO: ReferenceType and ValueType not set on X509Binding
0557:                                if (inferredKB == null) {
0558:                                    inferredSignaturePolicy
0559:                                            .setKeyBinding(skBinding);
0560:                                } else if (PolicyTypeUtil
0561:                                        .derivedTokenKeyBinding(inferredKB)) {
0562:                                    if (((DerivedTokenKeyBinding) inferredKB)
0563:                                            .getOriginalKeyBinding() == null)
0564:                                        ((DerivedTokenKeyBinding) inferredKB)
0565:                                                .setOriginalKeyBinding(skBinding);
0566:                                }
0567:                            }
0568:                            //Set return key here
0569:                            String ekSha1RefValue = (String) wssContext
0570:                                    .getExtraneousProperty("EncryptedKeySHA1");
0571:                            Key secretKey = (Key) wssContext
0572:                                    .getExtraneousProperty("SecretKey");
0573:                            String keyRefValue = keyId.getReferenceValue();
0574:                            if (ekSha1RefValue != null && secretKey != null) {
0575:                                if (ekSha1RefValue.equals(keyRefValue))
0576:                                    returnKey = secretKey;
0577:                            } else {
0578:                                String message = "EncryptedKeySHA1 reference not correct";
0579:                                logger
0580:                                        .log(
0581:                                                Level.SEVERE,
0582:                                                "WSS1306:unsupported.KeyIdentifier.Reference.Type.encountered",
0583:                                                new Object[] { message });
0584:                                throw new KeySelectorException(message);
0585:                            }
0586:                            //returnKey = null; 
0587:                        } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE
0588:                                .equals(keyId.getValueType())
0589:                                || MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE
0590:                                        .equals(keyId.getValueType())) {
0591:
0592:                            String assertionID = keyId.getReferenceValue();
0593:                            Element tokenElement = wssContext
0594:                                    .getIssuedSAMLToken();
0595:                            if (tokenElement == null) {
0596:                                Assertion samlAssertion = (Assertion) tokenCache
0597:                                        .get(assertionID);
0598:                                if (samlAssertion == null) {
0599:                                    if (str.getSamlAuthorityBinding() != null) {
0600:                                        tokenElement = wssContext
0601:                                                .getSecurityEnvironment()
0602:                                                .locateSAMLAssertion(
0603:                                                        wssContext
0604:                                                                .getExtraneousProperties(),
0605:                                                        str
0606:                                                                .getSamlAuthorityBinding(),
0607:                                                        assertionID,
0608:                                                        secureMsg.getSOAPPart());
0609:                                    } else {
0610:                                        tokenElement = SAMLUtil
0611:                                                .locateSamlAssertion(
0612:                                                        assertionID, secureMsg
0613:                                                                .getSOAPPart());
0614:                                        if (!("true"
0615:                                                .equals((String) wssContext
0616:                                                        .getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED)))
0617:                                                || "false"
0618:                                                        .equals((String) wssContext
0619:                                                                .getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))) {
0620:                                            wssContext
0621:                                                    .setExtraneousProperty(
0622:                                                            MessageConstants.SAML_SIG_RESOLVED,
0623:                                                            "false");
0624:                                        }
0625:                                    }
0626:                                } else {
0627:                                    try {
0628:                                        tokenElement = samlAssertion
0629:                                                .toElement(null);
0630:                                    } catch (Exception e) {
0631:                                        logger
0632:                                                .log(
0633:                                                        Level.SEVERE,
0634:                                                        "WSS1355.unableto.resolve.SAMLAssertion",
0635:                                                        e.getMessage());
0636:                                        throw new KeySelectorException(e);
0637:                                    }
0638:                                }
0639:                            }
0640:
0641:                            if (isPolicyRecipient
0642:                                    && inferredSignaturePolicy != null) {
0643:                                MLSPolicy inferredKB = inferredSignaturePolicy
0644:                                        .getKeyBinding();
0645:                                IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
0646:                                if (inferredKB == null) {
0647:                                    if (wssContext.hasIssuedToken()) {
0648:                                        inferredSignaturePolicy
0649:                                                .setKeyBinding(itkBinding);
0650:                                    } else {
0651:                                        inferredSignaturePolicy
0652:                                                .setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
0653:                                    }
0654:                                } else if (PolicyTypeUtil
0655:                                        .derivedTokenKeyBinding(inferredKB)) {
0656:                                    if (((DerivedTokenKeyBinding) inferredKB)
0657:                                            .getOriginalKeyBinding() == null)
0658:                                        ((DerivedTokenKeyBinding) inferredKB)
0659:                                                .setOriginalKeyBinding(itkBinding);
0660:
0661:                                }
0662:                            }
0663:
0664:                            returnKey = resolveSamlAssertion(context,
0665:                                    tokenElement, purpose, assertionID);
0666:                            addAuthorityId(tokenElement, wssContext);
0667:                            if (wssContext.hasIssuedToken()) {
0668:                                SecurityUtil.initInferredIssuedTokenContext(
0669:                                        wssContext, str, returnKey);
0670:                            }
0671:
0672:                        } else {
0673:
0674:                            // it could be SAML AssertionID without ValueType on KeyIdentifier
0675:                            String assertionID = keyId
0676:                                    .getDecodedReferenceValue();
0677:                            Element samlAssertion = null;
0678:                            try {
0679:                                samlAssertion = resolveSAMLToken(str,
0680:                                        assertionID, wssContext);
0681:                            } catch (Exception e) {
0682:                                if (logger.isLoggable(Level.FINEST)) {
0683:                                    logger
0684:                                            .log(
0685:                                                    Level.FINEST,
0686:                                                    "Error occurred while trying "
0687:                                                            + "to resolve SAML assertion"
0688:                                                            + e.getMessage());
0689:                                }
0690:                            }
0691:
0692:                            if (samlAssertion != null) {
0693:                                if (isPolicyRecipient
0694:                                        && inferredSignaturePolicy != null) {
0695:                                    MLSPolicy inferredKB = inferredSignaturePolicy
0696:                                            .getKeyBinding();
0697:                                    IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
0698:                                    if (inferredKB == null) {
0699:                                        if (wssContext.hasIssuedToken()) {
0700:                                            inferredSignaturePolicy
0701:                                                    .setKeyBinding(itkBinding);
0702:                                        } else {
0703:                                            inferredSignaturePolicy
0704:                                                    .setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
0705:                                        }
0706:                                    } else if (PolicyTypeUtil
0707:                                            .derivedTokenKeyBinding(inferredKB)) {
0708:                                        if (((DerivedTokenKeyBinding) inferredKB)
0709:                                                .getOriginalKeyBinding() == null)
0710:                                            ((DerivedTokenKeyBinding) inferredKB)
0711:                                                    .setOriginalKeyBinding(itkBinding);
0712:                                    }
0713:                                }
0714:                                returnKey = resolveSamlAssertion(context,
0715:                                        samlAssertion, purpose, assertionID);
0716:                                addAuthorityId(samlAssertion, wssContext);
0717:
0718:                                //whenever we have SAML we want to record the proofkey and str
0719:                                if (wssContext.hasIssuedToken()) {
0720:                                    SecurityUtil
0721:                                            .initInferredIssuedTokenContext(
0722:                                                    wssContext, str, returnKey);
0723:                                }
0724:
0725:                            } else {
0726:                                // now assume its an X509Token
0727:                                // Note: the code below assumes base64 EncodingType for X509 SKI
0728:                                if (isPolicyRecipient
0729:                                        && inferredSignaturePolicy != null) {
0730:                                    MLSPolicy inferredKB = inferredSignaturePolicy
0731:                                            .getKeyBinding();
0732:                                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0733:                                    x509Binding
0734:                                            .setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
0735:                                    x509Binding
0736:                                            .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0737:                                    if (inferredKB == null) {
0738:                                        inferredSignaturePolicy
0739:                                                .setKeyBinding(x509Binding);
0740:                                    } else if (PolicyTypeUtil
0741:                                            .symmetricKeyBinding(inferredKB)) {
0742:                                        ((SymmetricKeyBinding) inferredKB)
0743:                                                .setKeyBinding(x509Binding);
0744:                                    } else if (PolicyTypeUtil
0745:                                            .derivedTokenKeyBinding(inferredKB)) {
0746:                                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0747:                                        if (dktBind.getOriginalKeyBinding() == null)
0748:                                            ((DerivedTokenKeyBinding) inferredKB)
0749:                                                    .setOriginalKeyBinding(x509Binding);
0750:                                        else if (PolicyTypeUtil
0751:                                                .symmetricKeyBinding(dktBind
0752:                                                        .getOriginalKeyBinding())) {
0753:                                            dktBind.getOriginalKeyBinding()
0754:                                                    .setKeyBinding(x509Binding);
0755:                                        }
0756:                                    }
0757:
0758:                                }
0759:                                if (purpose == Purpose.VERIFY) {
0760:                                    byte[] keyIdBytes = XMLUtil
0761:                                            .getDecodedBase64EncodedData(keyId
0762:                                                    .getReferenceValue());
0763:                                    wssContext.setExtraneousProperty(
0764:                                            MessageConstants.REQUESTER_KEYID,
0765:                                            new String(keyIdBytes));
0766:                                    //update other party certificate
0767:                                    X509Certificate cert = wssContext
0768:                                            .getSecurityEnvironment()
0769:                                            .getCertificate(
0770:                                                    wssContext
0771:                                                            .getExtraneousProperties(),
0772:                                                    XMLUtil
0773:                                                            .getDecodedBase64EncodedData(keyId
0774:                                                                    .getReferenceValue()));
0775:                                    wssContext
0776:                                            .getSecurityEnvironment()
0777:                                            .updateOtherPartySubject(
0778:                                                    DefaultSecurityEnvironmentImpl
0779:                                                            .getSubject(wssContext),
0780:                                                    cert);
0781:                                    returnKey = cert.getPublicKey();
0782:
0783:                                } else if (purpose == Purpose.SIGN) {
0784:                                    returnKey = wssContext
0785:                                            .getSecurityEnvironment()
0786:                                            .getPrivateKey(
0787:                                                    wssContext
0788:                                                            .getExtraneousProperties(),
0789:                                                    XMLUtil
0790:                                                            .getDecodedBase64EncodedData(keyId
0791:                                                                    .getReferenceValue()));
0792:                                }
0793:                            }
0794:
0795:                        }
0796:
0797:                    } else if (refElement instanceof  DirectReference) {
0798:                        if (keyBinding != null) {
0799:                            keyBinding
0800:                                    .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
0801:
0802:                        }
0803:                        String uri = ((DirectReference) refElement).getURI();
0804:                        if (isBSP && !uri.startsWith("#")) {
0805:                            logger.log(Level.SEVERE,
0806:                                    "WSS1356.Violation.BSP.R5204");
0807:                            throw new XWSSecurityException(
0808:                                    "Violation of BSP R5204 "
0809:                                            + ": When a SECURITY_TOKEN_REFERENCE uses a Direct Reference to an INTERNAL_SECURITY_TOKEN, it MUST use a Shorthand XPointer Reference");
0810:                        }
0811:
0812:                        String valueType = ((DirectReference) refElement)
0813:                                .getValueType();
0814:                        if (MessageConstants.DKT_VALUETYPE.equals(valueType)) {
0815:                            //TODO: this will work for now but need to handle this case here later
0816:                            valueType = null;
0817:                        }
0818:
0819:                        if (MessageConstants.X509v3_NS.equals(valueType)
0820:                                || MessageConstants.X509v1_NS.equals(valueType)) {
0821:                            // its an X509 Token
0822:                            if (keyBinding != null) {
0823:                                keyBinding.setValueType(valueType);
0824:                            }
0825:                            String wsuId = secureMsg.getIdFromFragmentRef(uri);
0826:                            X509SecurityToken token = (X509SecurityToken) insertedX509Cache
0827:                                    .get(wsuId);
0828:                            //if(token == null)
0829:                            //    token =(X509SecurityToken) tokenCache.get(wsuId);
0830:
0831:                            if (token == null) {
0832:                                token = (X509SecurityToken) resolveToken(wsuId,
0833:                                        context);
0834:                                if (token == null) {
0835:                                    logger.log(Level.SEVERE,
0836:                                            "WSS1357.unableto.locate.Token");
0837:                                    throw new KeySelectorException(
0838:                                            "Token with Id " + wsuId
0839:                                                    + "not found");
0840:                                } else {
0841:                                    tokenCache.put(wsuId, token);
0842:                                }
0843:                            }
0844:
0845:                            if (isPolicyRecipient
0846:                                    && inferredSignaturePolicy != null) {
0847:                                MLSPolicy inferredKB = inferredSignaturePolicy
0848:                                        .getKeyBinding();
0849:                                AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0850:                                x509Binding
0851:                                        .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
0852:                                x509Binding.setValueType(valueType);
0853:                                if (inferredKB == null) {
0854:                                    inferredSignaturePolicy
0855:                                            .setKeyBinding(x509Binding);
0856:                                } else if (PolicyTypeUtil
0857:                                        .symmetricKeyBinding(inferredKB)) {
0858:                                    ((SymmetricKeyBinding) inferredKB)
0859:                                            .setKeyBinding(x509Binding);
0860:                                    isSymmetric = true;
0861:                                } else if (PolicyTypeUtil
0862:                                        .derivedTokenKeyBinding(inferredKB)) {
0863:                                    DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0864:                                    if (dktBind.getOriginalKeyBinding() == null)
0865:                                        dktBind
0866:                                                .setOriginalKeyBinding(x509Binding);
0867:                                    else if (PolicyTypeUtil
0868:                                            .symmetricKeyBinding(dktBind
0869:                                                    .getOriginalKeyBinding())) {
0870:                                        dktBind.getOriginalKeyBinding()
0871:                                                .setKeyBinding(x509Binding);
0872:                                        isSymmetric = true;
0873:                                    }
0874:                                }
0875:
0876:                            }
0877:
0878:                            returnKey = resolveX509Token(wssContext, token,
0879:                                    purpose, isSymmetric);
0880:
0881:                        } else if (MessageConstants.EncryptedKey_NS
0882:                                .equals(valueType)) {
0883:                            String wsuId = secureMsg.getIdFromFragmentRef(uri);
0884:                            SecurityToken token = (SecurityToken) tokenCache
0885:                                    .get(wsuId);
0886:                            if (token == null) {
0887:                                token = resolveToken(wsuId, context);
0888:                                if (token == null) {
0889:                                    logger.log(Level.SEVERE,
0890:                                            "WSS1357.unableto.locate.Token");
0891:                                    throw new KeySelectorException(
0892:                                            "Token with Id " + wsuId
0893:                                                    + "not found");//TODO LOG ::Venu
0894:                                } else {
0895:                                    tokenCache.put(wsuId, token);
0896:                                }
0897:                            }
0898:                            KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken) token)
0899:                                    .getKeyInfo();
0900:                            SecurityTokenReference sectr = kiHB
0901:                                    .getSecurityTokenReference(0);
0902:                            SOAPElement se = sectr.getAsSoapElement();
0903:                            ReferenceElement refElem = sectr.getReference();
0904:                            if (isPolicyRecipient
0905:                                    && inferredSignaturePolicy != null) {
0906:                                MLSPolicy inferredKB = inferredSignaturePolicy
0907:                                        .getKeyBinding();
0908:                                SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
0909:                                AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0910:                                skBinding.setKeyBinding(x509Binding);
0911:                                //TODO: ReferenceType and ValueType not set on X509Binding
0912:                                if (inferredKB == null) {
0913:                                    inferredSignaturePolicy
0914:                                            .setKeyBinding(skBinding);
0915:                                } else if (PolicyTypeUtil
0916:                                        .derivedTokenKeyBinding(inferredKB)) {
0917:                                    if (((DerivedTokenKeyBinding) inferredKB)
0918:                                            .getOriginalKeyBinding() == null)
0919:                                        ((DerivedTokenKeyBinding) inferredKB)
0920:                                                .setOriginalKeyBinding(skBinding);
0921:
0922:                                }
0923:                            }
0924:
0925:                            Key privKey = resolve(se, context, Purpose.SIGN);
0926:                            Element cipherData = (Element) ((EncryptedKeyToken) token)
0927:                                    .getAsSoapElement()
0928:                                    .getChildElements(
0929:                                            new QName(
0930:                                                    MessageConstants.XENC_NS,
0931:                                                    "CipherData",
0932:                                                    MessageConstants.XENC_PREFIX))
0933:                                    .next();
0934:                            String cipherValue = cipherData
0935:                                    .getElementsByTagNameNS(
0936:                                            MessageConstants.XENC_NS,
0937:                                            "CipherValue").item(0)
0938:                                    .getTextContent();
0939:                            byte[] decodedCipher = Base64.decode(cipherValue);
0940:                            byte[] ekSha1 = MessageDigest.getInstance("SHA-1")
0941:                                    .digest(decodedCipher);
0942:
0943:                            String encEkSha1 = Base64.encode(ekSha1);
0944:                            wssContext.setExtraneousProperty(
0945:                                    MessageConstants.EK_SHA1_VALUE, encEkSha1);
0946:
0947:                            returnKey = ((EncryptedKeyToken) token)
0948:                                    .getSecretKey(privKey, encAlgo);
0949:                            wssContext.setExtraneousProperty(
0950:                                    MessageConstants.SECRET_KEY_VALUE,
0951:                                    returnKey);
0952:                        } else if (MessageConstants.SCT_VALUETYPE
0953:                                .equals(valueType)) {
0954:                            // could be wsuId or SCT Session Id
0955:                            String sctId = secureMsg.getIdFromFragmentRef(uri);
0956:                            SecurityToken token = (SecurityToken) tokenCache
0957:                                    .get(sctId);
0958:
0959:                            if (token == null) {
0960:                                token = SecurityUtil.locateBySCTId(wssContext,
0961:                                        uri);
0962:                                if (token == null) {
0963:                                    token = resolveToken(sctId, context);
0964:                                }
0965:
0966:                                if (token == null) {
0967:                                    logger.log(Level.SEVERE,
0968:                                            "WSS1358.unableto.locate.SCTToken");
0969:                                    throw new KeySelectorException(
0970:                                            "SCT Token with Id " + sctId
0971:                                                    + "not found");
0972:                                } else {
0973:                                    tokenCache.put(sctId, token);
0974:                                }
0975:                            }
0976:
0977:                            if (token instanceof  SecurityContextToken) {
0978:                                //handling for SecurityContext Token
0979:                                if (isPolicyRecipient
0980:                                        && inferredSignaturePolicy != null) {
0981:                                    MLSPolicy inferredKB = inferredSignaturePolicy
0982:                                            .getKeyBinding();
0983:                                    SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
0984:                                    if (inferredKB == null) {
0985:                                        inferredSignaturePolicy
0986:                                                .setKeyBinding(sctBinding);
0987:                                    } else if (PolicyTypeUtil
0988:                                            .derivedTokenKeyBinding(inferredKB)) {
0989:                                        ((DerivedTokenKeyBinding) inferredKB)
0990:                                                .setOriginalKeyBinding(sctBinding);
0991:                                    }
0992:                                }
0993:                                returnKey = resolveSCT(wssContext,
0994:                                        (SecurityContextTokenImpl) token,
0995:                                        purpose);
0996:
0997:                            } else {
0998:                                logger
0999:                                        .log(Level.SEVERE,
1000:                                                "WSS1359.invalid.valuetype.nonSCTtoken");
1001:                                throw new KeySelectorException(
1002:                                        "Incorrect ValueType: "
1003:                                                + MessageConstants.SCT_VALUETYPE
1004:                                                + ", specified for a Non SCT Token");
1005:                            }
1006:
1007:                        } else if (null == valueType) {
1008:                            // Log fails BSP:R3059 and R3058
1009:                            //logger.log(Level.WARNING, "Fails BSP requirements R3058 and 3059");
1010:
1011:                            // Do default processing
1012:                            String wsuId = secureMsg.getIdFromFragmentRef(uri);
1013:                            SecurityToken token = (SecurityToken) tokenCache
1014:                                    .get(wsuId);
1015:
1016:                            if (token == null) {
1017:                                token = resolveToken(wsuId, context);
1018:                                if (token == null) {
1019:                                    token = SecurityUtil.locateBySCTId(
1020:                                            wssContext, uri);
1021:                                }
1022:
1023:                                if (token == null) {
1024:                                    logger.log(Level.SEVERE,
1025:                                            "WSS1357.unableto.locate.Token");
1026:                                    throw new KeySelectorException(
1027:                                            "Token with Id " + wsuId
1028:                                                    + "not found");
1029:                                } else {
1030:                                    tokenCache.put(wsuId, token);
1031:                                }
1032:                            }
1033:
1034:                            if (token instanceof  X509SecurityToken) {
1035:                                if (isPolicyRecipient
1036:                                        && inferredSignaturePolicy != null) {
1037:                                    MLSPolicy inferredKB = inferredSignaturePolicy
1038:                                            .getKeyBinding();
1039:                                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
1040:                                    x509Binding
1041:                                            .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
1042:                                    if (inferredKB == null) {
1043:                                        inferredSignaturePolicy
1044:                                                .setKeyBinding(x509Binding);
1045:                                    } else if (PolicyTypeUtil
1046:                                            .symmetricKeyBinding(inferredKB)) {
1047:                                        ((SymmetricKeyBinding) inferredKB)
1048:                                                .setKeyBinding(x509Binding);
1049:                                        isSymmetric = true;
1050:                                    } else if (PolicyTypeUtil
1051:                                            .derivedTokenKeyBinding(inferredKB)) {
1052:                                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
1053:                                        if (dktBind.getOriginalKeyBinding() == null)
1054:                                            dktBind
1055:                                                    .setOriginalKeyBinding(x509Binding);
1056:                                        else if (PolicyTypeUtil
1057:                                                .symmetricKeyBinding(dktBind
1058:                                                        .getOriginalKeyBinding())) {
1059:                                            dktBind.getOriginalKeyBinding()
1060:                                                    .setKeyBinding(x509Binding);
1061:                                            isSymmetric = true;
1062:                                        }
1063:                                    }
1064:
1065:                                }
1066:                                returnKey = resolveX509Token(wssContext,
1067:                                        (X509SecurityToken) token, purpose,
1068:                                        isSymmetric);
1069:
1070:                            } else if (token instanceof  EncryptedKeyToken) {
1071:
1072:                                if (isPolicyRecipient
1073:                                        && inferredSignaturePolicy != null) {
1074:                                    MLSPolicy inferredKB = inferredSignaturePolicy
1075:                                            .getKeyBinding();
1076:                                    SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
1077:                                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
1078:                                    skBinding.setKeyBinding(x509Binding);
1079:                                    //TODO: ReferenceType and ValueType not set on X509Binding
1080:                                    if (inferredKB == null) {
1081:                                        inferredSignaturePolicy
1082:                                                .setKeyBinding(skBinding);
1083:                                    } else if (PolicyTypeUtil
1084:                                            .derivedTokenKeyBinding(inferredKB)) {
1085:                                        if (((DerivedTokenKeyBinding) inferredKB)
1086:                                                .getOriginalKeyBinding() == null)
1087:                                            ((DerivedTokenKeyBinding) inferredKB)
1088:                                                    .setOriginalKeyBinding(skBinding);
1089:                                    }
1090:                                }
1091:
1092:                                KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken) token)
1093:                                        .getKeyInfo();
1094:                                SecurityTokenReference sectr = kiHB
1095:                                        .getSecurityTokenReference(0);
1096:                                SOAPElement se = sectr.getAsSoapElement();
1097:                                ReferenceElement refElem = sectr.getReference();
1098:                                Key privKey = resolve(se, context, Purpose.SIGN);
1099:
1100:                                Element cipherData = (Element) ((EncryptedKeyToken) token)
1101:                                        .getAsSoapElement()
1102:                                        .getChildElements(
1103:                                                new QName(
1104:                                                        MessageConstants.XENC_NS,
1105:                                                        "CipherData",
1106:                                                        MessageConstants.XENC_PREFIX))
1107:                                        .next();
1108:                                String cipherValue = cipherData
1109:                                        .getElementsByTagNameNS(
1110:                                                MessageConstants.XENC_NS,
1111:                                                "CipherValue").item(0)
1112:                                        .getTextContent();
1113:                                byte[] decodedCipher = Base64
1114:                                        .decode(cipherValue);
1115:                                byte[] ekSha1 = MessageDigest.getInstance(
1116:                                        "SHA-1").digest(decodedCipher);
1117:
1118:                                String encEkSha1 = Base64.encode(ekSha1);
1119:                                wssContext.setExtraneousProperty(
1120:                                        MessageConstants.EK_SHA1_VALUE,
1121:                                        encEkSha1);
1122:
1123:                                returnKey = ((EncryptedKeyToken) token)
1124:                                        .getSecretKey(privKey, encAlgo);
1125:                                wssContext.setExtraneousProperty(
1126:                                        MessageConstants.SECRET_KEY_VALUE,
1127:                                        returnKey);
1128:
1129:                            } else if (token instanceof  SecurityContextToken) {
1130:                                //handling for SecurityContext Token
1131:                                if (isPolicyRecipient
1132:                                        && inferredSignaturePolicy != null) {
1133:                                    MLSPolicy inferredKB = inferredSignaturePolicy
1134:                                            .getKeyBinding();
1135:                                    SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
1136:                                    if (inferredKB == null) {
1137:                                        inferredSignaturePolicy
1138:                                                .setKeyBinding(sctBinding);
1139:                                    } else if (PolicyTypeUtil
1140:                                            .derivedTokenKeyBinding(inferredKB)) {
1141:                                        ((DerivedTokenKeyBinding) inferredKB)
1142:                                                .setOriginalKeyBinding(sctBinding);
1143:                                    }
1144:                                }
1145:                                returnKey = resolveSCT(wssContext,
1146:                                        (SecurityContextTokenImpl) token,
1147:                                        purpose);
1148:
1149:                            } else if (token instanceof  DerivedKeyTokenHeaderBlock) {
1150:                                if (isPolicyRecipient
1151:                                        && inferredSignaturePolicy != null) {
1152:                                    MLSPolicy inferredKB = inferredSignaturePolicy
1153:                                            .getKeyBinding();
1154:                                    DerivedTokenKeyBinding dtkBinding = new DerivedTokenKeyBinding();
1155:                                    if (inferredKB == null) {
1156:                                        inferredSignaturePolicy
1157:                                                .setKeyBinding(dtkBinding);
1158:                                    } else if (PolicyTypeUtil
1159:                                            .derivedTokenKeyBinding(inferredKB)) {
1160:                                        //already set - do nothing
1161:                                    } else {
1162:                                        logger
1163:                                                .log(Level.SEVERE,
1164:                                                        "WSS1360.invalid.DerivedKeyToken");
1165:                                        throw new XWSSecurityException(
1166:                                                "A derived Key Token should be a top level key binding");
1167:                                    }
1168:                                }
1169:                                returnKey = resolveDKT(context,
1170:                                        (DerivedKeyTokenHeaderBlock) token);
1171:                            } else {
1172:                                String message = " Cannot Resolve URI " + uri;
1173:                                logger
1174:                                        .log(
1175:                                                Level.SEVERE,
1176:                                                "WSS1307.unsupported.directref.mechanism",
1177:                                                new Object[] { message });
1178:                                KeySelectorException xwsse = new KeySelectorException(
1179:                                        message);
1180:                                //throw xwsse;
1181:                                throw SecurableSoapMessage
1182:                                        .newSOAPFaultException(
1183:                                                MessageConstants.WSSE_SECURITY_TOKEN_UNAVAILABLE,
1184:                                                xwsse.getMessage(), xwsse);
1185:                            }
1186:
1187:                        } else {
1188:                            logger
1189:                                    .log(
1190:                                            Level.SEVERE,
1191:                                            "WSS1307.unsupported.directref.mechanism",
1192:                                            new Object[] { ((DirectReference) refElement)
1193:                                                    .getValueType() });
1194:
1195:                            throw SecurableSoapMessage
1196:                                    .newSOAPFaultException(
1197:                                            MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1198:                                            "unsupported directreference ValueType "
1199:                                                    + ((DirectReference) refElement)
1200:                                                            .getValueType(),
1201:                                            null);
1202:                        }
1203:                    } else if (refElement instanceof  com.sun.xml.wss.core.reference.X509IssuerSerial) {
1204:                        if (keyBinding != null) {
1205:                            keyBinding
1206:                                    .setReferenceType(MessageConstants.X509_ISSUER_TYPE);
1207:                        }
1208:                        com.sun.xml.wss.core.reference.X509IssuerSerial xisElement = (com.sun.xml.wss.core.reference.X509IssuerSerial) refElement;
1209:                        BigInteger serialNumber = xisElement.getSerialNumber();
1210:                        String issuerName = xisElement.getIssuerName();
1211:                        if (isPolicyRecipient
1212:                                && inferredSignaturePolicy != null) {
1213:                            MLSPolicy inferredKB = inferredSignaturePolicy
1214:                                    .getKeyBinding();
1215:                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
1216:                            x509Binding
1217:                                    .setReferenceType(MessageConstants.X509_ISSUER_TYPE);
1218:                            if (inferredKB == null) {
1219:                                inferredSignaturePolicy
1220:                                        .setKeyBinding(x509Binding);
1221:                            } else if (PolicyTypeUtil
1222:                                    .symmetricKeyBinding(inferredKB)) {
1223:                                ((SymmetricKeyBinding) inferredKB)
1224:                                        .setKeyBinding(x509Binding);
1225:                            } else if (PolicyTypeUtil
1226:                                    .derivedTokenKeyBinding(inferredKB)) {
1227:                                DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
1228:                                if (dktBind.getOriginalKeyBinding() == null)
1229:                                    dktBind.setOriginalKeyBinding(x509Binding);
1230:                                else if (PolicyTypeUtil
1231:                                        .symmetricKeyBinding(dktBind
1232:                                                .getOriginalKeyBinding()))
1233:                                    dktBind.getOriginalKeyBinding()
1234:                                            .setKeyBinding(x509Binding);
1235:                            }
1236:
1237:                        }
1238:                        if (purpose == Purpose.VERIFY) {
1239:                            wssContext.setExtraneousProperty(
1240:                                    MessageConstants.REQUESTER_SERIAL,
1241:                                    serialNumber);
1242:                            wssContext.setExtraneousProperty(
1243:                                    MessageConstants.REQUESTER_ISSUERNAME,
1244:                                    issuerName);
1245:                            //update other party certificate
1246:                            X509Certificate cert = wssContext
1247:                                    .getSecurityEnvironment().getCertificate(
1248:                                            wssContext
1249:                                                    .getExtraneousProperties(),
1250:                                            serialNumber, issuerName);
1251:                            wssContext.getSecurityEnvironment()
1252:                                    .updateOtherPartySubject(
1253:                                            DefaultSecurityEnvironmentImpl
1254:                                                    .getSubject(wssContext),
1255:                                            cert);
1256:                            returnKey = cert.getPublicKey();
1257:
1258:                        } else if (purpose == Purpose.SIGN) {
1259:                            returnKey = wssContext.getSecurityEnvironment()
1260:                                    .getPrivateKey(
1261:                                            wssContext
1262:                                                    .getExtraneousProperties(),
1263:                                            serialNumber, issuerName);
1264:                        }
1265:
1266:                    } else {
1267:                        logger.log(Level.SEVERE,
1268:                                "WSS1308.unsupported.reference.mechanism");
1269:                        KeySelectorException xwsse = new KeySelectorException(
1270:                                "Key reference mechanism not supported");
1271:                        //throw xwsse;
1272:                        throw SecurableSoapMessage
1273:                                .newSOAPFaultException(
1274:                                        MessageConstants.WSSE_UNSUPPORTED_SECURITY_TOKEN,
1275:                                        xwsse.getMessage(), xwsse);
1276:                    }
1277:                    return returnKey;
1278:                } catch (XWSSecurityException xwsExp) {
1279:                    logger.log(Level.SEVERE,
1280:                            "WSS1353.unable.resolve.keyInformation", xwsExp);
1281:                    throw new KeySelectorException(xwsExp);
1282:                } catch (MarshalException me) {
1283:                    logger.log(Level.SEVERE,
1284:                            "WSS1353.unable.resolve.keyInformation", me);
1285:                    throw new KeySelectorException(me);
1286:                } catch (Exception ex) {
1287:                    logger.log(Level.SEVERE,
1288:                            "WSS1353.unable.resolve.keyInformation", ex);
1289:                    throw new KeySelectorException(ex);
1290:                }
1291:            }
1292:
1293:            private static Key resolveSamlAssertion(
1294:                    XMLCryptoContext dsigContext, Element samlAssertion,
1295:                    Purpose purpose, String assertionID)
1296:                    throws MarshalException, KeySelectorException,
1297:                    XWSSecurityException {
1298:
1299:                FilterProcessingContext context = (FilterProcessingContext) dsigContext
1300:                        .get(MessageConstants.WSS_PROCESSING_CONTEXT);
1301:                String samlSignatureResolved = (String) context
1302:                        .getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED);
1303:
1304:                Key key = (Key) context.getSamlIdVSKeyCache().get(assertionID);
1305:                if (key != null) {
1306:                    return key;
1307:                }
1308:
1309:                if (samlAssertion == null) {
1310:                    logger.log(Level.SEVERE,
1311:                            "WSS1355.unableto.resolve.SAMLAssertion");
1312:                    throw new XWSSecurityException(
1313:                            "Cannot Resolve SAML Assertion");
1314:                }
1315:
1316:                if (purpose == Purpose.VERIFY
1317:                        || "false".equals(samlSignatureResolved)) {
1318:                    NodeList nl = samlAssertion.getElementsByTagNameNS(
1319:                            MessageConstants.DSIG_NS, "Signature");
1320:                    //verify the signature inside the SAML assertion
1321:                    if (nl.getLength() == 0) {
1322:                        XWSSecurityException e = new XWSSecurityException(
1323:                                "Unsigned SAML Assertion encountered");
1324:                        logger.log(Level.SEVERE,
1325:                                "WSS1309.saml.signature.verify.failed", e);
1326:                        throw SecurableSoapMessage
1327:                                .newSOAPFaultException(
1328:                                        MessageConstants.WSSE_INVALID_SECURITY,
1329:                                        "Exception during Signature verfication in SAML Assertion",
1330:                                        e);
1331:                    }
1332:                    SignaturePolicy policy = (SignaturePolicy) context
1333:                            .getInferredPolicy();
1334:                    // will be only during verify.
1335:                    AuthenticationTokenPolicy.SAMLAssertionBinding keyBinding = null;
1336:
1337:                    if (policy != null) {
1338:                        keyBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) policy
1339:                                .newSAMLAssertionKeyBinding();
1340:                    }
1341:
1342:                    Element elem = (Element) nl.item(0);
1343:
1344:                    try {
1345:                        if (!SignatureProcessor.verifySignature(elem, context)) {
1346:                            logger.log(Level.SEVERE,
1347:                                    "WSS1310.saml.signature.invalid");
1348:                            throw SecurableSoapMessage
1349:                                    .newSOAPFaultException(
1350:                                            MessageConstants.WSSE_FAILED_AUTHENTICATION,
1351:                                            "SAML Assertion has invalid Signature",
1352:                                            new Exception(
1353:                                                    "SAML Assertion has invalid Signature"));
1354:                        }
1355:                    } catch (XWSSecurityException ex) {
1356:                        logger.log(Level.SEVERE,
1357:                                "WSS1310.saml.signature.invalid");
1358:                        throw SecurableSoapMessage.newSOAPFaultException(
1359:                                MessageConstants.WSSE_FAILED_AUTHENTICATION,
1360:                                "SAML Assertion has invalid Signature", ex);
1361:                    }
1362:                }
1363:
1364:                if ("false".equals(samlSignatureResolved)) {
1365:                    context.setExtraneousProperty(
1366:                            MessageConstants.SAML_SIG_RESOLVED, "true");
1367:                }
1368:
1369:                Element keyInfoElem = AssertionUtil
1370:                        .getSubjectConfirmationKeyInfo(samlAssertion);
1371:
1372:                KeyInfo keyInfo = KeyInfoFactory.getInstance()
1373:                        .unmarshalKeyInfo(new DOMStructure(keyInfoElem));
1374:                List keyInfoList = keyInfo.getContent();
1375:                Iterator content = keyInfoList.iterator();
1376:                while (content.hasNext()) {
1377:                    Object data = content.next();
1378:                    if (data instanceof  KeyName) {
1379:                        logger.log(Level.SEVERE,
1380:                                "WSS1361.unsupported.KeyName.SAML");
1381:                        throw new XWSSecurityException(
1382:                                "Unsupported KeyName under SAML SubjectConfirmation");
1383:                    } else if (data instanceof  KeyValue) {
1384:                        key = resolveKeyValue(context, (KeyValue) data, purpose);
1385:                        break;
1386:                    } else if (data instanceof  X509Data) {
1387:                        key = resolveX509Data(context, (X509Data) data, purpose);
1388:                        break;
1389:                    } else if (data instanceof  DOMStructure) {
1390:                        // we will support STR,  EK and wst:BinarySecret
1391:                        SOAPElement reference = (SOAPElement) ((DOMStructure) data)
1392:                                .getNode();
1393:                        if (isSecurityTokenReference(reference)) {
1394:                            key = resolve(reference, dsigContext, purpose);
1395:                            break;
1396:                        } else if (SecurityUtil.isBinarySecret(reference)) {
1397:                            BinarySecret bs = null;
1398:                            try {
1399:                                bs = WSTrustElementFactory.newInstance()
1400:                                        .createBinarySecret(reference);
1401:                            } catch (WSTrustException ex) {
1402:                                logger
1403:                                        .log(
1404:                                                Level.SEVERE,
1405:                                                "WSS1362.exception.WSTrust.CreatingBinarySecret",
1406:                                                ex);
1407:                                throw new XWSSecurityException(ex);
1408:                            }
1409:                            // assuming the Binary Secret is of Type 
1410:                            if ((bs.getType() == null)
1411:                                    || bs.getType().equals(
1412:                                            BinarySecret.SYMMETRIC_KEY_TYPE)) {
1413:                                String algo = "AES"; // hardcoding for now
1414:                                if (context.getAlgorithmSuite() != null) {
1415:                                    algo = SecurityUtil
1416:                                            .getSecretKeyAlgorithm(context
1417:                                                    .getAlgorithmSuite()
1418:                                                    .getEncryptionAlgorithm());
1419:                                }
1420:                                key = new SecretKeySpec(bs.getRawValue(), algo);
1421:                                break;
1422:                            } else {
1423:                                logger.log(Level.SEVERE,
1424:                                        "WSS1312.unsupported.keyinfo");
1425:                                throw new KeySelectorException(
1426:                                        "Unsupported wst:BinarySecret Type");
1427:                            }
1428:                        } else if (SecurityUtil.isEncryptedKey(reference)) {
1429:                            EncryptedKeyToken ekToken = new EncryptedKeyToken(
1430:                                    reference);
1431:                            KeyInfoHeaderBlock kiHB = ekToken.getKeyInfo();
1432:                            // assume it contains STR 
1433:                            if (kiHB.containsSecurityTokenReference()) {
1434:                                //SecurityTokenReference str = kiHB.getSecurityTokenReference(0);
1435:                                Key privKey = KeyResolver.processSTR(kiHB,
1436:                                        false, context);
1437:                                //Default algo
1438:                                String dataEncAlgo = MessageConstants.AES_BLOCK_ENCRYPTION_128;
1439:                                if (context.getAlgorithmSuite() != null) {
1440:                                    dataEncAlgo = context.getAlgorithmSuite()
1441:                                            .getEncryptionAlgorithm();
1442:                                }
1443:                                key = ekToken
1444:                                        .getSecretKey(privKey, dataEncAlgo);
1445:                                break;
1446:                            } else {
1447:                                logger.log(Level.SEVERE,
1448:                                        "WSS1312.unsupported.keyinfo");
1449:                                throw new KeySelectorException(
1450:                                        "Unsupported Key Information Inside EncryptedKey");
1451:                            }
1452:
1453:                        } else {
1454:                            logger.log(Level.SEVERE,
1455:                                    "WSS1312.unsupported.keyinfo");
1456:                            throw new KeySelectorException(
1457:                                    "Unsupported Key Information");
1458:                        }
1459:
1460:                    } else {
1461:                        logger.log(Level.SEVERE, "WSS1312.unsupported.keyinfo");
1462:                        throw new KeySelectorException(
1463:                                "Unsupported Key Information");
1464:                    }
1465:                }
1466:                context.getSamlIdVSKeyCache().put(assertionID, key);
1467:                context
1468:                        .setExtraneousProperty(
1469:                                MessageConstants.INCOMING_SAML_ASSERTION,
1470:                                samlAssertion);
1471:
1472:                //set the SAML Assertion as Public Credential inside the requester Subject
1473:                try {
1474:                    context.getSecurityEnvironment().updateOtherPartySubject(
1475:                            DefaultSecurityEnvironmentImpl.getSubject(context),
1476:                            AssertionUtil.fromElement(samlAssertion));
1477:                } catch (SAMLException ex) {
1478:                    //ignore
1479:                }
1480:
1481:                return key;
1482:            }
1483:
1484:            private static Key resolveKeyValue(FilterProcessingContext context,
1485:                    KeyValue keyValue, Purpose purpose)
1486:                    throws KeySelectorException {
1487:                try {
1488:                    if (purpose == Purpose.VERIFY) {
1489:                        return keyValue.getPublicKey();
1490:                    } else if (purpose == Purpose.SIGN) {
1491:                        return context.getSecurityEnvironment().getPrivateKey(
1492:                                context.getExtraneousProperties(),
1493:                                keyValue.getPublicKey(), true);
1494:                    }
1495:                } catch (Exception e) {
1496:                    logger.log(Level.SEVERE, "WSS1313.illegal.key.value", e
1497:                            .getMessage());
1498:                    throw new KeySelectorException(e);
1499:                }
1500:                return null;
1501:            }
1502:
1503:            private static Key resolveX509Data(FilterProcessingContext context,
1504:                    X509Data x509Data, Purpose purpose)
1505:                    throws KeySelectorException {
1506:
1507:                X509Certificate cert = null;
1508:
1509:                try {
1510:                    List data = x509Data.getContent();
1511:                    Iterator iterator = data.iterator();
1512:                    while (iterator.hasNext()) {//will break for in single loop;
1513:                        Object content = iterator.next();
1514:                        if (content instanceof  X509Certificate) {
1515:                            cert = (X509Certificate) content;
1516:                        } else if (content instanceof  byte[]) {
1517:                            byte[] ski = (byte[]) content;
1518:                            if (purpose == Purpose.VERIFY) {
1519:                                //update other party subject
1520:                                cert = context
1521:                                        .getSecurityEnvironment()
1522:                                        .getCertificate(
1523:                                                context
1524:                                                        .getExtraneousProperties(),
1525:                                                ski);
1526:                                context.getSecurityEnvironment()
1527:                                        .updateOtherPartySubject(
1528:                                                DefaultSecurityEnvironmentImpl
1529:                                                        .getSubject(context),
1530:                                                cert);
1531:                                return cert.getPublicKey();
1532:                            } else if (purpose == Purpose.SIGN) {
1533:                                return context
1534:                                        .getSecurityEnvironment()
1535:                                        .getPrivateKey(
1536:                                                context
1537:                                                        .getExtraneousProperties(),
1538:                                                ski);
1539:                            }
1540:                        } else if (content instanceof  String) {
1541:                            logger.log(Level.SEVERE,
1542:                                    "WSS1312.unsupported.keyinfo");
1543:                            throw new KeySelectorException(
1544:                                    "X509SubjectName child element of X509Data is not yet supported by our implementation");
1545:                        } else if (content instanceof  X509IssuerSerial) {
1546:                            X509IssuerSerial xis = (X509IssuerSerial) content;
1547:                            if (purpose == Purpose.VERIFY) {
1548:                                //update other party certificate
1549:                                cert = context
1550:                                        .getSecurityEnvironment()
1551:                                        .getCertificate(
1552:                                                context
1553:                                                        .getExtraneousProperties(),
1554:                                                xis.getSerialNumber(),
1555:                                                xis.getIssuerName());
1556:                                context.getSecurityEnvironment()
1557:                                        .updateOtherPartySubject(
1558:                                                DefaultSecurityEnvironmentImpl
1559:                                                        .getSubject(context),
1560:                                                cert);
1561:                                return cert.getPublicKey();
1562:                            } else if (purpose == Purpose.SIGN) {
1563:                                return context
1564:                                        .getSecurityEnvironment()
1565:                                        .getPrivateKey(
1566:                                                context
1567:                                                        .getExtraneousProperties(),
1568:                                                xis.getSerialNumber(),
1569:                                                xis.getIssuerName());
1570:                            }
1571:
1572:                        } else {
1573:                            logger.log(Level.SEVERE,
1574:                                    "WSS1312.unsupported.keyinfo");
1575:                            throw new KeySelectorException(
1576:                                    "Unsupported child element of X509Data encountered");
1577:                        }
1578:
1579:                        if (purpose == Purpose.VERIFY) {
1580:                            //update other part subject
1581:                            context.getSecurityEnvironment()
1582:                                    .updateOtherPartySubject(
1583:                                            DefaultSecurityEnvironmentImpl
1584:                                                    .getSubject(context), cert);
1585:                            return cert.getPublicKey();
1586:                        } else if (purpose == Purpose.SIGN) {
1587:                            return context.getSecurityEnvironment()
1588:                                    .getPrivateKey(
1589:                                            context.getExtraneousProperties(),
1590:                                            cert);
1591:                        }
1592:                    }
1593:                } catch (Exception e) {
1594:                    logger.log(Level.SEVERE, "WSS1314.illegal.x509.data", e
1595:                            .getMessage());
1596:                    throw new KeySelectorException(e);
1597:                }
1598:                return null;//Should never come here.
1599:            }
1600:
1601:            private static Key resolveX509Token(
1602:                    FilterProcessingContext context, X509SecurityToken token,
1603:                    Purpose purpose, boolean isSymmetric)
1604:                    throws XWSSecurityException {
1605:                if (purpose == Purpose.VERIFY) {
1606:                    // Update the Subject of the sender
1607:                    //SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
1608:                    X509Certificate cert = token.getCertificate();
1609:                    if (!isSymmetric) {
1610:                        context.getSecurityEnvironment()
1611:                                .updateOtherPartySubject(
1612:                                        DefaultSecurityEnvironmentImpl
1613:                                                .getSubject(context), cert);
1614:                    }
1615:                    return cert.getPublicKey();
1616:                } else if (purpose == Purpose.SIGN
1617:                        || purpose == Purpose.DECRYPT) {
1618:                    return context.getSecurityEnvironment().getPrivateKey(
1619:                            context.getExtraneousProperties(),
1620:                            token.getCertificate());
1621:                }
1622:                return null;
1623:            }
1624:
1625:            private static boolean isSecurityTokenReference(Element reference) {
1626:                if (MessageConstants.WSSE_SECURITY_TOKEN_REFERENCE_LNAME
1627:                        .equals(reference.getLocalName()))
1628:                    return true;
1629:                return false;
1630:            }
1631:
1632:            /**
1633:             * BinaryTokens if found would be cached into {@link FilterProcessingContext}.
1634:             * @param uri
1635:             * @param context
1636:             * @throws URIReferenceException
1637:             * @throws XWSSecurityException
1638:             * @return
1639:             */
1640:            protected static SecurityToken resolveToken(final String uri,
1641:                    XMLCryptoContext context) throws URIReferenceException,
1642:                    XWSSecurityException {
1643:
1644:                URIDereferencer resolver = context.getURIDereferencer();
1645:                URIReference uriRef = new URIReference() {
1646:
1647:                    public String getURI() {
1648:                        return uri;
1649:                    }
1650:
1651:                    public String getType() {
1652:                        return null;
1653:                    }
1654:                };
1655:
1656:                FilterProcessingContext wssContext = (FilterProcessingContext) context
1657:                        .get(MessageConstants.WSS_PROCESSING_CONTEXT);
1658:
1659:                SecurityPolicy securityPolicy = wssContext.getSecurityPolicy();
1660:
1661:                boolean isBSP = false;
1662:
1663:                if (securityPolicy != null) {
1664:                    if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
1665:                        isBSP = ((MessagePolicy) securityPolicy).isBSP();
1666:                    } else {
1667:                        isBSP = ((WSSPolicy) securityPolicy).isBSP();
1668:                    }
1669:                }
1670:
1671:                try {
1672:                    NodeSetData set = (NodeSetData) resolver.dereference(
1673:                            uriRef, context);
1674:                    Iterator itr = set.iterator();
1675:                    while (itr.hasNext()) {
1676:                        Node node = (Node) itr.next();
1677:                        if (MessageConstants.WSSE_BINARY_SECURITY_TOKEN_LNAME
1678:                                .equals(node.getLocalName())) {
1679:                            X509SecurityToken token = new X509SecurityToken(
1680:                                    (SOAPElement) node, isBSP);
1681:                            X509Certificate cert = null;
1682:                            try {
1683:                                cert = token.getCertificate();
1684:                            } catch (XWSSecurityException xwe) {
1685:                                logger.log(Level.SEVERE,
1686:                                        "WSS1363.invalid.security.token");
1687:                                throw SecurableSoapMessage
1688:                                        .newSOAPFaultException(
1689:                                                MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1690:                                                "A Invalid security token was provided ",
1691:                                                xwe);
1692:                            }
1693:                            if (!wssContext.getSecurityEnvironment()
1694:                                    .validateCertificate(cert)) {
1695:                                logger
1696:                                        .log(Level.SEVERE,
1697:                                                "WSS1364.unableto.validate.certificate");
1698:                                throw SecurableSoapMessage
1699:                                        .newSOAPFaultException(
1700:                                                MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1701:                                                "Certificate validation failed",
1702:                                                null);
1703:                            }
1704:                            return token;
1705:                        } else if (MessageConstants.ENCRYPTEDKEY_LNAME
1706:                                .equals(node.getLocalName())) {
1707:                            return new EncryptedKeyToken((SOAPElement) node);
1708:                        } else if (MessageConstants.SECURITY_CONTEXT_TOKEN_LNAME
1709:                                .equals(node.getLocalName())) {
1710:                            return new SecurityContextTokenImpl(
1711:                                    (SOAPElement) node);
1712:                        } else if (MessageConstants.DERIVEDKEY_TOKEN_LNAME
1713:                                .equals(node.getLocalName())) {
1714:                            return new DerivedKeyTokenHeaderBlock(
1715:                                    (SOAPElement) node);
1716:                        }
1717:
1718:                    }
1719:                } catch (URIReferenceException ure) {
1720:                    logger.log(Level.SEVERE,
1721:                            "WSS1304.FC_SECURITY_TOKEN_UNAVAILABLE", ure);
1722:                    throw SecurableSoapMessage.newSOAPFaultException(
1723:                            MessageConstants.WSSE_SECURITY_TOKEN_UNAVAILABLE,
1724:                            "Referenced Security Token could not be retrieved",
1725:                            ure);
1726:                }
1727:
1728:                logger.log(Level.SEVERE, "WSS1305.UnSupported.security.token");
1729:                throw SecurableSoapMessage.newSOAPFaultException(
1730:                        MessageConstants.WSSE_UNSUPPORTED_SECURITY_TOKEN,
1731:                        "A Unsupported token was provided ", null);
1732:            }
1733:
1734:            private static Element resolveSAMLToken(
1735:                    SecurityTokenReference tokenRef, String assertionId,
1736:                    FilterProcessingContext context)
1737:                    throws XWSSecurityException {
1738:
1739:                /*
1740:                Assertion ret = (Assertion)context.getTokenCache().get(assertionId);
1741:                if (ret != null)
1742:                    return ret;
1743:                 */
1744:
1745:                // first check if this is a Trust Issued Token
1746:                Element tokenElement = context.getIssuedSAMLToken();
1747:                if (tokenElement != null) {
1748:                    context.setExtraneousProperty(
1749:                            MessageConstants.SAML_SIG_RESOLVED, "false");
1750:                }
1751:                if (tokenElement == null) {
1752:                    if (tokenRef.getSamlAuthorityBinding() != null) {
1753:                        tokenElement = context.getSecurityEnvironment()
1754:                                .locateSAMLAssertion(
1755:                                        context.getExtraneousProperties(),
1756:                                        tokenRef.getSamlAuthorityBinding(),
1757:                                        assertionId,
1758:                                        context.getSOAPMessage().getSOAPPart());
1759:
1760:                    } else {
1761:                        tokenElement = SAMLUtil.locateSamlAssertion(
1762:                                assertionId, context.getSOAPMessage()
1763:                                        .getSOAPPart());
1764:                        if (!("true"
1765:                                .equals((String) context
1766:                                        .getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED)))
1767:                                || "false"
1768:                                        .equals((String) context
1769:                                                .getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))) {
1770:                            context
1771:                                    .setExtraneousProperty(
1772:                                            MessageConstants.SAML_SIG_RESOLVED,
1773:                                            "false");
1774:                        }
1775:                    }
1776:                }
1777:                //TODO: expensive conversion happening here 
1778:                try {
1779:                    // if it is an Encrypted SAML Assertion we cannot decrypt it
1780:                    // on the client side since we don't have the Private Key
1781:                    if ("EncryptedData".equals(tokenElement.getLocalName())) {
1782:                        // do nothing
1783:                    }
1784:                } catch (Exception e) {
1785:                    logger.log(Level.SEVERE,
1786:                            "WSS1355.unableto.resolve.SAMLAssertion", e);
1787:                    throw new XWSSecurityException(e);
1788:                }
1789:
1790:                return tokenElement;
1791:            }
1792:
1793:            private static void addAuthorityId(Element assertion,
1794:                    FilterProcessingContext fp) {
1795:                String issuer = null;
1796:
1797:                SignaturePolicy ep = (SignaturePolicy) fp.getInferredPolicy();
1798:                if (ep != null) {
1799:                    AuthenticationTokenPolicy.SAMLAssertionBinding kb = (AuthenticationTokenPolicy.SAMLAssertionBinding) ep
1800:                            .newSAMLAssertionKeyBinding();
1801:
1802:                    if (assertion.getAttributeNode("ID") != null) {
1803:
1804:                        NodeList nl = assertion.getElementsByTagNameNS(
1805:                                MessageConstants.SAML_v2_0_NS, "Issuer");
1806:
1807:                        Element issuerElement = (Element) nl.item(0);
1808:                        issuer = issuerElement.getTextContent();
1809:                        //  System.out.println("Issuer 000000000000 :" + issuerElement.getTextContent());
1810:
1811:                    } else {
1812:                        issuer = assertion.getAttribute("Issuer");
1813:                    }
1814:                    kb.setAuthorityIdentifier(issuer);
1815:                }
1816:            }
1817:
1818:            // this method would be called on incoming client/server messages  
1819:            private static Key resolveSCT(FilterProcessingContext context,
1820:                    SecurityContextTokenImpl token, Purpose purpose)
1821:                    throws XWSSecurityException {
1822:
1823:                // first set it into Extraneous Properties
1824:                context.setExtraneousProperty(MessageConstants.INCOMING_SCT,
1825:                        token);
1826:                // now get the SC ID
1827:                String scId = token.getSCId();
1828:
1829:                IssuedTokenContext ctx = context.getIssuedTokenContext(scId);
1830:                if (ctx == null) {
1831:                    // this can happen on client side where the map is based on tokenId
1832:                    Enumeration elements = context.getIssuedTokenContextMap()
1833:                            .elements();
1834:                    while (elements.hasMoreElements()) {
1835:                        IssuedTokenContext ictx = (IssuedTokenContext) elements
1836:                                .nextElement();
1837:                        Object tok = ictx.getSecurityToken();
1838:                        String ctxid = null;
1839:                        if (tok instanceof  SecurityContextToken) {
1840:                            ctxid = ((SecurityContextToken) tok)
1841:                                    .getIdentifier().toString();
1842:                            if (ctxid.equals(scId)) {
1843:                                ctx = ictx;
1844:                                break;
1845:                            }
1846:                        }
1847:
1848:                    }
1849:                }
1850:
1851:                if (ctx == null) {
1852:                    logger
1853:                            .log(Level.SEVERE,
1854:                                    "WSS1365.unableto.locate.SecureConversation.Session");
1855:                    throw new XWSSecurityException(
1856:                            "Could not locate SecureConversation session for Id:"
1857:                                    + scId);
1858:                }
1859:
1860:                byte[] proofKey = ctx.getProofKey();
1861:                // this is because the key would be used for Signatures
1862:                //TODO: PLUGFEST : change this to globally available encryption algo
1863:                if (proofKey == null) {
1864:                    logger
1865:                            .log(Level.SEVERE,
1866:                                    "WSS1365.unableto.locate.SecureConversation.Session");
1867:                    throw new XWSSecurityException(
1868:                            "Could not locate SecureConversation session for Id:"
1869:                                    + scId);
1870:                }
1871:
1872:                String algo = "AES"; // hardcoding for now
1873:                if (context.getAlgorithmSuite() != null) {
1874:                    algo = SecurityUtil.getSecretKeyAlgorithm(context
1875:                            .getAlgorithmSuite().getEncryptionAlgorithm());
1876:                }
1877:                SecretKeySpec key = new SecretKeySpec(proofKey, algo);
1878:                if (purpose == Purpose.VERIFY) {
1879:                    Subject subj = ctx.getRequestorSubject();
1880:                    if (subj != null) {
1881:                        // subj will be null if this is the client side execution
1882:                        if (context
1883:                                .getExtraneousProperty(MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ) == null) {
1884:                            //do it only once
1885:                            context
1886:                                    .getSecurityEnvironment()
1887:                                    .updateOtherPartySubject(
1888:                                            SecurityUtil.getSubject(context
1889:                                                    .getExtraneousProperties()),
1890:                                            subj);
1891:                            context.getExtraneousProperties().put(
1892:                                    MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ,
1893:                                    "true");
1894:                        }
1895:                    }
1896:                }
1897:
1898:                return key;
1899:            }
1900:
1901:            private static Key resolveDKT(XMLCryptoContext context,
1902:                    DerivedKeyTokenHeaderBlock token)
1903:                    throws XWSSecurityException {
1904:
1905:                FilterProcessingContext wssContext = (FilterProcessingContext) context
1906:                        .get(MessageConstants.WSS_PROCESSING_CONTEXT);
1907:                AlgorithmSuite algSuite = wssContext.getAlgorithmSuite();
1908:                //TODO: hardcoded for testing -- need to obtain this from somewhere
1909:                String algorithm = MessageConstants.AES_BLOCK_ENCRYPTION_128;
1910:                if (algSuite != null)
1911:                    algorithm = algSuite.getEncryptionAlgorithm();
1912:
1913:                try {
1914:                    SecurityTokenReference sectr = token.getDerivedKeyElement();
1915:                    SOAPElement se = sectr.getAsSoapElement();
1916:                    //ReferenceElement refElem = sectr.getReference();
1917:                    Key encKey = resolve(se, context, Purpose.SIGN);
1918:                    byte[] secret = encKey.getEncoded();
1919:
1920:                    byte[] nonce = token.getNonce();
1921:                    long length = token.getLength();
1922:                    long offset = token.getOffset();
1923:                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset,
1924:                            length, secret, nonce);
1925:                    String jceAlgo = SecurityUtil
1926:                            .getSecretKeyAlgorithm(algorithm);
1927:                    Key returnKey = dkt.generateSymmetricKey(jceAlgo);
1928:                    return returnKey;
1929:                } catch (Exception e) {
1930:                    logger.log(Level.SEVERE,
1931:                            "WSS1366.unable.generateSymmetricKey.DKT", e);
1932:                    throw new XWSSecurityException(e);
1933:                }
1934:            }
1935:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.