Source Code Cross Referenced for KeySelectorImpl.java in  » 6.0-JDK-Modules-com.sun » xws-security » com » sun » xml » ws » security » opt » impl » incoming » 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.ws.security.opt.impl.incoming 
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:        package com.sun.xml.ws.security.opt.impl.incoming;
0024:
0025:        import com.sun.xml.ws.security.IssuedTokenContext;
0026:        import com.sun.xml.ws.security.SecurityContextTokenInfo;
0027:        import com.sun.xml.ws.security.opt.api.SecurityElement;
0028:        import com.sun.xml.ws.security.opt.api.SecurityHeaderElement;
0029:        import com.sun.xml.ws.security.opt.impl.crypto.OctectStreamData;
0030:        import com.sun.xml.ws.security.opt.impl.crypto.SSEData;
0031:
0032:        import com.sun.xml.wss.impl.misc.SecurityUtil;
0033:        import com.sun.xml.wss.impl.policy.MLSPolicy;
0034:        import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0035:        import com.sun.xml.wss.impl.policy.mls.DerivedTokenKeyBinding;
0036:        import com.sun.xml.wss.impl.policy.mls.IssuedTokenKeyBinding;
0037:        import com.sun.xml.wss.impl.policy.mls.SecureConversationTokenKeyBinding;
0038:        import com.sun.xml.wss.impl.policy.mls.SymmetricKeyBinding;
0039:        import java.util.Enumeration;
0040:
0041:        import javax.crypto.spec.SecretKeySpec;
0042:        import javax.xml.crypto.Data;
0043:        import javax.xml.crypto.KeySelector;
0044:        import javax.xml.crypto.KeySelectorException;
0045:        import javax.xml.crypto.KeySelectorResult;
0046:        import javax.xml.crypto.AlgorithmMethod;
0047:        import javax.xml.crypto.XMLCryptoContext;
0048:        import javax.xml.crypto.XMLStructure;
0049:        import javax.xml.crypto.URIDereferencer;
0050:        import javax.xml.crypto.URIReference;
0051:        import javax.xml.crypto.URIReferenceException;
0052:        import javax.xml.crypto.dsig.keyinfo.KeyInfo;
0053:        import javax.xml.crypto.dsig.SignatureMethod;
0054:        import javax.xml.crypto.dsig.keyinfo.KeyValue;
0055:        import javax.xml.crypto.dsig.keyinfo.KeyName;
0056:        import javax.xml.crypto.dsig.keyinfo.X509Data;
0057:        import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
0058:
0059:        import javax.xml.bind.JAXBElement;
0060:
0061:        import java.security.PublicKey;
0062:        import java.security.KeyException;
0063:        import java.security.Key;
0064:        import java.security.cert.X509Certificate;
0065:
0066:        import java.math.BigInteger;
0067:        import java.util.List;
0068:        import java.util.Iterator;
0069:        import java.util.HashMap;
0070:        import java.util.logging.Level;
0071:        import java.util.logging.Logger;
0072:        import com.sun.xml.wss.logging.LogDomainConstants;
0073:
0074:        import com.sun.xml.ws.security.opt.impl.keyinfo.SecurityTokenReference;
0075:        import com.sun.xml.ws.security.opt.api.reference.Reference;
0076:        import com.sun.xml.ws.security.opt.api.reference.KeyIdentifier;
0077:        import com.sun.xml.ws.security.opt.api.reference.DirectReference;
0078:
0079:        import com.sun.xml.ws.runtime.util.Session;
0080:        import com.sun.xml.ws.runtime.util.SessionManager;
0081:
0082:        import com.sun.xml.wss.XWSSecurityException;
0083:        import com.sun.xml.wss.impl.MessageConstants;
0084:        import com.sun.xml.wss.impl.policy.SecurityPolicy;
0085:        import com.sun.xml.wss.impl.PolicyTypeUtil;
0086:        import com.sun.xml.wss.impl.policy.mls.WSSPolicy;
0087:        import com.sun.xml.wss.impl.policy.mls.MessagePolicy;
0088:        import com.sun.xml.wss.impl.XMLUtil;
0089:        import com.sun.xml.wss.impl.misc.DefaultSecurityEnvironmentImpl;
0090:        import com.sun.xml.ws.security.opt.impl.JAXBFilterProcessingContext;
0091:        import com.sun.xml.ws.security.opt.impl.util.SOAPUtil;
0092:        import com.sun.xml.ws.security.opt.crypto.jaxb.JAXBStructure;
0093:        import javax.xml.crypto.KeySelector.Purpose;
0094:        import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
0095:        import java.security.cert.CertificateEncodingException;
0096:        import javax.security.auth.Subject;
0097:
0098:        /**
0099:         *
0100:         * @author Ashutosh.Shahi@Sun.Com
0101:         */
0102:        public class KeySelectorImpl extends KeySelector {
0103:
0104:            private static KeySelectorImpl keyResolver = null;
0105:            private static final Logger logger = Logger.getLogger(
0106:                    LogDomainConstants.IMPL_SIGNATURE_DOMAIN,
0107:                    LogDomainConstants.IMPL_SIGNATURE_DOMAIN_BUNDLE);
0108:
0109:            /** Creates a new instance of KeySelectorImpl */
0110:            static {
0111:                keyResolver = new KeySelectorImpl();
0112:            }
0113:
0114:            /** Creates a new instance of KeySelectorImpl */
0115:            private KeySelectorImpl() {
0116:            }
0117:
0118:            /**
0119:             *
0120:             * @return
0121:             */
0122:            public static KeySelector getInstance() {
0123:                return keyResolver;
0124:            }
0125:
0126:            /**
0127:             *
0128:             * @param keyInfo
0129:             * @param purpose
0130:             * @param method
0131:             * @param context
0132:             * @throws KeySelectorException
0133:             * @return
0134:             */
0135:            public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
0136:                    AlgorithmMethod method, XMLCryptoContext context)
0137:                    throws KeySelectorException {
0138:                if (keyInfo == null) {
0139:                    if (logger.getLevel() == Level.SEVERE) {
0140:                        logger.log(Level.SEVERE, "WSS1317.keyinfo.null");
0141:                    }
0142:                    throw new KeySelectorException("Null KeyInfo object!");
0143:                }
0144:
0145:                if (MessageConstants.debug) {
0146:                    logger.log(Level.FINEST,
0147:                            "KeySelectorResult::select Purpose =  " + purpose);
0148:                    logger.log(Level.FINEST,
0149:                            "KeySelectorResult::select Algorithm is "
0150:                                    + method.getAlgorithm());
0151:                    logger.log(Level.FINEST,
0152:                            "KeySelectorResult::select ParameterSpec is "
0153:                                    + method.getParameterSpec());
0154:                }
0155:                try {
0156:
0157:                    SignatureMethod sm = (SignatureMethod) method;
0158:                    List list = keyInfo.getContent();
0159:                    JAXBFilterProcessingContext wssContext = (JAXBFilterProcessingContext) context
0160:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0161:
0162:                    SecurityPolicy securityPolicy = wssContext
0163:                            .getSecurityPolicy();
0164:                    boolean isBSP = false;
0165:                    if (securityPolicy != null) {
0166:                        if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
0167:                            isBSP = ((MessagePolicy) securityPolicy).isBSP();
0168:                        } else {
0169:                            isBSP = ((WSSPolicy) securityPolicy).isBSP();
0170:                        }
0171:                    }
0172:
0173:                    if (isBSP && list.size() > 1) {
0174:                        logger
0175:                                .log(Level.SEVERE,
0176:                                        "BSP Violation of R5402: KeyInfo MUST have exactly one child");
0177:                        throw SOAPUtil
0178:                                .newSOAPFaultException(
0179:                                        MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
0180:                                        "BSP Violation of R5402: KeyInfo MUST have exactly one child",
0181:                                        null);
0182:                    }
0183:
0184:                    boolean isStr = false;
0185:
0186:                    for (int i = 0; i < list.size(); i++) {
0187:                        XMLStructure xmlStructure = (XMLStructure) list.get(i);
0188:                        if (xmlStructure instanceof  KeyValue) {
0189:                            PublicKey pk = null;
0190:                            try {
0191:                                pk = ((KeyValue) xmlStructure).getPublicKey();
0192:                            } catch (KeyException ke) {
0193:                                throw new KeySelectorException(ke);
0194:                            }
0195:                            // make sure algorithm is compatible with method
0196:                            if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
0197:                                return new SimpleKeySelectorResult(pk);
0198:                            }
0199:                        } else if (xmlStructure instanceof  JAXBStructure) {
0200:                            JAXBElement reference = ((JAXBStructure) xmlStructure)
0201:                                    .getJAXBElement();
0202:                            if (isSecurityTokenReference(reference)) {
0203:                                isStr = true;
0204:                                final Key key = resolve(reference, context,
0205:                                        purpose);
0206:                                return new KeySelectorResult() {
0207:                                    public Key getKey() {
0208:                                        return key;
0209:                                    }
0210:                                };
0211:                            }
0212:                        } else if (xmlStructure instanceof  KeyName) {
0213:                            KeyName keyName = (KeyName) xmlStructure;
0214:                            Key returnKey = wssContext.getSecurityEnvironment()
0215:                                    .getSecretKey(
0216:                                            wssContext
0217:                                                    .getExtraneousProperties(),
0218:                                            keyName.getName(), false);
0219:                            if (returnKey == null) {
0220:                                X509Certificate cert = wssContext
0221:                                        .getSecurityEnvironment()
0222:                                        .getCertificate(
0223:                                                wssContext
0224:                                                        .getExtraneousProperties(),
0225:                                                keyName.getName(), false);
0226:                                if (cert != null
0227:                                        && algEquals(sm.getAlgorithm(), cert
0228:                                                .getPublicKey().getAlgorithm())) {
0229:                                    return new SimpleKeySelectorResult(cert
0230:                                            .getPublicKey());
0231:                                }
0232:                            } else {
0233:                                return new SimpleKeySelectorResult(returnKey);
0234:                            }
0235:                        } else if (xmlStructure instanceof  X509Data) {
0236:                            Key key = resolveX509Data(wssContext,
0237:                                    (X509Data) xmlStructure, purpose);
0238:                            return new SimpleKeySelectorResult(key);
0239:                        }
0240:                    }
0241:
0242:                } catch (KeySelectorException kse) {
0243:                    throw kse;
0244:                } catch (Exception ex) {
0245:                    logger.log(Level.FINEST,
0246:                            "Error occurred while resolving keyinformation"
0247:                                    + ex.getMessage());
0248:                    throw new KeySelectorException(ex);
0249:                }
0250:                throw new KeySelectorException("No KeyValue element found!");
0251:            }
0252:
0253:            private static class SimpleKeySelectorResult implements 
0254:                    KeySelectorResult {
0255:                private Key pk;
0256:
0257:                SimpleKeySelectorResult(Key pk) {
0258:                    this .pk = pk;
0259:                }
0260:
0261:                public Key getKey() {
0262:                    return pk;
0263:                }
0264:            }
0265:
0266:            private static Key resolve(JAXBElement securityTokenReference,
0267:                    XMLCryptoContext context, Purpose purpose)
0268:                    throws KeySelectorException {
0269:                try {
0270:                    JAXBFilterProcessingContext wssContext = (JAXBFilterProcessingContext) context
0271:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0272:                    boolean isPolicyRecipient = (wssContext.getMode() == JAXBFilterProcessingContext.WSDL_POLICY);
0273:
0274:                    SecurityPolicy securityPolicy = wssContext
0275:                            .getSecurityPolicy();
0276:                    boolean isBSP = false;
0277:                    if (securityPolicy != null) {
0278:                        if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
0279:                            isBSP = ((MessagePolicy) securityPolicy).isBSP();
0280:                        } else {
0281:                            isBSP = ((WSSPolicy) securityPolicy).isBSP();
0282:                        }
0283:                    }
0284:
0285:                    //SecurityTokenReference str = new com.sun.xml.ws.opt.security.impl.keyinfo.SecurityTokenReference(
0286:                    //        (SecurityTokenReferenceType)securityTokenReference.getValue());
0287:                    SecurityTokenReference str = (SecurityTokenReference) securityTokenReference
0288:                            .getValue();
0289:                    Reference reference = str.getReference();
0290:                    //HashMap tokenCache = wssContext.getTokenCache();
0291:                    //HashMap insertedX509Cache = wssContext.getInsertedX509Cache();
0292:
0293:                    Key returnKey = null;
0294:                    if (reference instanceof  KeyIdentifier) {
0295:                        KeyIdentifier keyId = (KeyIdentifier) reference;
0296:
0297:                        returnKey = resolveKeyIdentifier(context, keyId
0298:                                .getValueType(), keyId.getReferenceValue(),
0299:                                null, purpose);
0300:
0301:                    } else if (reference instanceof  DirectReference) {
0302:                        DirectReference dReference = (DirectReference) reference;
0303:                        String uri = dReference.getURI();
0304:                        if (isBSP && !uri.startsWith("#")) {
0305:                            throw new XWSSecurityException(
0306:                                    "Violation of BSP R5204 "
0307:                                            + ": When a SECURITY_TOKEN_REFERENCE uses a Direct Reference to an INTERNAL_SECURITY_TOKEN, it MUST use a Shorthand XPointer Reference");
0308:                        }
0309:
0310:                        String valueType = dReference.getValueType();
0311:                        if (MessageConstants.DKT_VALUETYPE.equals(valueType)) {
0312:                            //TODO: this will work for now but need to handle this case here later
0313:                            valueType = null;
0314:                        }
0315:
0316:                        returnKey = resolveDirectReference(context, valueType,
0317:                                uri, purpose);
0318:
0319:                    } else if (reference instanceof  com.sun.xml.ws.security.opt.impl.reference.X509IssuerSerial) {
0320:                        com.sun.xml.ws.security.opt.impl.reference.X509IssuerSerial xis = (com.sun.xml.ws.security.opt.impl.reference.X509IssuerSerial) reference;
0321:                        BigInteger serialNumber = xis.getX509SerialNumber();
0322:                        String issuerName = xis.getX509IssuerName();
0323:
0324:                        resolveIssuerSerial(context, issuerName, serialNumber,
0325:                                xis.getId(), purpose);
0326:                    } else {
0327:                        logger.log(Level.SEVERE,
0328:                                "WSS1308.unsupported.reference.mechanism");
0329:                        KeySelectorException xwsse = new KeySelectorException(
0330:                                "Key reference mechanism not supported");
0331:                        //throw xwsse;
0332:                        throw SOAPUtil
0333:                                .newSOAPFaultException(
0334:                                        MessageConstants.WSSE_UNSUPPORTED_SECURITY_TOKEN,
0335:                                        xwsse.getMessage(), xwsse);
0336:                    }
0337:                    return returnKey;
0338:                } catch (XWSSecurityException xwsExp) {
0339:                    logger.log(Level.FINEST, "Error occurred while resolving"
0340:                            + "key information", xwsExp);
0341:                    throw new KeySelectorException(xwsExp);
0342:                } catch (Exception ex) {
0343:                    logger.log(Level.FINEST, "Error occurred while resolving"
0344:                            + "key information", ex);
0345:                    throw new KeySelectorException(ex);
0346:                }
0347:
0348:            }
0349:
0350:            public static Key resolveIssuerSerial(XMLCryptoContext context,
0351:                    String issuerName, BigInteger serialNumber, String strId,
0352:                    Purpose purpose) throws KeySelectorException {
0353:                Key returnKey = null;
0354:                String normalizedIssuerName = RFC2253Parser
0355:                        .normalize(issuerName);
0356:                try {
0357:                    JAXBFilterProcessingContext wssContext = (JAXBFilterProcessingContext) context
0358:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0359:                    MLSPolicy inferredKB = wssContext.getSecurityContext()
0360:                            .getInferredKB();
0361:
0362:                    // for policy verification
0363:                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0364:                    x509Binding
0365:                            .setReferenceType(MessageConstants.X509_ISSUER_TYPE);
0366:                    if (inferredKB == null) {
0367:                        wssContext.getSecurityContext().setInferredKB(
0368:                                x509Binding);
0369:                    } else if (PolicyTypeUtil.symmetricKeyBinding(inferredKB)) {
0370:                        ((SymmetricKeyBinding) inferredKB)
0371:                                .setKeyBinding(x509Binding);
0372:                    } else if (PolicyTypeUtil
0373:                            .derivedTokenKeyBinding(inferredKB)) {
0374:                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0375:                        if (dktBind.getOriginalKeyBinding() == null) {
0376:                            dktBind.setOriginalKeyBinding(x509Binding);
0377:                        } else if (PolicyTypeUtil.symmetricKeyBinding(dktBind
0378:                                .getOriginalKeyBinding())) {
0379:                            dktBind.getOriginalKeyBinding().setKeyBinding(
0380:                                    x509Binding);
0381:                        }
0382:                    }
0383:
0384:                    if (purpose == Purpose.VERIFY) {
0385:                        wssContext
0386:                                .setExtraneousProperty(
0387:                                        MessageConstants.REQUESTER_SERIAL,
0388:                                        serialNumber);
0389:                        wssContext.setExtraneousProperty(
0390:                                MessageConstants.REQUESTER_ISSUERNAME,
0391:                                normalizedIssuerName);
0392:
0393:                        //                returnKey = wssContext.getSecurityEnvironment().getPublicKey(
0394:                        //                        wssContext.getExtraneousProperties(),serialNumber, normalizedIssuerName);
0395:                        X509Certificate cert = wssContext
0396:                                .getSecurityEnvironment().getCertificate(
0397:                                        wssContext.getExtraneousProperties(),
0398:                                        serialNumber, normalizedIssuerName);
0399:                        returnKey = cert.getPublicKey();
0400:                        if (strId != null) {
0401:                            byte[] encodedCert = cert.getEncoded();
0402:                            wssContext.getElementCache().put(
0403:                                    strId,
0404:                                    new OctectStreamData(
0405:                                            new String(encodedCert)));
0406:                        }
0407:
0408:                    } else if (purpose == Purpose.SIGN
0409:                            || purpose == Purpose.DECRYPT) {
0410:                        returnKey = wssContext.getSecurityEnvironment()
0411:                                .getPrivateKey(
0412:                                        wssContext.getExtraneousProperties(),
0413:                                        serialNumber, normalizedIssuerName);
0414:                    }
0415:                } catch (Exception ex) {
0416:                    logger.log(Level.FINEST, "Error occurred while resolving"
0417:                            + "key information", ex);
0418:                    throw new KeySelectorException(ex);
0419:                }
0420:                return returnKey;
0421:            }
0422:
0423:            public static Key resolveDirectReference(XMLCryptoContext context,
0424:                    String valueType, String uri, Purpose purpose)
0425:                    throws KeySelectorException {
0426:
0427:                Key returnKey = null;
0428:                try {
0429:                    JAXBFilterProcessingContext wssContext = (JAXBFilterProcessingContext) context
0430:                            .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0431:                    MLSPolicy inferredKB = wssContext.getSecurityContext()
0432:                            .getInferredKB();
0433:                    String wsuId = SOAPUtil.getIdFromFragmentRef(uri);
0434:                    boolean isSymmetric = false;
0435:                    if (MessageConstants.X509v3_NS.equals(valueType)
0436:                            || MessageConstants.X509v1_NS.equals(valueType)) {
0437:                        // its an X509 Token
0438:                        BinarySecurityToken token = null;
0439:                        token = (BinarySecurityToken) resolveToken(wsuId,
0440:                                context);
0441:                        if (token == null) {
0442:                            throw new KeySelectorException("Token with Id "
0443:                                    + wsuId + "not found");
0444:                        }
0445:                        // for policy verification
0446:                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0447:                        x509Binding
0448:                                .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
0449:                        x509Binding.setValueType(valueType);
0450:                        if (inferredKB == null) {
0451:                            wssContext.getSecurityContext().setInferredKB(
0452:                                    x509Binding);
0453:                        } else if (PolicyTypeUtil
0454:                                .symmetricKeyBinding(inferredKB)) {
0455:                            ((SymmetricKeyBinding) inferredKB)
0456:                                    .setKeyBinding(x509Binding);
0457:                            isSymmetric = true;
0458:                        } else if (PolicyTypeUtil
0459:                                .derivedTokenKeyBinding(inferredKB)) {
0460:                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0461:                            if (dktBind.getOriginalKeyBinding() == null) {
0462:                                dktBind.setOriginalKeyBinding(x509Binding);
0463:                            } else if (PolicyTypeUtil
0464:                                    .symmetricKeyBinding(dktBind
0465:                                            .getOriginalKeyBinding())) {
0466:                                dktBind.getOriginalKeyBinding().setKeyBinding(
0467:                                        x509Binding);
0468:                                isSymmetric = true;
0469:                            }
0470:                        }
0471:
0472:                        returnKey = resolveX509Token(wssContext, token,
0473:                                purpose, isSymmetric);
0474:                    } else if (MessageConstants.EncryptedKey_NS
0475:                            .equals(valueType)) {
0476:                        EncryptedKey token = (EncryptedKey) resolveToken(wsuId,
0477:                                context);
0478:                        if (token == null) {
0479:                            throw new KeySelectorException("Token with Id "
0480:                                    + wsuId + "not found");
0481:                        }
0482:
0483:                        // for policy verification
0484:                        WSSPolicy skBinding = null;
0485:                        boolean saml = wssContext.getSecurityContext()
0486:                                .getIsSAMLKeyBinding();
0487:                        if (saml) {
0488:                            skBinding = new AuthenticationTokenPolicy.SAMLAssertionBinding();
0489:                            //reset the property, but why ?. Currently Policy is being inferred for
0490:                            // every ED, so reset here will screw up again
0491:                            //wssContext.getSecurityContext().setIsSAMLKeyBinding(false);
0492:                        } else {
0493:                            // for policy verification
0494:                            SymmetricKeyBinding symkBinding = new SymmetricKeyBinding();
0495:                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0496:                            symkBinding.setKeyBinding(x509Binding);
0497:                            skBinding = symkBinding;
0498:                        }
0499:                        //TODO: ReferenceType and ValueType not set on X509Binding
0500:                        if (inferredKB == null) {
0501:                            wssContext.getSecurityContext().setInferredKB(
0502:                                    skBinding);
0503:                        } else if (PolicyTypeUtil
0504:                                .derivedTokenKeyBinding(inferredKB)) {
0505:                            if (((DerivedTokenKeyBinding) inferredKB)
0506:                                    .getOriginalKeyBinding() == null)
0507:                                ((DerivedTokenKeyBinding) inferredKB)
0508:                                        .setOriginalKeyBinding(skBinding);
0509:
0510:                        }
0511:
0512:                        // TODO: where are EKSHA1 and and SECRET_KEY values being set?
0513:
0514:                        String algo = wssContext.getAlgorithmSuite()
0515:                                .getEncryptionAlgorithm();
0516:                        returnKey = token.getKey(algo);
0517:
0518:                    } else if (MessageConstants.SCT_VALUETYPE.equals(valueType)) {
0519:                        returnKey = resolveSCT(wssContext, wsuId, purpose,
0520:                                false);
0521:
0522:                        if (returnKey == null) {
0523:                            SecurityContextToken scToken = (SecurityContextToken) resolveToken(
0524:                                    wsuId, context);
0525:                            //wssContext.setExtraneousProperty(MessageConstants.INCOMING_SCT, scToken);
0526:                            if (scToken == null) {
0527:                                throw new KeySelectorException("Token with Id "
0528:                                        + wsuId + "not found");
0529:                            }
0530:                            returnKey = resolveSCT(wssContext, scToken
0531:                                    .getSCId(), purpose, true);
0532:                        }
0533:
0534:                        SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
0535:                        if (inferredKB == null) {
0536:                            wssContext.getSecurityContext().setInferredKB(
0537:                                    sctBinding);
0538:                        } else if (PolicyTypeUtil
0539:                                .derivedTokenKeyBinding(inferredKB)) {
0540:                            ((DerivedTokenKeyBinding) inferredKB)
0541:                                    .setOriginalKeyBinding(sctBinding);
0542:                        }
0543:                        return returnKey;
0544:                    } else if (MessageConstants.DKT_VALUETYPE.equals(valueType)) {
0545:                        DerivedKeyToken token = (DerivedKeyToken) resolveToken(
0546:                                wsuId, context);
0547:                        if (token == null) {
0548:                            throw new KeySelectorException("Token with Id "
0549:                                    + wsuId + "not found");
0550:                        }
0551:                        DerivedTokenKeyBinding dtkBinding = new DerivedTokenKeyBinding();
0552:                        dtkBinding.setOriginalKeyBinding(token.getInferredKB());
0553:                        if (inferredKB == null) {
0554:                            wssContext.getSecurityContext().setInferredKB(
0555:                                    dtkBinding);
0556:                        } else if (PolicyTypeUtil
0557:                                .derivedTokenKeyBinding(inferredKB)) {
0558:                            //already set - do nothing
0559:                        } else {
0560:                            //throw new XWSSecurityException("A derived Key Token should be a top level key binding");
0561:                        }
0562:
0563:                        returnKey = ((DerivedKeyToken) token).getKey();
0564:                    } else if (null == valueType) {
0565:
0566:                        SecurityHeaderElement token = resolveToken(wsuId,
0567:                                context);
0568:                        if (token == null) {
0569:                            throw new KeySelectorException("Token with Id "
0570:                                    + wsuId + "not found");
0571:                        }
0572:                        if (token instanceof  BinarySecurityToken) {
0573:                            // for policy verification
0574:                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0575:                            x509Binding
0576:                                    .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
0577:                            if (inferredKB == null) {
0578:                                wssContext.getSecurityContext().setInferredKB(
0579:                                        x509Binding);
0580:                            } else if (PolicyTypeUtil
0581:                                    .symmetricKeyBinding(inferredKB)) {
0582:                                ((SymmetricKeyBinding) inferredKB)
0583:                                        .setKeyBinding(x509Binding);
0584:                            } else if (PolicyTypeUtil
0585:                                    .derivedTokenKeyBinding(inferredKB)) {
0586:                                DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0587:                                if (dktBind.getOriginalKeyBinding() == null)
0588:                                    dktBind.setOriginalKeyBinding(x509Binding);
0589:                                else if (PolicyTypeUtil
0590:                                        .symmetricKeyBinding(dktBind
0591:                                                .getOriginalKeyBinding())) {
0592:                                    dktBind.getOriginalKeyBinding()
0593:                                            .setKeyBinding(x509Binding);
0594:                                }
0595:                            }
0596:                            //
0597:
0598:                            returnKey = resolveX509Token(wssContext,
0599:                                    (BinarySecurityToken) token, purpose,
0600:                                    isSymmetric);
0601:                        } else if (token instanceof  EncryptedKey) {
0602:                            // for policy verification
0603:                            SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
0604:                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0605:                            skBinding.setKeyBinding(x509Binding);
0606:                            //TODO: ReferenceType and ValueType not set on X509Binding
0607:                            if (inferredKB == null) {
0608:                                wssContext.getSecurityContext().setInferredKB(
0609:                                        skBinding);
0610:                            } else if (PolicyTypeUtil
0611:                                    .derivedTokenKeyBinding(inferredKB)) {
0612:                                if (((DerivedTokenKeyBinding) inferredKB)
0613:                                        .getOriginalKeyBinding() == null)
0614:                                    ((DerivedTokenKeyBinding) inferredKB)
0615:                                            .setOriginalKeyBinding(skBinding);
0616:                            }
0617:                            //
0618:
0619:                            String algo = wssContext.getAlgorithmSuite()
0620:                                    .getEncryptionAlgorithm();
0621:                            returnKey = ((EncryptedKey) token).getKey(algo);
0622:                        } else if (token instanceof  DerivedKeyToken) {
0623:                            // for policy verification
0624:                            DerivedTokenKeyBinding dtkBinding = new DerivedTokenKeyBinding();
0625:                            dtkBinding
0626:                                    .setOriginalKeyBinding(((DerivedKeyToken) token)
0627:                                            .getInferredKB());
0628:                            if (inferredKB == null) {
0629:                                wssContext.getSecurityContext().setInferredKB(
0630:                                        dtkBinding);
0631:                            } else if (PolicyTypeUtil
0632:                                    .derivedTokenKeyBinding(inferredKB)) {
0633:                                //already set - do nothing
0634:                            } else {
0635:                                //throw new XWSSecurityException("A derived Key Token should be a top level key binding");
0636:                            }
0637:                            //
0638:
0639:                            returnKey = ((DerivedKeyToken) token).getKey();
0640:                        } else if (token instanceof  SecurityContextToken) {
0641:                            // for policy verification
0642:                            SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
0643:                            if (inferredKB == null) {
0644:                                wssContext.getSecurityContext().setInferredKB(
0645:                                        sctBinding);
0646:                            } else if (PolicyTypeUtil
0647:                                    .derivedTokenKeyBinding(inferredKB)) {
0648:                                ((DerivedTokenKeyBinding) inferredKB)
0649:                                        .setOriginalKeyBinding(sctBinding);
0650:                            }
0651:                            //wssContext.setExtraneousProperty(MessageConstants.INCOMING_SCT, token);
0652:                            returnKey = resolveSCT(wssContext,
0653:                                    ((SecurityContextToken) token).getSCId(),
0654:                                    purpose, true);
0655:                        }
0656:
0657:                    } else {
0658:                        logger.log(Level.SEVERE,
0659:                                "WSS1307.unsupported.directref.mechanism",
0660:                                new Object[] { valueType });
0661:                        throw SOAPUtil.newSOAPFaultException(
0662:                                MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
0663:                                "unsupported directreference ValueType "
0664:                                        + valueType, null);
0665:                    }
0666:                } catch (XWSSecurityException ex) {
0667:                    logger.log(Level.SEVERE,
0668:                            "WSS1377.error.in.resolving.keyinfo", ex);
0669:                    throw new KeySelectorException(ex);
0670:                } catch (URIReferenceException ex) {
0671:                    logger.log(Level.SEVERE,
0672:                            "WSS1377.error.in.resolving.keyinfo", ex);
0673:                    throw new KeySelectorException(ex);
0674:                }
0675:
0676:                return returnKey;
0677:            }
0678:
0679:            public static Key resolveKeyIdentifier(XMLCryptoContext xc,
0680:                    String valueType, String referenceValue, String strId,
0681:                    Purpose purpose) throws KeySelectorException {
0682:                JAXBFilterProcessingContext context = (JAXBFilterProcessingContext) xc
0683:                        .get(MessageConstants.WSS_PROCESSING_CONTEXT);
0684:                Key returnKey = null;
0685:                MLSPolicy inferredKB = context.getSecurityContext()
0686:                        .getInferredKB();
0687:                boolean isSymmetric = false;
0688:                try {
0689:                    if (MessageConstants.X509SubjectKeyIdentifier_NS
0690:                            .equals(valueType)
0691:                            || MessageConstants.X509v3SubjectKeyIdentifier_NS
0692:                                    .equals(valueType)) {
0693:                        //for policy verification
0694:                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0695:                        x509Binding
0696:                                .setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
0697:                        x509Binding
0698:                                .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0699:                        if (inferredKB == null) {
0700:                            context.getSecurityContext().setInferredKB(
0701:                                    x509Binding);
0702:                        } else if (PolicyTypeUtil
0703:                                .symmetricKeyBinding(inferredKB)) {
0704:                            ((SymmetricKeyBinding) inferredKB)
0705:                                    .setKeyBinding(x509Binding);
0706:                            isSymmetric = true;
0707:                        } else if (PolicyTypeUtil
0708:                                .derivedTokenKeyBinding(inferredKB)) {
0709:                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0710:                            if (dktBind.getOriginalKeyBinding() == null)
0711:                                ((DerivedTokenKeyBinding) inferredKB)
0712:                                        .setOriginalKeyBinding(x509Binding);
0713:                            else if (PolicyTypeUtil.symmetricKeyBinding(dktBind
0714:                                    .getOriginalKeyBinding())) {
0715:                                dktBind.getOriginalKeyBinding().setKeyBinding(
0716:                                        x509Binding);
0717:                                isSymmetric = true;
0718:                            }
0719:                        }
0720:                        // get the key
0721:                        if (purpose == Purpose.VERIFY
0722:                                || purpose == Purpose.ENCRYPT) {
0723:                            byte[] keyIdBytes = XMLUtil
0724:                                    .getDecodedBase64EncodedData(referenceValue);
0725:                            context.setExtraneousProperty(
0726:                                    MessageConstants.REQUESTER_KEYID,
0727:                                    new String(keyIdBytes));
0728:                            //returnKey = context.getSecurityEnvironment().getPublicKey(
0729:                            //      context.getExtraneousProperties(),keyIdBytes);
0730:                            X509Certificate cert = context
0731:                                    .getSecurityEnvironment().getCertificate(
0732:                                            context.getExtraneousProperties(),
0733:                                            keyIdBytes);
0734:                            if (strId != null) {
0735:                                byte[] encodedCert = cert.getEncoded();
0736:                                context.getElementCache().put(
0737:                                        strId,
0738:                                        new OctectStreamData(new String(
0739:                                                encodedCert)));
0740:                            }
0741:                            if (!isSymmetric) {
0742:                                context.getSecurityEnvironment()
0743:                                        .updateOtherPartySubject(
0744:                                                DefaultSecurityEnvironmentImpl
0745:                                                        .getSubject(context),
0746:                                                cert);
0747:                            }
0748:                            returnKey = cert.getPublicKey();
0749:                        } else if (purpose == Purpose.SIGN
0750:                                || purpose == Purpose.DECRYPT) {
0751:                            returnKey = context
0752:                                    .getSecurityEnvironment()
0753:                                    .getPrivateKey(
0754:                                            context.getExtraneousProperties(),
0755:                                            XMLUtil
0756:                                                    .getDecodedBase64EncodedData(referenceValue));
0757:                        }
0758:                    } else if (MessageConstants.ThumbPrintIdentifier_NS
0759:                            .equals(valueType)) {
0760:                        //for policy verification
0761:                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0762:                        x509Binding
0763:                                .setValueType(MessageConstants.ThumbPrintIdentifier_NS);
0764:                        x509Binding
0765:                                .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0766:                        if (inferredKB == null) {
0767:                            context.getSecurityContext().setInferredKB(
0768:                                    x509Binding);
0769:                        } else if (PolicyTypeUtil
0770:                                .symmetricKeyBinding(inferredKB)) {
0771:                            ((SymmetricKeyBinding) inferredKB)
0772:                                    .setKeyBinding(x509Binding);
0773:                            isSymmetric = true;
0774:                        } else if (PolicyTypeUtil
0775:                                .derivedTokenKeyBinding(inferredKB)) {
0776:                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding) inferredKB;
0777:                            if (dktBind.getOriginalKeyBinding() == null)
0778:                                ((DerivedTokenKeyBinding) inferredKB)
0779:                                        .setOriginalKeyBinding(x509Binding);
0780:                            else if (PolicyTypeUtil.symmetricKeyBinding(dktBind
0781:                                    .getOriginalKeyBinding())) {
0782:                                dktBind.getOriginalKeyBinding().setKeyBinding(
0783:                                        x509Binding);
0784:                                isSymmetric = true;
0785:                            }
0786:                        }
0787:                        // get the key
0788:                        if (purpose == Purpose.VERIFY
0789:                                || purpose == Purpose.ENCRYPT) {
0790:                            byte[] keyIdBytes = XMLUtil
0791:                                    .getDecodedBase64EncodedData(referenceValue);
0792:                            context.setExtraneousProperty(
0793:                                    MessageConstants.REQUESTER_KEYID,
0794:                                    new String(keyIdBytes));
0795:
0796:                            X509Certificate cert = context
0797:                                    .getSecurityEnvironment().getCertificate(
0798:                                            context.getExtraneousProperties(),
0799:                                            keyIdBytes,
0800:                                            MessageConstants.THUMB_PRINT_TYPE);
0801:                            if (!isSymmetric) {
0802:                                context.getSecurityEnvironment()
0803:                                        .updateOtherPartySubject(
0804:                                                DefaultSecurityEnvironmentImpl
0805:                                                        .getSubject(context),
0806:                                                cert);
0807:                            }
0808:                            returnKey = cert.getPublicKey();
0809:
0810:                            if (strId != null) {
0811:                                byte[] encodedCert = cert.getEncoded();
0812:                                context.getElementCache().put(
0813:                                        strId,
0814:                                        new OctectStreamData(new String(
0815:                                                encodedCert)));
0816:                            }
0817:
0818:                        } else if (purpose == Purpose.SIGN
0819:                                || purpose == Purpose.DECRYPT) {
0820:                            returnKey = context
0821:                                    .getSecurityEnvironment()
0822:                                    .getPrivateKey(
0823:                                            context.getExtraneousProperties(),
0824:                                            XMLUtil
0825:                                                    .getDecodedBase64EncodedData(referenceValue),
0826:                                            MessageConstants.THUMB_PRINT_TYPE);
0827:                        }
0828:                    } else if (MessageConstants.EncryptedKeyIdentifier_NS
0829:                            .equals(valueType)) {
0830:                        //for policy verification
0831:                        SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
0832:                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
0833:                        x509Binding
0834:                                .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
0835:                        skBinding.setKeyBinding(x509Binding);
0836:                        //TODO: ValueType not set on X509Binding
0837:                        if (inferredKB == null) {
0838:                            context.getSecurityContext().setInferredKB(
0839:                                    skBinding);
0840:                        } else if (PolicyTypeUtil
0841:                                .derivedTokenKeyBinding(inferredKB)) {
0842:                            if (((DerivedTokenKeyBinding) inferredKB)
0843:                                    .getOriginalKeyBinding() == null)
0844:                                ((DerivedTokenKeyBinding) inferredKB)
0845:                                        .setOriginalKeyBinding(skBinding);
0846:                        }
0847:                        // get the key
0848:                        String ekSha1RefValue = (String) context
0849:                                .getExtraneousProperty("EncryptedKeySHA1");
0850:                        Key secretKey = (Key) context
0851:                                .getExtraneousProperty("SecretKey");
0852:                        String keyRefValue = referenceValue;
0853:                        if (ekSha1RefValue != null && secretKey != null) {
0854:                            if (ekSha1RefValue.equals(keyRefValue))
0855:                                returnKey = secretKey;
0856:                        } else {
0857:                            String message = "EncryptedKeySHA1 reference not correct";
0858:                            logger
0859:                                    .log(
0860:                                            Level.SEVERE,
0861:                                            "WSS1306:unsupported.KeyIdentifier.Reference.Type.encountered",
0862:                                            new Object[] { message });
0863:                            throw new KeySelectorException(message);
0864:                        }
0865:                    } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE
0866:                            .equals(valueType)
0867:                            || MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE
0868:                                    .equals(valueType)) {
0869:                        //for policy verification
0870:                        IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
0871:                        if (inferredKB == null) {
0872:                            if (context.hasIssuedToken()) {
0873:                                context.getSecurityContext().setInferredKB(
0874:                                        itkBinding);
0875:                            } else {
0876:                                context
0877:                                        .getSecurityContext()
0878:                                        .setInferredKB(
0879:                                                new AuthenticationTokenPolicy.SAMLAssertionBinding());
0880:                            }
0881:                        } else if (PolicyTypeUtil
0882:                                .derivedTokenKeyBinding(inferredKB)) {
0883:                            if (((DerivedTokenKeyBinding) inferredKB)
0884:                                    .getOriginalKeyBinding() == null)
0885:                                ((DerivedTokenKeyBinding) inferredKB)
0886:                                        .setOriginalKeyBinding(itkBinding);
0887:
0888:                        }
0889:                        // TODO:
0890:                        SecurityHeaderElement she = resolveToken(
0891:                                referenceValue, xc);
0892:                        if (she != null && she instanceof  SAMLAssertion) {
0893:                            SAMLAssertion samlAssertion = (SAMLAssertion) she;
0894:                            returnKey = samlAssertion.getKey();
0895:                            if (strId != null && strId.length() > 0) {
0896:                                Data data = new SSEData(
0897:                                        (SecurityElement) samlAssertion, false,
0898:                                        context.getNamespaceContext());
0899:                                context.getElementCache().put(strId, data);
0900:                            }
0901:                        } else {
0902:                            HashMap sentSamlKeys = (HashMap) context
0903:                                    .getExtraneousProperty(MessageConstants.STORED_SAML_KEYS);
0904:                            if (sentSamlKeys != null) {
0905:                                // for policy verification
0906:                                context.getSecurityContext()
0907:                                        .setIsSAMLKeyBinding(true);
0908:                                returnKey = (Key) sentSamlKeys
0909:                                        .get(referenceValue);
0910:                            }
0911:                        }
0912:
0913:                        if (context.hasIssuedToken()) {
0914:                            SecurityTokenReference str = new SecurityTokenReference(
0915:                                    context.getSOAPVersion());
0916:                            com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier ki = new com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier(
0917:                                    context.getSOAPVersion());
0918:                            ki.setValueType(valueType);
0919:                            ki.setReferenceValue(referenceValue);
0920:                            str.setReference(ki);
0921:                            SecurityUtil.initInferredIssuedTokenContext(
0922:                                    context, str, returnKey);
0923:                        }
0924:                    } else {
0925:                        // assume SAML AssertionID without ValueType on KeyIdentifier
0926:                        // now assume its an X509Token
0927:                        returnKey = null;
0928:                    }
0929:                } catch (XWSSecurityException ex) {
0930:                    logger.log(Level.SEVERE,
0931:                            "WSS1377.error.in.resolving.keyinfo", ex);
0932:                    throw new KeySelectorException(ex);
0933:                } catch (URIReferenceException ex) {
0934:                    logger.log(Level.SEVERE,
0935:                            "WSS1377.error.in.resolving.keyinfo", ex);
0936:                    throw new KeySelectorException(ex);
0937:                } catch (CertificateEncodingException ex) {
0938:                    logger.log(Level.SEVERE,
0939:                            "WSS1377.error.in.resolving.keyinfo", ex);
0940:                    throw new KeySelectorException(ex);
0941:                }
0942:                return returnKey;
0943:
0944:            }
0945:
0946:            //@@@FIXME: this should also work for key types other than DSA/RSA
0947:            /**
0948:             *
0949:             * @param algURI
0950:             * @param algName
0951:             * @return
0952:             */
0953:            private static boolean algEquals(String algURI, String algName) {
0954:                if (algName.equalsIgnoreCase("DSA")
0955:                        && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
0956:                    return true;
0957:                } else if (algName.equalsIgnoreCase("RSA")
0958:                        && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
0959:                    return true;
0960:                } else {
0961:                    return false;
0962:                }
0963:            }
0964:
0965:            private static Key resolveX509Token(
0966:                    JAXBFilterProcessingContext context,
0967:                    BinarySecurityToken token, Purpose purpose,
0968:                    boolean isSymmetric) throws XWSSecurityException {
0969:                X509Certificate cert = token.getCertificate();
0970:                if (cert == null)
0971:                    cert = SOAPUtil.getCertificateFromToken(token);
0972:                if (purpose == Purpose.VERIFY) {
0973:                    if (!isSymmetric) {
0974:                        context.getSecurityEnvironment()
0975:                                .updateOtherPartySubject(
0976:                                        DefaultSecurityEnvironmentImpl
0977:                                                .getSubject(context), cert);
0978:                    }
0979:                    return cert.getPublicKey();
0980:                } else if (purpose == Purpose.SIGN
0981:                        || purpose == Purpose.DECRYPT) {
0982:                    return context.getSecurityEnvironment().getPrivateKey(
0983:                            context.getExtraneousProperties(), cert);
0984:                }
0985:                return null;
0986:            }
0987:
0988:            private static Key resolveX509Data(
0989:                    JAXBFilterProcessingContext context, X509Data x509Data,
0990:                    Purpose purpose) throws KeySelectorException {
0991:
0992:                X509Certificate cert = null;
0993:                try {
0994:                    List data = x509Data.getContent();
0995:                    Iterator iterator = data.iterator();
0996:                    while (iterator.hasNext()) {//will break for in single loop;
0997:                        Object content = iterator.next();
0998:                        if (content instanceof  X509Certificate) {
0999:                            cert = (X509Certificate) content;
1000:                        } else if (content instanceof  byte[]) {
1001:                            byte[] ski = (byte[]) content;
1002:                            if (purpose == Purpose.VERIFY) {
1003:                                //return context.getSecurityEnvironment().getPublicKey(
1004:                                //      context.getExtraneousProperties(),ski);
1005:                                cert = context
1006:                                        .getSecurityEnvironment()
1007:                                        .getCertificate(
1008:                                                context
1009:                                                        .getExtraneousProperties(),
1010:                                                ski);
1011:                                context.getSecurityEnvironment()
1012:                                        .updateOtherPartySubject(
1013:                                                DefaultSecurityEnvironmentImpl
1014:                                                        .getSubject(context),
1015:                                                cert);
1016:                                return cert.getPublicKey();
1017:                            } else if (purpose == Purpose.SIGN) {
1018:                                return context
1019:                                        .getSecurityEnvironment()
1020:                                        .getPrivateKey(
1021:                                                context
1022:                                                        .getExtraneousProperties(),
1023:                                                ski);
1024:                            }
1025:                        } else if (content instanceof  String) {
1026:                            logger.log(Level.SEVERE,
1027:                                    "WSS1312.unsupported.keyinfo");
1028:                            throw new KeySelectorException(
1029:                                    "X509SubjectName child element of X509Data is not yet supported by our implementation");
1030:                        } else if (content instanceof  X509IssuerSerial) {
1031:                            X509IssuerSerial xis = (X509IssuerSerial) content;
1032:                            if (purpose == Purpose.VERIFY) {
1033:                                //return context.getSecurityEnvironment().getPublicKey(
1034:                                //        context.getExtraneousProperties(), xis.getSerialNumber(), xis.getIssuerName());
1035:                                cert = context
1036:                                        .getSecurityEnvironment()
1037:                                        .getCertificate(
1038:                                                context
1039:                                                        .getExtraneousProperties(),
1040:                                                xis.getSerialNumber(),
1041:                                                xis.getIssuerName());
1042:                                context.getSecurityEnvironment()
1043:                                        .updateOtherPartySubject(
1044:                                                DefaultSecurityEnvironmentImpl
1045:                                                        .getSubject(context),
1046:                                                cert);
1047:                                return cert.getPublicKey();
1048:                            } else if (purpose == Purpose.SIGN) {
1049:                                return context
1050:                                        .getSecurityEnvironment()
1051:                                        .getPrivateKey(
1052:                                                context
1053:                                                        .getExtraneousProperties(),
1054:                                                xis.getSerialNumber(),
1055:                                                xis.getIssuerName());
1056:                            }
1057:
1058:                        } else {
1059:                            logger.log(Level.SEVERE,
1060:                                    "WSS1312.unsupported.keyinfo");
1061:                            throw new KeySelectorException(
1062:                                    "Unsupported child element of X509Data encountered");
1063:                        }
1064:
1065:                        if (purpose == Purpose.VERIFY) {
1066:                            context.getSecurityEnvironment()
1067:                                    .updateOtherPartySubject(
1068:                                            DefaultSecurityEnvironmentImpl
1069:                                                    .getSubject(context), cert);
1070:                            return cert.getPublicKey();
1071:                        } else if (purpose == Purpose.SIGN) {
1072:                            return context.getSecurityEnvironment()
1073:                                    .getPrivateKey(
1074:                                            context.getExtraneousProperties(),
1075:                                            cert);
1076:                        }
1077:                    }
1078:                } catch (Exception e) {
1079:                    logger.log(Level.SEVERE, "WSS1314.illegal.x509.data", e
1080:                            .getMessage());
1081:                    throw new KeySelectorException(e);
1082:                }
1083:                return null;//Should never come here.
1084:            }
1085:
1086:            protected static SecurityHeaderElement resolveToken(
1087:                    final String uri, XMLCryptoContext context)
1088:                    throws URIReferenceException, XWSSecurityException {
1089:                URIDereferencer resolver = context.getURIDereferencer();
1090:
1091:                URIReference uriRef = new URIReference() {
1092:                    public String getURI() {
1093:                        return uri;
1094:                    }
1095:
1096:                    public String getType() {
1097:                        return null;
1098:                    }
1099:                };
1100:
1101:                JAXBFilterProcessingContext wssContext = (JAXBFilterProcessingContext) context
1102:                        .get(MessageConstants.WSS_PROCESSING_CONTEXT);
1103:
1104:                try {
1105:                    StreamWriterData data = (StreamWriterData) resolver
1106:                            .dereference(uriRef, context);
1107:                    //JAXBElement element = data.getJAXBElement();
1108:                    if (data == null) {
1109:                        return null;
1110:                    }
1111:                    Object derefData = data.getDereferencedObject();
1112:                    SecurityHeaderElement she = null;
1113:                    if (derefData instanceof  SecurityHeaderElement) {
1114:                        she = (SecurityHeaderElement) derefData;
1115:                    }
1116:
1117:                    if (she == null) {
1118:                        logger.log(Level.SEVERE,
1119:                                "WSS1304.FC_SECURITY_TOKEN_UNAVAILABLE");
1120:                        throw SOAPUtil
1121:                                .newSOAPFaultException(
1122:                                        MessageConstants.WSSE_SECURITY_TOKEN_UNAVAILABLE,
1123:                                        "Referenced Security Token could not be retrieved",
1124:                                        null);
1125:                    }
1126:
1127:                    if (MessageConstants.WSSE_BINARY_SECURITY_TOKEN_LNAME
1128:                            .equals(she.getLocalPart())) {
1129:                        BinarySecurityToken token = (BinarySecurityToken) she;
1130:                        X509Certificate cert = null;
1131:                        //                try{
1132:                        cert = token.getCertificate();
1133:                        //SOAPUtil.getCertificateFromToken(token);
1134:                        //                } catch(XWSSecurityException xwe){
1135:                        //                    throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1136:                        //                            "A Invalid security token was provided ", xwe);
1137:                        //                }
1138:
1139:                        if (!wssContext.getSecurityEnvironment()
1140:                                .validateCertificate(cert)) {
1141:                            throw SOAPUtil
1142:                                    .newSOAPFaultException(
1143:                                            MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1144:                                            "Certificate validation failed",
1145:                                            null);
1146:                        }
1147:                        return token;
1148:                    } else if (MessageConstants.ENCRYPTEDKEY_LNAME.equals(she
1149:                            .getLocalPart())) {
1150:                        return (EncryptedKey) she;
1151:                    } else if (MessageConstants.SECURITY_CONTEXT_TOKEN_LNAME
1152:                            .equals(she.getLocalPart())) {
1153:                        return (SecurityContextToken) she;
1154:                    } else if (MessageConstants.DERIVEDKEY_TOKEN_LNAME
1155:                            .equals(she.getLocalPart())) {
1156:                        return (DerivedKeyToken) she;
1157:                    } else if (MessageConstants.SAML_ASSERTION_LNAME.equals(she
1158:                            .getLocalPart())) {
1159:                        //TODO : update other party subject
1160:                        return she;
1161:                    }
1162:                } catch (URIReferenceException ure) {
1163:                    logger.log(Level.SEVERE,
1164:                            "WSS1304.FC_SECURITY_TOKEN_UNAVAILABLE", ure);
1165:                    throw SOAPUtil.newSOAPFaultException(
1166:                            MessageConstants.WSSE_SECURITY_TOKEN_UNAVAILABLE,
1167:                            "Referenced Security Token could not be retrieved",
1168:                            ure);
1169:                }
1170:
1171:                if (logger.isLoggable(Level.SEVERE)) {
1172:                    logger.log(Level.SEVERE,
1173:                            "WSS1305.UnSupported.security.token");
1174:                }
1175:                throw SOAPUtil.newSOAPFaultException(
1176:                        MessageConstants.WSSE_UNSUPPORTED_SECURITY_TOKEN,
1177:                        "A Unsupported token was provided ", null);
1178:            }
1179:
1180:            private static boolean isSecurityTokenReference(
1181:                    JAXBElement reference) {
1182:                String local = reference.getName().getLocalPart();
1183:                String uri = reference.getName().getNamespaceURI();
1184:                if (MessageConstants.WSSE_SECURITY_TOKEN_REFERENCE_LNAME
1185:                        .equals(local)
1186:                        && MessageConstants.WSSE_NS.equals(uri))
1187:                    return true;
1188:                return false;
1189:            }
1190:
1191:            private static SessionManager sessionManager = SessionManager
1192:                    .getSessionManager();
1193:
1194:            private static Key resolveSCT(
1195:                    JAXBFilterProcessingContext wssContext, String scId,
1196:                    KeySelector.Purpose purpose, boolean checkSession)
1197:                    throws XWSSecurityException {
1198:
1199:                IssuedTokenContext ctx = null;
1200:
1201:                Enumeration elements = wssContext.getIssuedTokenContextMap()
1202:                        .elements();
1203:                while (elements.hasMoreElements()) {
1204:                    IssuedTokenContext ictx = (IssuedTokenContext) elements
1205:                            .nextElement();
1206:                    Object tok = ictx.getSecurityToken();
1207:                    String ctxid = null;
1208:
1209:                    if (tok instanceof  com.sun.xml.ws.security.SecurityContextToken) {
1210:                        ctxid = ((com.sun.xml.ws.security.SecurityContextToken) tok)
1211:                                .getIdentifier().toString();
1212:                        if (ctxid.equals(scId)) {
1213:                            ctx = ictx;
1214:                            break;
1215:                        }
1216:                    }
1217:                }
1218:
1219:                // MK: Recreate the IssuedTokenContext based on the information
1220:                // present in the SCTInfo in the session.
1221:
1222:                if (checkSession && ctx == null) {
1223:                    // check if session has the context.
1224:                    Session session = sessionManager.getSession(scId);
1225:
1226:                    if (session != null) {
1227:                        // recreate context info based on data stored in the session
1228:                        SecurityContextTokenInfo sctInfo = session
1229:                                .getSecurityInfo();
1230:                        ctx = sctInfo.getIssuedTokenContext();
1231:                        // add it to the contextMap; recreating the contextMap
1232:                        // after possible crash
1233:                        wssContext.getIssuedTokenContextMap().put(scId, ctx);
1234:
1235:                    } else {
1236:                        throw new XWSSecurityException(
1237:                                "Could not locate SecureConversation session for Id:"
1238:                                        + scId);
1239:                    }
1240:                }
1241:
1242:                if (ctx == null) {
1243:                    return null;
1244:                }
1245:
1246:                //update otherparty subject with bootstrap credentials.
1247:                Subject subj = ctx.getRequestorSubject();
1248:                if (subj != null) {
1249:                    // subj will be null if this is the client side execution
1250:                    if (wssContext
1251:                            .getExtraneousProperty(MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ) == null) {
1252:                        //do it only once
1253:                        wssContext.getSecurityEnvironment()
1254:                                .updateOtherPartySubject(
1255:                                        SecurityUtil.getSubject(wssContext
1256:                                                .getExtraneousProperties()),
1257:                                        subj);
1258:                        wssContext.getExtraneousProperties().put(
1259:                                MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ,
1260:                                "true");
1261:                    }
1262:                }
1263:
1264:                byte[] proofKey = ctx.getProofKey();
1265:                wssContext.setExtraneousProperty(MessageConstants.INCOMING_SCT,
1266:                        ctx.getSecurityToken());
1267:
1268:                if (proofKey == null) {
1269:                    throw new XWSSecurityException(
1270:                            "Could not locate SecureConversation session for Id:"
1271:                                    + scId);
1272:                }
1273:
1274:                String algo = "AES"; // hardcoding for now
1275:                if (wssContext.getAlgorithmSuite() != null) {
1276:                    algo = SecurityUtil.getSecretKeyAlgorithm(wssContext
1277:                            .getAlgorithmSuite().getEncryptionAlgorithm());
1278:                }
1279:                SecretKeySpec key = new SecretKeySpec(proofKey, algo);
1280:                return key;
1281:            }
1282:
1283:        }
w___w___w_.j_a_va2s__.c__o__m | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.