Source Code Cross Referenced for DefaultCallbackHandler.java in  » 6.0-JDK-Modules-com.sun » xws-security » com » sun » xml » wss » impl » misc » 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.misc 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * $Id: DefaultCallbackHandler.java,v 1.27 2007/08/01 11:05:49 ashutoshshahi Exp $
0003:         *
0004:         */
0005:        /*
0006:         * The contents of this file are subject to the terms
0007:         * of the Common Development and Distribution License
0008:         * (the License).  You may not use this file except in
0009:         * compliance with the License.
0010:         *
0011:         * You can obtain a copy of the license at
0012:         * https://glassfish.dev.java.net/public/CDDLv1.0.html.
0013:         * See the License for the specific language governing
0014:         * permissions and limitations under the License.
0015:         *
0016:         * When distributing Covered Code, include this CDDL
0017:         * Header Notice in each file and include the License file
0018:         * at https://glassfish.dev.java.net/public/CDDLv1.0.html.
0019:         * If applicable, add the following below the CDDL Header,
0020:         * with the fields enclosed by brackets [] replaced by
0021:         * you own identifying information:
0022:         * "Portions Copyrighted [year] [name of copyright owner]"
0023:         *
0024:         * Copyright 2006 Sun Microsystems Inc. All Rights Reserved
0025:         */
0026:
0027:        package com.sun.xml.wss.impl.misc;
0028:
0029:        import com.sun.xml.wss.AliasSelector;
0030:        import com.sun.xml.wss.impl.callback.CertStoreCallback;
0031:        import com.sun.xml.wss.logging.LogDomainConstants;
0032:        import java.io.IOException;
0033:        import java.io.InputStream;
0034:        import java.io.FileInputStream;
0035:        import java.lang.reflect.Constructor;
0036:        import java.lang.reflect.InvocationTargetException;
0037:
0038:        import java.net.URI;
0039:        import java.security.KeyStoreException;
0040:        import java.security.cert.CertSelector;
0041:        import java.security.cert.CertStore;
0042:        import java.security.cert.CertStoreException;
0043:        import java.util.Collection;
0044:        import java.util.Enumeration;
0045:        import java.util.Map;
0046:        import java.util.Properties;
0047:        import java.util.Arrays;
0048:        import java.util.Date;
0049:        import java.util.Calendar;
0050:        import java.util.GregorianCalendar;
0051:        import java.text.SimpleDateFormat;
0052:        import java.math.BigInteger;
0053:
0054:        import java.security.KeyStore;
0055:        import java.security.PrivateKey;
0056:        import java.security.PublicKey;
0057:        import java.security.cert.CertPathBuilder;
0058:        import java.security.cert.Certificate;
0059:        import java.security.cert.CertificateExpiredException;
0060:        import java.security.cert.CertificateNotYetValidException;
0061:        import java.security.cert.PKIXBuilderParameters;
0062:        import java.security.cert.PKIXCertPathBuilderResult;
0063:        import java.security.cert.X509CertSelector;
0064:        import java.security.cert.X509Certificate;
0065:        import java.util.logging.Level;
0066:        import java.util.logging.Logger;
0067:        import javax.security.auth.callback.Callback;
0068:        import javax.security.auth.callback.CallbackHandler;
0069:        import javax.security.auth.callback.UnsupportedCallbackException;
0070:
0071:        import com.sun.xml.wss.impl.callback.CertificateValidationCallback;
0072:        import com.sun.xml.wss.impl.callback.DecryptionKeyCallback;
0073:        import com.sun.xml.wss.impl.callback.EncryptionKeyCallback;
0074:        import com.sun.xml.wss.impl.callback.PasswordCallback;
0075:        import com.sun.xml.wss.impl.callback.PasswordValidationCallback;
0076:        import com.sun.xml.wss.impl.callback.SignatureKeyCallback;
0077:        import com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback;
0078:        import com.sun.xml.wss.impl.callback.UsernameCallback;
0079:        import com.sun.xml.wss.impl.callback.TimestampValidationCallback;
0080:        import com.sun.xml.wss.impl.callback.SAMLAssertionValidator;
0081:        import com.sun.xml.wss.impl.callback.DynamicPolicyCallback;
0082:
0083:        import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
0084:
0085:        import java.security.MessageDigest;
0086:        import java.security.NoSuchAlgorithmException;
0087:        import java.security.cert.CertificateEncodingException;
0088:
0089:        import com.sun.xml.ws.security.trust.WSTrustConstants;
0090:        import com.sun.xml.wss.RealmAuthenticationAdapter;
0091:
0092:        import com.sun.xml.wss.XWSSecurityException;
0093:        import com.sun.xml.wss.impl.MessageConstants;
0094:        import com.sun.xml.wss.impl.callback.SAMLCallback;
0095:        import com.sun.xml.wss.impl.policy.SecurityPolicy;
0096:        import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0097:        import com.sun.xml.wss.impl.policy.mls.PrivateKeyBinding;
0098:        import java.security.AccessController;
0099:        import java.security.PrivilegedAction;
0100:        import java.util.Iterator;
0101:        import java.util.Set;
0102:        import javax.security.auth.Subject;
0103:        import javax.xml.ws.BindingProvider;
0104:        import org.w3c.dom.Element;
0105:
0106:        /**
0107:         * A sample implementation of a CallbackHandler.
0108:         */
0109:        public class DefaultCallbackHandler implements  CallbackHandler {
0110:
0111:            public static final String KEYSTORE_URL = "keystore.url";
0112:            public static final String KEYSTORE_TYPE = "keystore.type";
0113:            public static final String KEYSTORE_PASSWORD = "keystore.password";
0114:            public static final String KEY_PASSWORD = "key.password";
0115:            public static final String MY_ALIAS = "my.alias";
0116:            public static final String MY_USERNAME = "my.username";
0117:            public static final String MY_PASSWORD = "my.password";
0118:
0119:            public static final String TRUSTSTORE_URL = "truststore.url";
0120:            public static final String TRUSTSTORE_TYPE = "truststore.type";
0121:            public static final String TRUSTSTORE_PASSWORD = "truststore.password";
0122:            public static final String PEER_ENTITY_ALIAS = "peerentity.alias";
0123:            public static final String STS_ALIAS = "sts.alias";
0124:            public static final String SERVICE_ALIAS = "service.alias";
0125:
0126:            public static final String USERNAME_CBH = "username.callback.handler";
0127:            public static final String PASSWORD_CBH = "password.callback.handler";
0128:            public static final String SAML_CBH = "saml.callback.handler";
0129:
0130:            public static final String USERNAME_VALIDATOR = "username.validator";
0131:            public static final String SAML_VALIDATOR = "saml.validator";
0132:            public static final String TIMESTAMP_VALIDATOR = "timestamp.validator";
0133:            public static final String CERTIFICATE_VALIDATOR = "certificate.validator";
0134:
0135:            public static final String MAX_CLOCK_SKEW_PROPERTY = "max.clock.skew";
0136:            public static final String MAX_NONCE_AGE_PROPERTY = "max.nonce.age";
0137:            public static final String TIMESTAMP_FRESHNESS_LIMIT_PROPERTY = "timestamp.freshness.limit";
0138:            public static final String REVOCATION_ENABLED = "revocation.enabled";
0139:
0140:            public static final String CERTSTORE_CBH = "certstore.cbh";
0141:            public static final String CERTSTORE_CERTSELECTOR = "certstore.certselector";
0142:            public static final String CERTSTORE_CRLSELECTOR = "certstore.crlselector";
0143:            //this one is actually an AliasSelector for Keystore
0144:            public static final String KEYSTORE_CERTSELECTOR = "keystore.certselector";
0145:            public static final String TRUSTSTORE_CERTSELECTOR = "truststore.certselector";
0146:            //A CallbackHandler for Java Message Authentication SPI for Containers
0147:            public static final String JMAC_CALLBACK_HANDLER = "jmac.callbackhandler";
0148:
0149:            private String keyStoreURL;
0150:            private String keyStorePassword;
0151:            private String keyStoreType;
0152:            private String myAlias;
0153:            private String keyPwd;
0154:            private char[] keyPassword = null;
0155:
0156:            private String trustStoreURL;
0157:            private String trustStorePassword;
0158:            private String trustStoreType;
0159:            private String peerEntityAlias;
0160:            //private String stsAlias;
0161:            //private String serviceAlias;
0162:
0163:            private String certStoreCBHClassName;
0164:            private String certSelectorClassName;
0165:            private String crlSelectorClassName;
0166:
0167:            private String keystoreCertSelectorClassName;
0168:            private String truststoreCertSelectorClassName;
0169:
0170:            private String myUsername;
0171:            private String myPassword;
0172:
0173:            private KeyStore keyStore;
0174:            private KeyStore trustStore;
0175:
0176:            private Class usernameCbHandler;
0177:            private Class passwordCbHandler;
0178:            private Class samlCbHandler;
0179:
0180:            private Class certstoreCbHandler;
0181:            private Class certSelectorClass;
0182:            private Class crlSelectorClass;
0183:
0184:            private Class usernameValidator;
0185:            private Class timestampValidator;
0186:            private Class samlValidator;
0187:            private Class certificateValidator;
0188:
0189:            //private String home = null;
0190:
0191:            protected long maxClockSkewG;
0192:            protected long timestampFreshnessLimitG;
0193:            protected long maxNonceAge;
0194:
0195:            protected String revocationEnabledAttr;
0196:            protected boolean revocationEnabled = false;
0197:
0198:            protected String mcs = null;
0199:            protected String tfl = null;
0200:            protected String mna = null;
0201:
0202:            private static Logger log = Logger.getLogger(
0203:                    LogDomainConstants.IMPL_MISC_DOMAIN,
0204:                    LogDomainConstants.IMPL_MISC_DOMAIN_BUNDLE);
0205:
0206:            private static final String fileSeparator = System
0207:                    .getProperty("file.separator");
0208:            private static final UnsupportedCallbackException unsupported = new UnsupportedCallbackException(
0209:                    null, "Unsupported Callback Type Encountered");
0210:            private static final URI ISSUE_REQUEST_URI = URI
0211:                    .create(WSTrustConstants.REQUEST_SECURITY_TOKEN_ISSUE_ACTION);
0212:
0213:            private CallbackHandler usernameHandler;
0214:            private CallbackHandler passwordHandler;
0215:            private CallbackHandler samlHandler;
0216:            private CallbackHandler certstoreHandler;
0217:
0218:            private PasswordValidationCallback.PasswordValidator pwValidator;
0219:            private TimestampValidationCallback.TimestampValidator tsValidator;
0220:            private CertificateValidationCallback.CertificateValidator certValidator;
0221:            private SAMLAssertionValidator sValidator;
0222:
0223:            private CertificateValidationCallback.CertificateValidator defaultCertValidator;
0224:            private TimestampValidationCallback.TimestampValidator defaultTSValidator;
0225:            //private PasswordValidationCallback.PasswordValidator defaultPWValidator;
0226:            private RealmAuthenticationAdapter usernameAuthenticator = null;
0227:            private RealmAuthenticationAdapter defRealmAuthenticator = null;
0228:
0229:            private CertStore certStore = null;
0230:
0231:            private Class keystoreCertSelectorClass;
0232:            private Class truststoreCertSelectorClass;
0233:
0234:            public DefaultCallbackHandler(String clientOrServer,
0235:                    Properties assertions) throws XWSSecurityException {
0236:
0237:                Properties properties = null;
0238:                if (assertions != null && !assertions.isEmpty()) {
0239:                    properties = assertions;
0240:                } else {
0241:                    //fallback option
0242:                    properties = new Properties();
0243:                    String resource = clientOrServer
0244:                            + "-security-env.properties";
0245:                    InputStream in = Thread.currentThread()
0246:                            .getContextClassLoader().getResourceAsStream(
0247:                                    resource);
0248:                    if (in != null) {
0249:                        try {
0250:                            properties.load(in);
0251:                        } catch (IOException ex) {
0252:                            throw new XWSSecurityException(ex);
0253:                        }
0254:                    } else {
0255:                        //throw new XWSSecurityException("Resource " + resource + " could not be located in classpath");
0256:                    }
0257:                }
0258:
0259:                this .keyStoreURL = properties.getProperty(KEYSTORE_URL);
0260:                this .keyStoreURL = resolveHome(this .keyStoreURL);
0261:                this .keyStoreType = properties.getProperty(KEYSTORE_TYPE);
0262:                this .keyStorePassword = properties
0263:                        .getProperty(KEYSTORE_PASSWORD);
0264:                this .keyPwd = properties.getProperty(KEY_PASSWORD);
0265:                this .myAlias = properties.getProperty(MY_ALIAS);
0266:                this .myUsername = properties.getProperty(MY_USERNAME);
0267:                this .myPassword = properties.getProperty(MY_PASSWORD);
0268:
0269:                this .trustStoreURL = properties.getProperty(TRUSTSTORE_URL);
0270:                this .trustStoreURL = resolveHome(this .trustStoreURL);
0271:                this .keyStoreType = properties.getProperty(KEYSTORE_TYPE);
0272:                this .trustStoreType = properties.getProperty(TRUSTSTORE_TYPE);
0273:                this .trustStorePassword = properties
0274:                        .getProperty(TRUSTSTORE_PASSWORD);
0275:                this .peerEntityAlias = properties
0276:                        .getProperty(PEER_ENTITY_ALIAS);
0277:                //this.stsAlias =  properties.getProperty(STS_ALIAS);
0278:                //this.serviceAlias = properties.getProperty(SERVICE_ALIAS);
0279:
0280:                this .certStoreCBHClassName = properties
0281:                        .getProperty(this .CERTSTORE_CBH);
0282:                this .certSelectorClassName = properties
0283:                        .getProperty(this .CERTSTORE_CERTSELECTOR);
0284:                this .crlSelectorClassName = properties
0285:                        .getProperty(this .CERTSTORE_CRLSELECTOR);
0286:
0287:                this .keystoreCertSelectorClassName = properties
0288:                        .getProperty(this .KEYSTORE_CERTSELECTOR);
0289:                this .truststoreCertSelectorClassName = properties
0290:                        .getProperty(this .TRUSTSTORE_CERTSELECTOR);
0291:
0292:                String uCBH = properties.getProperty(USERNAME_CBH);
0293:                String pCBH = properties.getProperty(PASSWORD_CBH);
0294:                String sCBH = properties.getProperty(SAML_CBH);
0295:
0296:                String uV = properties.getProperty(USERNAME_VALIDATOR);
0297:                String sV = properties.getProperty(SAML_VALIDATOR);
0298:                String tV = properties.getProperty(TIMESTAMP_VALIDATOR);
0299:                String cV = properties.getProperty(CERTIFICATE_VALIDATOR);
0300:
0301:                usernameCbHandler = loadClass(uCBH);
0302:                passwordCbHandler = loadClass(pCBH);
0303:                samlCbHandler = loadClass(sCBH);
0304:
0305:                usernameValidator = loadClass(uV);
0306:                samlValidator = loadClass(sV);
0307:                timestampValidator = loadClass(tV);
0308:                certificateValidator = loadClass(cV);
0309:
0310:                keystoreCertSelectorClass = loadClass(this .keystoreCertSelectorClassName);
0311:                truststoreCertSelectorClass = loadClass(this .truststoreCertSelectorClassName);
0312:
0313:                this .certstoreCbHandler = loadClass(this .certStoreCBHClassName);
0314:                this .certSelectorClass = loadClass(this .certSelectorClassName);
0315:                this .crlSelectorClass = loadClass(this .crlSelectorClassName);
0316:
0317:                mcs = properties.getProperty(MAX_CLOCK_SKEW_PROPERTY);
0318:                tfl = properties
0319:                        .getProperty(TIMESTAMP_FRESHNESS_LIMIT_PROPERTY);
0320:                mna = properties.getProperty(MAX_NONCE_AGE_PROPERTY);
0321:                revocationEnabledAttr = properties
0322:                        .getProperty(REVOCATION_ENABLED);
0323:                if (revocationEnabledAttr != null) {
0324:                    this .revocationEnabled = Boolean
0325:                            .parseBoolean(revocationEnabledAttr);
0326:                }
0327:                maxClockSkewG = toLong(mcs);
0328:                timestampFreshnessLimitG = toLong(tfl);
0329:                maxNonceAge = toLong(mna);
0330:
0331:                initTrustStore();
0332:                initKeyStore();
0333:                initNewInstances();
0334:
0335:                defaultCertValidator = new X509CertificateValidatorImpl();
0336:                defaultTSValidator = new DefaultTimestampValidator();
0337:            }
0338:
0339:            public DefaultCallbackHandler(String clientOrServer,
0340:                    Properties assertions, RealmAuthenticationAdapter adapter)
0341:                    throws Exception {
0342:                this (clientOrServer, assertions);
0343:                usernameAuthenticator = adapter;
0344:                if (adapter == null) {
0345:                    defRealmAuthenticator = RealmAuthenticationAdapter
0346:                            .newInstance(null);
0347:                }
0348:            }
0349:
0350:            private void handleUsernameCallback(UsernameCallback cb)
0351:                    throws IOException, UnsupportedCallbackException {
0352:                if (myUsername != null) {
0353:                    cb.setUsername(myUsername);
0354:                } else {
0355:                    String username = (String) cb.getRuntimeProperties().get(
0356:                            BindingProvider.USERNAME_PROPERTY);
0357:                    if (username != null) {
0358:                        cb.setUsername(username);
0359:                    } else if (usernameHandler != null) {
0360:                        javax.security.auth.callback.NameCallback nc = new javax.security.auth.callback.NameCallback(
0361:                                "Username=");
0362:                        Callback[] cbs = new Callback[] { nc };
0363:                        usernameHandler.handle(cbs);
0364:                        cb
0365:                                .setUsername(((javax.security.auth.callback.NameCallback) cbs[0])
0366:                                        .getName());
0367:                    } else {
0368:                        log
0369:                                .log(Level.SEVERE,
0370:                                        "WSS1500.invalid.usernameHandler");
0371:                        throw new UnsupportedCallbackException(null,
0372:                                "Username Handler Not Configured");
0373:                    }
0374:                }
0375:            }
0376:
0377:            private void handlePasswordCallback(PasswordCallback cb)
0378:                    throws IOException, UnsupportedCallbackException {
0379:                if (myPassword != null) {
0380:                    cb.setPassword(myPassword);
0381:                } else {
0382:                    String password = (String) cb.getRuntimeProperties().get(
0383:                            BindingProvider.PASSWORD_PROPERTY);
0384:                    if (password != null) {
0385:                        cb.setPassword(password);
0386:                    } else if (passwordHandler != null) {
0387:                        javax.security.auth.callback.PasswordCallback pc = new javax.security.auth.callback.PasswordCallback(
0388:                                "Password=", false);
0389:                        Callback[] cbs = new Callback[] { pc };
0390:                        passwordHandler.handle(cbs);
0391:                        char[] pass = ((javax.security.auth.callback.PasswordCallback) cbs[0])
0392:                                .getPassword();
0393:                        cb.setPassword(new String(pass));
0394:                    } else {
0395:                        log
0396:                                .log(Level.SEVERE,
0397:                                        "WSS1525.invalid.passwordHandler");
0398:                        throw new UnsupportedCallbackException(null,
0399:                                "Password Handler Not Configured");
0400:                    }
0401:                }
0402:            }
0403:
0404:            private void handlePasswordValidation(PasswordValidationCallback cb)
0405:                    throws IOException, UnsupportedCallbackException {
0406:                if (cb.getRequest() instanceof  PasswordValidationCallback.PlainTextPasswordRequest) {
0407:                    if (pwValidator != null) {
0408:                        cb.setValidator(pwValidator);
0409:                    } else {
0410:                        if (usernameAuthenticator != null) {
0411:                            cb
0412:                                    .setRealmAuthentcationAdapter(usernameAuthenticator);
0413:                        } else {
0414:                            cb
0415:                                    .setRealmAuthentcationAdapter(defRealmAuthenticator);
0416:                        }
0417:                    }
0418:                } else if (cb.getRequest() instanceof  PasswordValidationCallback.DigestPasswordRequest) {
0419:                    log.log(Level.SEVERE, "WSS1502.unsupported.digestAuth");
0420:                    throw new UnsupportedCallbackException(null,
0421:                            "Digest Authentication for Passwords Not Supported");
0422:                } else {
0423:                    log.log(Level.SEVERE, "WSS1503.unsupported.requesttype");
0424:                    throw new UnsupportedCallbackException(null,
0425:                            "Unsupported Request Type for Password Validation");
0426:                }
0427:            }
0428:
0429:            private void handleTimestampValidation(
0430:                    TimestampValidationCallback cb) throws IOException,
0431:                    UnsupportedCallbackException {
0432:                if (tsValidator != null) {
0433:                    cb.setValidator(tsValidator);
0434:                } else {
0435:                    // this is for BC reasons, but will be enabled later
0436:                    cb.setValidator(defaultTSValidator);
0437:                }
0438:            }
0439:
0440:            public void handle(Callback[] callbacks) throws IOException,
0441:                    UnsupportedCallbackException {
0442:
0443:                for (int i = 0; i < callbacks.length; i++) {
0444:
0445:                    if (callbacks[i] instanceof  UsernameCallback) {
0446:                        UsernameCallback cb = (UsernameCallback) callbacks[i];
0447:                        handleUsernameCallback(cb);
0448:
0449:                    } else if (callbacks[i] instanceof  PasswordCallback) {
0450:                        PasswordCallback cb = (PasswordCallback) callbacks[i];
0451:                        handlePasswordCallback(cb);
0452:
0453:                    } else if (callbacks[i] instanceof  PasswordValidationCallback) {
0454:                        PasswordValidationCallback cb = (PasswordValidationCallback) callbacks[i];
0455:                        handlePasswordValidation(cb);
0456:
0457:                    } else if (callbacks[i] instanceof  TimestampValidationCallback) {
0458:                        TimestampValidationCallback cb = (TimestampValidationCallback) callbacks[i];
0459:                        handleTimestampValidation(cb);
0460:
0461:                    } else if (callbacks[i] instanceof  SignatureVerificationKeyCallback) {
0462:
0463:                        SignatureVerificationKeyCallback cb = (SignatureVerificationKeyCallback) callbacks[i];
0464:
0465:                        if (cb.getRequest() instanceof  SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
0466:                            // subject keyid request
0467:                            SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request = (SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) cb
0468:                                    .getRequest();
0469:                            X509Certificate cert = getCertificateFromTrustStore(request
0470:                                    .getSubjectKeyIdentifier());
0471:                            request.setX509Certificate(cert);
0472:
0473:                        } else if (cb.getRequest() instanceof  SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) {
0474:                            // issuer serial request
0475:                            SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request = (SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) cb
0476:                                    .getRequest();
0477:                            X509Certificate cert = getCertificateFromTrustStore(
0478:                                    request.getIssuerName(), request
0479:                                            .getSerialNumber());
0480:                            request.setX509Certificate(cert);
0481:
0482:                        } else if (cb.getRequest() instanceof  SignatureVerificationKeyCallback.ThumbprintBasedRequest) {
0483:                            SignatureVerificationKeyCallback.ThumbprintBasedRequest request = (SignatureVerificationKeyCallback.ThumbprintBasedRequest) cb
0484:                                    .getRequest();
0485:                            X509Certificate cert = getCertificateFromTrustStoreForThumbprint(request
0486:                                    .getThumbprintIdentifier());
0487:                            request.setX509Certificate(cert);
0488:
0489:                        } else {
0490:                            log.log(Level.SEVERE,
0491:                                    "WSS1504.unsupported.callbackType");
0492:                            throw unsupported;
0493:                        }
0494:
0495:                    } else if (callbacks[i] instanceof  SignatureKeyCallback) {
0496:                        SignatureKeyCallback cb = (SignatureKeyCallback) callbacks[i];
0497:
0498:                        if (cb.getRequest() instanceof  SignatureKeyCallback.DefaultPrivKeyCertRequest) {
0499:                            // default priv key cert req
0500:                            SignatureKeyCallback.DefaultPrivKeyCertRequest request = (SignatureKeyCallback.DefaultPrivKeyCertRequest) cb
0501:                                    .getRequest();
0502:                            getDefaultPrivKeyCert(request, cb
0503:                                    .getRuntimeProperties());
0504:
0505:                        } else if (cb.getRequest() instanceof  SignatureKeyCallback.AliasPrivKeyCertRequest) {
0506:                            SignatureKeyCallback.AliasPrivKeyCertRequest request = (SignatureKeyCallback.AliasPrivKeyCertRequest) cb
0507:                                    .getRequest();
0508:                            String alias = request.getAlias();
0509:                            try {
0510:                                X509Certificate cert = (X509Certificate) keyStore
0511:                                        .getCertificate(alias);
0512:                                request.setX509Certificate(cert);
0513:                                // Assuming key passwords same as the keystore password
0514:                                PrivateKey privKey = (PrivateKey) keyStore
0515:                                        .getKey(alias, this .keyPassword);
0516:                                request.setPrivateKey(privKey);
0517:                            } catch (Exception e) {
0518:                                log.log(Level.SEVERE,
0519:                                        "WSS1505.failedto.getkey", e);
0520:                                throw new RuntimeException(e);
0521:                            }
0522:
0523:                        } else {
0524:                            log.log(Level.SEVERE,
0525:                                    "WSS1504.unsupported.callbackType");
0526:                            throw unsupported;
0527:                        }
0528:
0529:                    } else if (callbacks[i] instanceof  DecryptionKeyCallback) {
0530:                        DecryptionKeyCallback cb = (DecryptionKeyCallback) callbacks[i];
0531:
0532:                        if (cb.getRequest() instanceof  DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
0533:                            DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request = (DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) cb
0534:                                    .getRequest();
0535:                            byte[] ski = request.getSubjectKeyIdentifier();
0536:                            PrivateKey privKey = getPrivateKey(ski);
0537:                            request.setPrivateKey(privKey);
0538:
0539:                        } else if (cb.getRequest() instanceof  DecryptionKeyCallback.X509IssuerSerialBasedRequest) {
0540:                            DecryptionKeyCallback.X509IssuerSerialBasedRequest request = (DecryptionKeyCallback.X509IssuerSerialBasedRequest) cb
0541:                                    .getRequest();
0542:                            String issuerName = request.getIssuerName();
0543:                            BigInteger serialNumber = request.getSerialNumber();
0544:                            PrivateKey privKey = getPrivateKey(issuerName,
0545:                                    serialNumber);
0546:                            request.setPrivateKey(privKey);
0547:
0548:                        } else if (cb.getRequest() instanceof  DecryptionKeyCallback.X509CertificateBasedRequest) {
0549:                            DecryptionKeyCallback.X509CertificateBasedRequest request = (DecryptionKeyCallback.X509CertificateBasedRequest) cb
0550:                                    .getRequest();
0551:                            X509Certificate cert = request.getX509Certificate();
0552:                            PrivateKey privKey = getPrivateKey(cert);
0553:                            request.setPrivateKey(privKey);
0554:
0555:                        } else if (cb.getRequest() instanceof  DecryptionKeyCallback.ThumbprintBasedRequest) {
0556:                            DecryptionKeyCallback.ThumbprintBasedRequest request = (DecryptionKeyCallback.ThumbprintBasedRequest) cb
0557:                                    .getRequest();
0558:                            byte[] ski = request.getThumbprintIdentifier();
0559:                            PrivateKey privKey = getPrivateKeyForThumbprint(ski);
0560:                            request.setPrivateKey(privKey);
0561:                        } else if (cb.getRequest() instanceof  DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) {
0562:                            DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request = (DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) cb
0563:                                    .getRequest();
0564:
0565:                            PrivateKey privKey = getPrivateKeyFromKeyStore(request
0566:                                    .getPublicKey());
0567:                            request.setPrivateKey(privKey);
0568:                        } else {
0569:                            log.log(Level.SEVERE,
0570:                                    "WSS1504.unsupported.callbackType");
0571:                            throw unsupported;
0572:                        }
0573:
0574:                    } else if (callbacks[i] instanceof  EncryptionKeyCallback) {
0575:                        EncryptionKeyCallback cb = (EncryptionKeyCallback) callbacks[i];
0576:
0577:                        if (cb.getRequest() instanceof  EncryptionKeyCallback.AliasX509CertificateRequest) {
0578:                            EncryptionKeyCallback.AliasX509CertificateRequest request = (EncryptionKeyCallback.AliasX509CertificateRequest) cb
0579:                                    .getRequest();
0580:
0581:                            String alias = request.getAlias();
0582:                            if ("".equals(alias) || (alias == null)) {
0583:                                getDefaultCertificateFromTrustStore(cb
0584:                                        .getRuntimeProperties(), request);
0585:                            } else {
0586:                                try {
0587:                                    X509Certificate cert = (X509Certificate) trustStore
0588:                                            .getCertificate(alias);
0589:                                    request.setX509Certificate(cert);
0590:                                } catch (Exception e) {
0591:                                    log.log(Level.SEVERE,
0592:                                            "WSS1526.failedto.getcertificate",
0593:                                            e);
0594:                                    throw new RuntimeException(e);
0595:                                }
0596:                            }
0597:
0598:                        } else if (cb.getRequest() instanceof  EncryptionKeyCallback.PublicKeyBasedRequest) {
0599:                            EncryptionKeyCallback.PublicKeyBasedRequest request = (EncryptionKeyCallback.PublicKeyBasedRequest) cb
0600:                                    .getRequest();
0601:                            try {
0602:                                X509Certificate cert = getCertificateFromTrustStoreForSAML(request
0603:                                        .getPublicKey());
0604:                                request.setX509Certificate(cert);
0605:                            } catch (Exception e) {
0606:                                log.log(Level.SEVERE,
0607:                                        "WSS1526.failedto.getcertificate", e);
0608:                                throw new RuntimeException(e);
0609:                            }
0610:                        } else if (cb.getRequest() instanceof  EncryptionKeyCallback.AliasSymmetricKeyRequest) {
0611:                            log.log(Level.SEVERE,
0612:                                    "WSS1504.unsupported.callbackType");
0613:                            throw unsupported;
0614:                        }
0615:
0616:                    } else if (callbacks[i] instanceof  CertificateValidationCallback) {
0617:                        CertificateValidationCallback cb = (CertificateValidationCallback) callbacks[i];
0618:                        if (certValidator != null) {
0619:                            cb.setValidator(certValidator);
0620:                        } else {
0621:                            cb.setValidator(defaultCertValidator);
0622:                        }
0623:                    } else if (callbacks[i] instanceof  DynamicPolicyCallback) {
0624:                        DynamicPolicyCallback dp = (DynamicPolicyCallback) callbacks[i];
0625:                        SecurityPolicy policy = dp.getSecurityPolicy();
0626:                        if (policy instanceof  AuthenticationTokenPolicy.SAMLAssertionBinding) {
0627:                            AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) ((AuthenticationTokenPolicy.SAMLAssertionBinding) policy)
0628:                                    .clone();
0629:
0630:                            if ((samlBinding.getAssertion() == null)
0631:                                    && (samlBinding.getAuthorityBinding() == null)
0632:                                    && (samlBinding.getAssertionReader() == null)) {
0633:                                populateAssertion(samlBinding, dp);
0634:                            } else if (samlBinding.getAssertion() != null
0635:                                    || samlBinding.getAssertionReader() != null) {
0636:                                Subject subj = (Subject) dp
0637:                                        .getRuntimeProperties().get(
0638:                                                MessageConstants.AUTH_SUBJECT);
0639:                                validateSAMLAssertion(samlBinding, subj);
0640:                            } else if ((samlBinding.getAuthorityBinding() != null)
0641:                                    && (samlBinding.getAssertionId() != null)) {
0642:                                locateSAMLAssertion(samlBinding);
0643:                            } else {
0644:                                log.log(Level.SEVERE,
0645:                                        "WSS1506.invalid.SAMLPolicy");
0646:                                throw new UnsupportedCallbackException(null,
0647:                                        "SAML Assertion not present in the Policy");
0648:                            }
0649:                        }
0650:                    } else {
0651:                        log.log(Level.SEVERE,
0652:                                "WSS1504.unsupported.callbackType");
0653:                        throw unsupported;
0654:                    }
0655:                }
0656:            }
0657:
0658:            private void populateAssertion(
0659:                    AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding,
0660:                    DynamicPolicyCallback dp) throws IOException,
0661:                    UnsupportedCallbackException {
0662:
0663:                if (samlBinding.getAssertionType() == AuthenticationTokenPolicy.SAMLAssertionBinding.SV_ASSERTION) {
0664:
0665:                    if (samlHandler != null) {
0666:
0667:                        SAMLCallback sc = new SAMLCallback();
0668:                        sc.setConfirmationMethod(sc.SV_ASSERTION_TYPE);
0669:                        sc.setSAMLVersion(samlBinding.getSAMLVersion());
0670:                        Callback[] cbs = new Callback[] { sc };
0671:                        samlHandler.handle(cbs);
0672:                        samlBinding.setAssertion(sc.getAssertionElement());
0673:                        samlBinding.setAuthorityBinding(sc
0674:                                .getAuthorityBindingElement());
0675:                        dp.setSecurityPolicy(samlBinding);
0676:
0677:                    } else {
0678:                        log.log(Level.SEVERE, "WSS1507.no.SAMLCallbackHandler");
0679:                        throw new UnsupportedCallbackException(
0680:                                null,
0681:                                "A Required SAML Callback Handler was not specified in configuration : Cannot Populate SAML Assertion");
0682:                    }
0683:
0684:                } else {
0685:
0686:                    if (samlHandler != null) {
0687:
0688:                        SAMLCallback sc = new SAMLCallback();
0689:                        sc.setConfirmationMethod(sc.HOK_ASSERTION_TYPE);
0690:                        sc.setSAMLVersion(samlBinding.getSAMLVersion());
0691:                        Callback[] cbs = new Callback[] { sc };
0692:                        samlHandler.handle(cbs);
0693:                        samlBinding.setAssertion(sc.getAssertionElement());
0694:                        samlBinding.setAuthorityBinding(sc
0695:                                .getAuthorityBindingElement());
0696:                        dp.setSecurityPolicy(samlBinding);
0697:                        PrivateKeyBinding pkBinding = (PrivateKeyBinding) samlBinding
0698:                                .newPrivateKeyBinding();
0699:
0700:                        SignatureKeyCallback.DefaultPrivKeyCertRequest request = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0701:                        getDefaultPrivKeyCert(request, dp
0702:                                .getRuntimeProperties());
0703:                        pkBinding.setPrivateKey(request.getPrivateKey());
0704:
0705:                    } else {
0706:                        log.log(Level.SEVERE, "WSS1507.no.SAMLCallbackHandler");
0707:                        throw new UnsupportedCallbackException(
0708:                                null,
0709:                                "A Required SAML Callback Handler was not specified in configuration : Cannot Populate SAML Assertion");
0710:                    }
0711:                }
0712:            }
0713:
0714:            private void validateSAMLAssertion(
0715:                    AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding,
0716:                    Subject subj) throws IOException,
0717:                    UnsupportedCallbackException {
0718:                if (sValidator != null) {
0719:                    try {
0720:                        if (samlBinding.getAssertion() != null) {
0721:                            sValidator.validate(samlBinding.getAssertion());
0722:                        } else if (samlBinding.getAssertionReader() != null) {
0723:                            sValidator.validate(samlBinding
0724:                                    .getAssertionReader());
0725:                        }
0726:                    } catch (SAMLAssertionValidator.SAMLValidationException e) {
0727:                        log.log(Level.SEVERE,
0728:                                "WSS1508.failed.validateSAMLAssertion", e);
0729:                        throw new RuntimeException(e);
0730:                    }
0731:                }
0732:            }
0733:
0734:            private void locateSAMLAssertion(
0735:                    AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding)
0736:                    throws IOException, UnsupportedCallbackException {
0737:
0738:                Element binding = samlBinding.getAuthorityBinding();
0739:                String assertionId = samlBinding.getAssertionId();
0740:                // use the above information to locate the assertion
0741:                // this simple impl will just set the assertion
0742:                if (samlBinding.getAssertionType() == AuthenticationTokenPolicy.SAMLAssertionBinding.SV_ASSERTION) {
0743:                    if (samlHandler != null) {
0744:                        SAMLCallback sc = new SAMLCallback();
0745:                        sc.setConfirmationMethod(sc.SV_ASSERTION_TYPE);
0746:                        sc.setSAMLVersion(samlBinding.getSAMLVersion());
0747:                        sc.setAssertionId(assertionId);
0748:                        sc.setAuthorityBindingElement(binding);
0749:                        Callback[] cbs = new Callback[] { sc };
0750:                        samlHandler.handle(cbs);
0751:                        samlBinding.setAssertion(sc.getAssertionElement());
0752:                    } else {
0753:                        log.log(Level.SEVERE, "WSS1507.no.SAMLCallbackHandler");
0754:                        throw new UnsupportedCallbackException(
0755:                                null,
0756:                                "A Required SAML Callback Handler was not specified in configuration : Cannot Populate SAML Assertion");
0757:                    }
0758:
0759:                } else {
0760:
0761:                    if (samlHandler != null) {
0762:                        SAMLCallback sc = new SAMLCallback();
0763:                        sc.setConfirmationMethod(sc.HOK_ASSERTION_TYPE);
0764:                        sc.setSAMLVersion(samlBinding.getSAMLVersion());
0765:                        sc.setAssertionId(assertionId);
0766:                        sc.setAuthorityBindingElement(binding);
0767:                        Callback[] cbs = new Callback[] { sc };
0768:                        samlHandler.handle(cbs);
0769:                        samlBinding.setAssertion(sc.getAssertionElement());
0770:                        PrivateKeyBinding pkBinding = (PrivateKeyBinding) samlBinding
0771:                                .newPrivateKeyBinding();
0772:
0773:                        SignatureKeyCallback.DefaultPrivKeyCertRequest request = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0774:                        getDefaultPrivKeyCert(request, null);
0775:                        pkBinding.setPrivateKey(request.getPrivateKey());
0776:
0777:                    } else {
0778:                        log.log(Level.SEVERE, "WSS1507.no.SAMLCallbackHandler");
0779:                        throw new UnsupportedCallbackException(
0780:                                null,
0781:                                "A Required SAML Callback Handler was not specified in configuration : Cannot Populate SAML Assertion");
0782:                    }
0783:                }
0784:            }
0785:
0786:            private void initTrustStore() throws XWSSecurityException {
0787:                try {
0788:
0789:                    if (trustStoreURL == null) {
0790:                        if (log.isLoggable(Level.FINE)) {
0791:                            log.log(Level.FINE, "Got NULL for TrustStore URL");
0792:                        }
0793:                        return;
0794:                    }
0795:                    if (this .trustStorePassword == null) {
0796:                        if (log.isLoggable(Level.FINE)) {
0797:                            log.log(Level.FINE,
0798:                                    "Got NULL for TrustStore Password");
0799:                        }
0800:                    }
0801:
0802:                    char[] trustStorePasswordChars = null;
0803:                    //check here if trustStorePassword is a CBH className
0804:                    Class cbh = this .loadClassSilent(trustStorePassword);
0805:                    if (cbh != null) {
0806:                        CallbackHandler hdlr = (CallbackHandler) cbh
0807:                                .newInstance();
0808:                        javax.security.auth.callback.PasswordCallback pc = new javax.security.auth.callback.PasswordCallback(
0809:                                "TrustStorePassword", false);
0810:                        Callback[] cbs = new Callback[] { pc };
0811:                        hdlr.handle(cbs);
0812:                        trustStorePasswordChars = ((javax.security.auth.callback.PasswordCallback) cbs[0])
0813:                                .getPassword();
0814:                    } else {
0815:                        //the user supplied value is a Password for the truststore
0816:                        trustStorePasswordChars = trustStorePassword
0817:                                .toCharArray();
0818:                    }
0819:
0820:                    trustStore = KeyStore.getInstance(trustStoreType);
0821:                    FileInputStream is = null;
0822:                    try {
0823:                        is = new FileInputStream(trustStoreURL);
0824:                        trustStore.load(is, trustStorePasswordChars);
0825:                    } finally {
0826:                        is.close();
0827:                    }
0828:                } catch (Exception e) {
0829:                    log.log(Level.SEVERE, "WSS1509.failed.init.truststore", e);
0830:                    throw new RuntimeException(e);
0831:                }
0832:            }
0833:
0834:            private void initKeyStore() throws XWSSecurityException {
0835:                try {
0836:                    if (keyStoreURL == null) {
0837:                        if (log.isLoggable(Level.FINE)) {
0838:                            log.log(Level.FINE, "Got NULL for KeyStore URL");
0839:                        }
0840:                        return;
0841:                    }
0842:
0843:                    if (keyStorePassword == null) {
0844:                        if (log.isLoggable(Level.FINE)) {
0845:                            log.log(Level.FINE,
0846:                                    "Got NULL for KeyStore PASSWORD");
0847:                        }
0848:                        return;
0849:                    }
0850:
0851:                    char[] keyStorePasswordChars = null;
0852:                    //check here if keyStorePassword is a CBH className
0853:                    Class cbh = this .loadClassSilent(keyStorePassword);
0854:                    if (cbh != null) {
0855:                        CallbackHandler hdlr = (CallbackHandler) cbh
0856:                                .newInstance();
0857:                        javax.security.auth.callback.PasswordCallback pc = new javax.security.auth.callback.PasswordCallback(
0858:                                "KeyStorePassword", false);
0859:                        Callback[] cbs = new Callback[] { pc };
0860:                        hdlr.handle(cbs);
0861:                        keyStorePasswordChars = ((javax.security.auth.callback.PasswordCallback) cbs[0])
0862:                                .getPassword();
0863:                    } else {
0864:                        //the user supplied value is a Password for the keystore
0865:                        keyStorePasswordChars = keyStorePassword.toCharArray();
0866:                    }
0867:
0868:                    //now initialize KeyPassword if any ?
0869:                    if (this .keyPwd == null) {
0870:                        this .keyPassword = keyStorePasswordChars;
0871:                    } else {
0872:                        initKeyPassword();
0873:                    }
0874:
0875:                    keyStore = KeyStore.getInstance(keyStoreType);
0876:                    FileInputStream is = null;
0877:                    try {
0878:                        is = new FileInputStream(keyStoreURL);
0879:                        keyStore.load(is, keyStorePasswordChars);
0880:                    } finally {
0881:                        is.close();
0882:                    }
0883:                } catch (Exception e) {
0884:                    log.log(Level.SEVERE, "WSS1510.failed.init.keystore", e);
0885:                    throw new RuntimeException(e);
0886:                }
0887:            }
0888:
0889:            private X509Certificate getCertificateFromTrustStore(byte[] ski)
0890:                    throws IOException {
0891:
0892:                try {
0893:                    if (trustStore == null && certStore == null)
0894:                        return null;
0895:                    if (trustStore != null) {
0896:                        Enumeration aliases = trustStore.aliases();
0897:                        while (aliases.hasMoreElements()) {
0898:                            String alias = (String) aliases.nextElement();
0899:                            Certificate cert = trustStore.getCertificate(alias);
0900:                            if (cert == null || !"X.509".equals(cert.getType())) {
0901:                                continue;
0902:                            }
0903:                            X509Certificate x509Cert = (X509Certificate) cert;
0904:                            byte[] keyId = getSubjectKeyIdentifier(x509Cert);
0905:                            if (keyId == null) {
0906:                                // Cert does not contain a key identifier
0907:                                continue;
0908:                            }
0909:                            if (Arrays.equals(ski, keyId)) {
0910:                                return x509Cert;
0911:                            }
0912:                        }
0913:                    }
0914:                } catch (Exception e) {
0915:                    log.log(Level.SEVERE, "WSS1526.failedto.getcertificate", e);
0916:                    throw new RuntimeException(e);
0917:                }
0918:                //now search in CertStore if present
0919:                if (this .certStore != null) {
0920:                    CertSelector selector = new KeyIdentifierCertSelector(ski);
0921:                    Collection certs = null;
0922:                    try {
0923:                        certs = certStore.getCertificates(selector);
0924:                    } catch (CertStoreException ex) {
0925:                        log.log(Level.SEVERE,
0926:                                "WSS1530.exception.in.certstore.lookup", ex);
0927:                        throw new RuntimeException(ex);
0928:                    }
0929:                    if (certs.size() > 0) {
0930:                        return (X509Certificate) certs.iterator().next();
0931:                    }
0932:                }
0933:                return null;
0934:            }
0935:
0936:            private X509Certificate getCertificateFromTrustStore(
0937:                    String issuerName, BigInteger serialNumber)
0938:                    throws IOException {
0939:
0940:                try {
0941:                    if (trustStore == null && certStore == null)
0942:                        return null;
0943:                    if (trustStore != null) {
0944:                        Enumeration aliases = trustStore.aliases();
0945:                        while (aliases.hasMoreElements()) {
0946:                            String alias = (String) aliases.nextElement();
0947:                            Certificate cert = trustStore.getCertificate(alias);
0948:                            if (cert == null || !"X.509".equals(cert.getType())) {
0949:                                continue;
0950:                            }
0951:                            X509Certificate x509Cert = (X509Certificate) cert;
0952:                            String this IssuerName = RFC2253Parser
0953:                                    .normalize(x509Cert.getIssuerDN().getName());
0954:                            BigInteger this SerialNumber = x509Cert
0955:                                    .getSerialNumber();
0956:                            if (this IssuerName.equals(issuerName)
0957:                                    && this SerialNumber.equals(serialNumber)) {
0958:                                return x509Cert;
0959:                            }
0960:                        }
0961:                    }
0962:                } catch (Exception e) {
0963:                    log.log(Level.SEVERE, "WSS1526.failedto.getcertificate", e);
0964:                    throw new RuntimeException(e);
0965:                }
0966:                //now search in CertStore if present
0967:                if (this .certStore != null) {
0968:                    CertSelector selector = new IssuerNameAndSerialCertSelector(
0969:                            serialNumber, issuerName);
0970:                    Collection certs = null;
0971:                    try {
0972:                        certs = certStore.getCertificates(selector);
0973:                    } catch (CertStoreException ex) {
0974:                        log.log(Level.SEVERE,
0975:                                "WSS1530.exception.in.certstore.lookup", ex);
0976:                        throw new RuntimeException(ex);
0977:                    }
0978:                    if (certs.size() > 0) {
0979:                        return (X509Certificate) certs.iterator().next();
0980:                    }
0981:                }
0982:
0983:                return null;
0984:            }
0985:
0986:            public PrivateKey getPrivateKey(byte[] ski) throws IOException {
0987:
0988:                try {
0989:                    if (keyStore == null)
0990:                        return null;
0991:                    Enumeration aliases = keyStore.aliases();
0992:                    while (aliases.hasMoreElements()) {
0993:                        String alias = (String) aliases.nextElement();
0994:                        if (!keyStore.isKeyEntry(alias))
0995:                            continue;
0996:                        Certificate cert = keyStore.getCertificate(alias);
0997:                        if (cert == null || !"X.509".equals(cert.getType())) {
0998:                            continue;
0999:                        }
1000:                        X509Certificate x509Cert = (X509Certificate) cert;
1001:                        byte[] keyId = getSubjectKeyIdentifier(x509Cert);
1002:                        if (keyId == null) {
1003:                            // Cert does not contain a key identifier
1004:                            continue;
1005:                        }
1006:                        if (Arrays.equals(ski, keyId)) {
1007:                            // Asuumed key password same as the keystore password
1008:                            return (PrivateKey) keyStore.getKey(alias,
1009:                                    this .keyPassword);
1010:                        }
1011:                    }
1012:                } catch (Exception e) {
1013:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1014:                    throw new RuntimeException(e);
1015:                }
1016:                return null;
1017:            }
1018:
1019:            public PrivateKey getPrivateKey(String issuerName,
1020:                    BigInteger serialNumber) throws IOException {
1021:
1022:                try {
1023:                    if (keyStore == null)
1024:                        return null;
1025:                    Enumeration aliases = keyStore.aliases();
1026:                    while (aliases.hasMoreElements()) {
1027:                        String alias = (String) aliases.nextElement();
1028:                        if (!keyStore.isKeyEntry(alias))
1029:                            continue;
1030:                        Certificate cert = keyStore.getCertificate(alias);
1031:                        if (cert == null || !"X.509".equals(cert.getType())) {
1032:                            continue;
1033:                        }
1034:                        X509Certificate x509Cert = (X509Certificate) cert;
1035:                        String this IssuerName = RFC2253Parser
1036:                                .normalize(x509Cert.getIssuerDN().getName());
1037:                        BigInteger this SerialNumber = x509Cert
1038:                                .getSerialNumber();
1039:                        if (this IssuerName.equals(issuerName)
1040:                                && this SerialNumber.equals(serialNumber)) {
1041:                            return (PrivateKey) keyStore.getKey(alias,
1042:                                    this .keyPassword);
1043:                        }
1044:                    }
1045:                } catch (Exception e) {
1046:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1047:                    throw new RuntimeException(e);
1048:                }
1049:                return null;
1050:            }
1051:
1052:            public PrivateKey getPrivateKey(X509Certificate certificate)
1053:                    throws IOException {
1054:
1055:                try {
1056:                    if (keyStore == null)
1057:                        return null;
1058:                    Enumeration aliases = keyStore.aliases();
1059:                    while (aliases.hasMoreElements()) {
1060:                        String alias = (String) aliases.nextElement();
1061:                        if (!keyStore.isKeyEntry(alias))
1062:                            continue;
1063:                        Certificate cert = keyStore.getCertificate(alias);
1064:                        if (cert != null && cert.equals(certificate))
1065:                            return (PrivateKey) keyStore.getKey(alias,
1066:                                    this .keyPassword);
1067:                    }
1068:                } catch (Exception e) {
1069:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1070:                    throw new RuntimeException(e);
1071:                }
1072:                return null;
1073:            }
1074:
1075:            private void getDefaultCertificateFromTrustStore(Map context,
1076:                    EncryptionKeyCallback.AliasX509CertificateRequest req)
1077:                    throws IOException {
1078:
1079:                String currentAlias = null;
1080:                if (peerEntityAlias != null) {
1081:                    currentAlias = peerEntityAlias;
1082:                } else {
1083:                    //try to locate in certstore using user supplied CertSelector
1084:                    if (certStore != null) {
1085:                        CertSelector selector = null;
1086:                        if (this .certSelectorClass != null) {
1087:                            Constructor ctor = null;
1088:                            try {
1089:                                ctor = certSelectorClass
1090:                                        .getConstructor(new Class[] { Map.class });
1091:                            } catch (SecurityException ex) {
1092:                                //ignore and use default CTOR
1093:                            } catch (NoSuchMethodException ex) {
1094:                                //ignore and use default CTOR
1095:                            }
1096:                            if (ctor != null) {
1097:                                try {
1098:                                    selector = (CertSelector) ctor
1099:                                            .newInstance(context);
1100:                                } catch (IllegalArgumentException ex) {
1101:                                    log
1102:                                            .log(
1103:                                                    Level.SEVERE,
1104:                                                    "WSS1531.exception.instantiating.certselector",
1105:                                                    ex);
1106:                                    throw new RuntimeException(ex);
1107:                                } catch (InstantiationException ex) {
1108:                                    log
1109:                                            .log(
1110:                                                    Level.SEVERE,
1111:                                                    "WSS1531.exception.instantiating.certselector",
1112:                                                    ex);
1113:                                    throw new RuntimeException(ex);
1114:                                } catch (InvocationTargetException ex) {
1115:                                    log
1116:                                            .log(
1117:                                                    Level.SEVERE,
1118:                                                    "WSS1531.exception.instantiating.certselector",
1119:                                                    ex);
1120:                                    throw new RuntimeException(ex);
1121:                                } catch (IllegalAccessException ex) {
1122:                                    log
1123:                                            .log(
1124:                                                    Level.SEVERE,
1125:                                                    "WSS1531.exception.instantiating.certselector",
1126:                                                    ex);
1127:                                    throw new RuntimeException(ex);
1128:                                }
1129:                            } else {
1130:                                try {
1131:                                    selector = (CertSelector) certSelectorClass
1132:                                            .newInstance();
1133:                                } catch (InstantiationException ex) {
1134:                                    log
1135:                                            .log(
1136:                                                    Level.SEVERE,
1137:                                                    "WSS1531.exception.instantiating.certselector",
1138:                                                    ex);
1139:                                    throw new RuntimeException(ex);
1140:                                } catch (IllegalAccessException ex) {
1141:                                    log
1142:                                            .log(
1143:                                                    Level.SEVERE,
1144:                                                    "WSS1531.exception.instantiating.certselector",
1145:                                                    ex);
1146:                                    throw new RuntimeException(ex);
1147:                                }
1148:                            }
1149:                        }
1150:
1151:                        if (selector != null) {
1152:                            Collection certs = null;
1153:                            try {
1154:                                certs = certStore.getCertificates(selector);
1155:                            } catch (CertStoreException ex) {
1156:                                log.log(Level.SEVERE,
1157:                                        "WSS1526.failedto.getcertificate", ex);
1158:                                throw new RuntimeException(ex);
1159:                            }
1160:                            if (certs.size() > 0) {
1161:                                req.setX509Certificate((X509Certificate) certs
1162:                                        .iterator().next());
1163:                                return;
1164:                            }
1165:                        }
1166:                    }
1167:
1168:                    if (trustStore != null) {
1169:                        if (this .truststoreCertSelectorClass != null) {
1170:                            CertSelector selector = null;
1171:                            Constructor ctor = null;
1172:                            try {
1173:                                ctor = truststoreCertSelectorClass
1174:                                        .getConstructor(new Class[] { Map.class });
1175:                            } catch (SecurityException ex) {
1176:                                //ignore and use default CTOR
1177:                            } catch (NoSuchMethodException ex) {
1178:                                //ignore and use default CTOR
1179:                            }
1180:                            if (ctor != null) {
1181:                                try {
1182:                                    selector = (CertSelector) ctor
1183:                                            .newInstance(context);
1184:                                } catch (IllegalArgumentException ex) {
1185:                                    log
1186:                                            .log(
1187:                                                    Level.SEVERE,
1188:                                                    "WSS1531.exception.instantiating.certselector",
1189:                                                    ex);
1190:                                    throw new RuntimeException(ex);
1191:                                } catch (InstantiationException ex) {
1192:                                    log
1193:                                            .log(
1194:                                                    Level.SEVERE,
1195:                                                    "WSS1531.exception.instantiating.certselector",
1196:                                                    ex);
1197:                                    throw new RuntimeException(ex);
1198:                                } catch (InvocationTargetException ex) {
1199:                                    log
1200:                                            .log(
1201:                                                    Level.SEVERE,
1202:                                                    "WSS1531.exception.instantiating.certselector",
1203:                                                    ex);
1204:                                    throw new RuntimeException(ex);
1205:                                } catch (IllegalAccessException ex) {
1206:                                    log
1207:                                            .log(
1208:                                                    Level.SEVERE,
1209:                                                    "WSS1531.exception.instantiating.certselector",
1210:                                                    ex);
1211:                                    throw new RuntimeException(ex);
1212:                                }
1213:                            } else {
1214:                                try {
1215:                                    selector = (CertSelector) truststoreCertSelectorClass
1216:                                            .newInstance();
1217:                                } catch (InstantiationException ex) {
1218:                                    log
1219:                                            .log(
1220:                                                    Level.SEVERE,
1221:                                                    "WSS1531.exception.instantiating.certselector",
1222:                                                    ex);
1223:                                    throw new RuntimeException(ex);
1224:                                } catch (IllegalAccessException ex) {
1225:                                    log
1226:                                            .log(
1227:                                                    Level.SEVERE,
1228:                                                    "WSS1531.exception.instantiating.certselector",
1229:                                                    ex);
1230:                                    throw new RuntimeException(ex);
1231:                                }
1232:                            }
1233:
1234:                            if (selector != null) {
1235:                                Enumeration aliases = null;
1236:                                try {
1237:                                    aliases = trustStore.aliases();
1238:                                } catch (KeyStoreException ex) {
1239:                                    log.log(Level.SEVERE,
1240:                                            "WSS1526.failedto.getcertificate",
1241:                                            ex);
1242:                                    throw new RuntimeException(ex);
1243:                                }
1244:                                while (aliases.hasMoreElements()) {
1245:                                    String currAlias = (String) aliases
1246:                                            .nextElement();
1247:                                    Certificate this Certificate = null;
1248:                                    try {
1249:                                        this Certificate = trustStore
1250:                                                .getCertificate(currAlias);
1251:                                    } catch (KeyStoreException ex) {
1252:                                        log
1253:                                                .log(
1254:                                                        Level.SEVERE,
1255:                                                        "WSS1526.failedto.getcertificate",
1256:                                                        ex);
1257:                                        throw new RuntimeException(ex);
1258:                                    }
1259:                                    if ((this Certificate instanceof  X509Certificate)
1260:                                            && selector.match(this Certificate)) {
1261:                                        req
1262:                                                .setX509Certificate((X509Certificate) this Certificate);
1263:                                        return;
1264:                                    }
1265:                                }
1266:                            }
1267:
1268:                        } else {
1269:                            //now try dynamic certificate
1270:                            X509Certificate cert = getDynamicCertificate(
1271:                                    context, trustStore);
1272:                            if (cert != null) {
1273:                                req.setX509Certificate(cert);
1274:                                return;
1275:                            }
1276:                            //TODO: remove this code below, this code is not correct anyway
1277:                            Enumeration aliases = null;
1278:                            try {
1279:                                aliases = trustStore.aliases();
1280:                            } catch (KeyStoreException ex) {
1281:                                log.log(Level.SEVERE,
1282:                                        "WSS1526.failedto.getcertificate", ex);
1283:                                throw new RuntimeException(ex);
1284:                            }
1285:                            while (aliases.hasMoreElements()) {
1286:                                currentAlias = (String) aliases.nextElement();
1287:                                if (!"certificate-authority"
1288:                                        .equals(currentAlias)
1289:                                        && !"root".equals(currentAlias)) {
1290:                                    break;
1291:                                } else {
1292:                                    currentAlias = null;
1293:                                }
1294:                            }
1295:                        }
1296:                    }
1297:                }
1298:
1299:                if (trustStore != null && currentAlias != null) {
1300:                    X509Certificate this Certificate = null;
1301:                    try {
1302:                        this Certificate = (X509Certificate) trustStore
1303:                                .getCertificate(currentAlias);
1304:                    } catch (KeyStoreException ex) {
1305:                        log.log(Level.SEVERE,
1306:                                "WSS1526.failedto.getcertificate", ex);
1307:                        throw new RuntimeException(ex);
1308:                    }
1309:                    req.setX509Certificate(this Certificate);
1310:                    return;
1311:                } else {
1312:                    log.log(Level.SEVERE,
1313:                            "WSS1511.failed.locate.peerCertificate");
1314:                    throw new RuntimeException(
1315:                            "An Error occurred while locating PEER Entity certificate in TrustStore");
1316:                }
1317:            }
1318:
1319:            private void getDefaultPrivKeyCert(
1320:                    SignatureKeyCallback.DefaultPrivKeyCertRequest request,
1321:                    Map context) throws IOException {
1322:
1323:                if (keyStore == null)
1324:                    return;
1325:                String uniqueAlias = null;
1326:                try {
1327:                    if (this .myAlias != null) {
1328:                        uniqueAlias = this .myAlias;
1329:                    } else {
1330:                        //if Keystore CertSelector Provided use it
1331:                        //It is actually an AliasSelector for the sake of uniformity with
1332:                        // JSR 196 Callbacks. JSR 196 Callbacks do not allow browsing the
1333:                        // Keystore (although they allow browsing TrustStore)
1334:                        if (this .keystoreCertSelectorClass != null) {
1335:                            AliasSelector selector = null;
1336:                            try {
1337:                                selector = (AliasSelector) this .keystoreCertSelectorClass
1338:                                        .newInstance();
1339:                            } catch (IllegalAccessException ex) {
1340:                                log
1341:                                        .log(
1342:                                                Level.SEVERE,
1343:                                                "WSS1532.exception.instantiating.aliasselector",
1344:                                                ex);
1345:                                throw new RuntimeException(ex);
1346:                            } catch (InstantiationException ex) {
1347:                                log
1348:                                        .log(
1349:                                                Level.SEVERE,
1350:                                                "WSS1532.exception.instantiating.aliasselector",
1351:                                                ex);
1352:                                throw new RuntimeException(ex);
1353:                            }
1354:                            uniqueAlias = selector.select(context);
1355:                        } /*else {*/
1356:                        // if alias selector fails, select a unique private key entry if one exists
1357:                        if (uniqueAlias == null) {
1358:                            Enumeration aliases = keyStore.aliases();
1359:                            while (aliases.hasMoreElements()) {
1360:                                String currentAlias = (String) aliases
1361:                                        .nextElement();
1362:                                if (keyStore.isKeyEntry(currentAlias)) {
1363:                                    Certificate this Certificate = keyStore
1364:                                            .getCertificate(currentAlias);
1365:                                    if (this Certificate != null) {
1366:                                        if (this Certificate instanceof  X509Certificate) {
1367:                                            if (uniqueAlias == null) {
1368:                                                uniqueAlias = currentAlias;
1369:                                            } else {
1370:                                                // Not unique!
1371:                                                uniqueAlias = null;
1372:                                                break;
1373:                                            }
1374:                                        }
1375:                                    }
1376:                                }
1377:                            }
1378:                        }
1379:                    }
1380:                    if (uniqueAlias != null) {
1381:                        //System.out.println("Signing Key Alias=" + uniqueAlias);
1382:                        request.setX509Certificate((X509Certificate) keyStore
1383:                                .getCertificate(uniqueAlias));
1384:                        request.setPrivateKey((PrivateKey) keyStore.getKey(
1385:                                uniqueAlias, this .keyPassword));
1386:                    } else {
1387:                        log.log(Level.SEVERE,
1388:                                "WSS1512.failed.locate.certificate.privatekey");
1389:                        throw new RuntimeException(
1390:                                "An Error occurred while locating default certificate and privateKey in KeyStore");
1391:                    }
1392:                } catch (Exception e) {
1393:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1394:                    throw new RuntimeException(e);
1395:                }
1396:            }
1397:
1398:            private static byte[] getSubjectKeyIdentifier(X509Certificate cert) {
1399:                String SUBJECT_KEY_IDENTIFIER_OID = "2.5.29.14";
1400:                byte[] subjectKeyIdentifier = cert
1401:                        .getExtensionValue(SUBJECT_KEY_IDENTIFIER_OID);
1402:                if (subjectKeyIdentifier == null)
1403:                    return null;
1404:
1405:                try {
1406:                    sun.security.x509.KeyIdentifier keyId = null;
1407:
1408:                    sun.security.util.DerValue derVal = new sun.security.util.DerValue(
1409:                            new sun.security.util.DerInputStream(
1410:                                    subjectKeyIdentifier).getOctetString());
1411:
1412:                    keyId = new sun.security.x509.KeyIdentifier(derVal
1413:                            .getOctetString());
1414:                    return keyId.getIdentifier();
1415:                } catch (NoClassDefFoundError ncde) {
1416:
1417:                    byte[] dest = new byte[subjectKeyIdentifier.length - 4];
1418:                    System.arraycopy(subjectKeyIdentifier, 4, dest, 0,
1419:                            subjectKeyIdentifier.length - 4);
1420:                    return dest;
1421:                } catch (java.io.IOException ex) {
1422:                    //ignore
1423:                    return null;
1424:                }
1425:            }
1426:
1427:            private class DefaultTimestampValidator implements 
1428:                    TimestampValidationCallback.TimestampValidator {
1429:
1430:                public void validate(TimestampValidationCallback.Request request)
1431:                        throws TimestampValidationCallback.TimestampValidationException {
1432:
1433:                    // validate timestamp creation and expiration time.
1434:                    TimestampValidationCallback.UTCTimestampRequest utcTimestampRequest = (TimestampValidationCallback.UTCTimestampRequest) request;
1435:
1436:                    SimpleDateFormat calendarFormatter1 = new SimpleDateFormat(
1437:                            "yyyy-MM-dd'T'HH:mm:ss'Z'");
1438:                    SimpleDateFormat calendarFormatter2 = new SimpleDateFormat(
1439:                            "yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
1440:                    Date created = null;
1441:                    Date expired = null;
1442:
1443:                    try {
1444:                        created = calendarFormatter1.parse(utcTimestampRequest
1445:                                .getCreated());
1446:                        if (utcTimestampRequest.getExpired() != null)
1447:                            expired = calendarFormatter1
1448:                                    .parse(utcTimestampRequest.getExpired());
1449:                    } catch (java.text.ParseException pe) {
1450:                        try {
1451:                            created = calendarFormatter2
1452:                                    .parse(utcTimestampRequest.getCreated());
1453:                            if (utcTimestampRequest.getExpired() != null)
1454:                                expired = calendarFormatter2
1455:                                        .parse(utcTimestampRequest.getExpired());
1456:                        } catch (java.text.ParseException ipe) {
1457:                            log.log(Level.SEVERE,
1458:                                    "WSS1513.exception.validate.timestamp");
1459:                            throw new TimestampValidationCallback.TimestampValidationException(
1460:                                    ipe.getMessage());
1461:                        }
1462:                    }
1463:
1464:                    long maxClockSkewLocal = utcTimestampRequest
1465:                            .getMaxClockSkew();
1466:                    if (mcs != null && maxClockSkewG >= 0) {
1467:                        maxClockSkewLocal = maxClockSkewG;
1468:                    }
1469:                    long tsfLocal = utcTimestampRequest
1470:                            .getTimestampFreshnessLimit();
1471:                    if (tfl != null && timestampFreshnessLimitG > 0) {
1472:                        tsfLocal = timestampFreshnessLimitG;
1473:                    }
1474:
1475:                    // validate creation time
1476:                    validateCreationTime(created, maxClockSkewLocal, tsfLocal);
1477:
1478:                    // validate expiration time
1479:                    if (expired != null)
1480:                        validateExpirationTime(expired, maxClockSkewLocal,
1481:                                tsfLocal);
1482:                }
1483:            }
1484:
1485:            public void validateExpirationTime(Date expires, long maxClockSkew,
1486:                    long timestampFreshnessLimit)
1487:                    throws TimestampValidationCallback.TimestampValidationException {
1488:
1489:                //System.out.println("Validate Expiration time called");
1490:                Date currentTime = getGMTDateWithSkewAdjusted(
1491:                        new GregorianCalendar(), maxClockSkew, false);
1492:                if (expires.before(currentTime)) {
1493:                    log.log(Level.SEVERE, "WSS1514.error.aheadCurrentTime");
1494:                    throw new TimestampValidationCallback.TimestampValidationException(
1495:                            "The current time is ahead of the expiration time in Timestamp");
1496:                }
1497:            }
1498:
1499:            public void validateCreationTime(Date created, long maxClockSkew,
1500:                    long timestampFreshnessLimit)
1501:                    throws TimestampValidationCallback.TimestampValidationException {
1502:
1503:                //System.out.println("Validate Creation time called");
1504:                Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew,
1505:                        timestampFreshnessLimit);
1506:
1507:                if (created.before(current)) {
1508:                    log.log(Level.SEVERE, "WSS1515.error.currentTime");
1509:                    log.log(Level.SEVERE, "Creation time:" + created);
1510:                    log.log(Level.SEVERE, "Current time:" + current);
1511:                    throw new TimestampValidationCallback.TimestampValidationException(
1512:                            "The creation time is older than "
1513:                                    + " currenttime - timestamp-freshness-limit - max-clock-skew");
1514:                }
1515:
1516:                Date currentTime = getGMTDateWithSkewAdjusted(
1517:                        new GregorianCalendar(), maxClockSkew, true);
1518:                if (currentTime.before(created)) {
1519:                    log.log(Level.SEVERE,
1520:                            "WSS1516.error.creationAheadCurrent.time");
1521:                    throw new TimestampValidationCallback.TimestampValidationException(
1522:                            "The creation time is ahead of the current time.");
1523:                }
1524:            }
1525:
1526:            private static Date getFreshnessAndSkewAdjustedDate(
1527:                    long maxClockSkew, long timestampFreshnessLimit) {
1528:                Calendar c = new GregorianCalendar();
1529:                long offset = c.get(Calendar.ZONE_OFFSET);
1530:                if (c.getTimeZone().inDaylightTime(c.getTime())) {
1531:                    offset += c.getTimeZone().getDSTSavings();
1532:                }
1533:                long beforeTime = c.getTimeInMillis();
1534:                long currentTime = beforeTime - offset;
1535:
1536:                long adjustedTime = currentTime - maxClockSkew
1537:                        - timestampFreshnessLimit;
1538:                c.setTimeInMillis(adjustedTime);
1539:
1540:                return c.getTime();
1541:            }
1542:
1543:            private static Date getGMTDateWithSkewAdjusted(Calendar c,
1544:                    long maxClockSkew, boolean addSkew) {
1545:                long offset = c.get(Calendar.ZONE_OFFSET);
1546:                if (c.getTimeZone().inDaylightTime(c.getTime())) {
1547:                    offset += c.getTimeZone().getDSTSavings();
1548:                }
1549:                long beforeTime = c.getTimeInMillis();
1550:                long currentTime = beforeTime - offset;
1551:
1552:                if (addSkew)
1553:                    currentTime = currentTime + maxClockSkew;
1554:                else
1555:                    currentTime = currentTime - maxClockSkew;
1556:
1557:                c.setTimeInMillis(currentTime);
1558:                return c.getTime();
1559:            }
1560:
1561:            private class X509CertificateValidatorImpl implements 
1562:                    CertificateValidationCallback.CertificateValidator {
1563:
1564:                public boolean validate(X509Certificate certificate)
1565:                        throws CertificateValidationCallback.CertificateValidationException {
1566:
1567:                    if (isSelfCert(certificate)) {
1568:                        return true;
1569:                    }
1570:
1571:                    try {
1572:                        certificate.checkValidity();
1573:                    } catch (CertificateExpiredException e) {
1574:                        log.log(Level.SEVERE, "WSS1517.X509.expired", e);
1575:                        throw new CertificateValidationCallback.CertificateValidationException(
1576:                                "X509Certificate Expired", e);
1577:                    } catch (CertificateNotYetValidException e) {
1578:                        log.log(Level.SEVERE, "WSS1527.X509.notValid", e);
1579:                        throw new CertificateValidationCallback.CertificateValidationException(
1580:                                "X509Certificate's Validity Failed", e);
1581:                    }
1582:
1583:                    X509CertSelector certSelector = new X509CertSelector();
1584:                    certSelector.setCertificate(certificate);
1585:
1586:                    PKIXBuilderParameters parameters;
1587:                    CertPathBuilder builder;
1588:                    try {
1589:                        parameters = new PKIXBuilderParameters(trustStore,
1590:                                certSelector);
1591:                        parameters.setRevocationEnabled(revocationEnabled);
1592:                        if (certStore != null) {
1593:                            parameters.addCertStore(certStore);
1594:                        }
1595:                        builder = CertPathBuilder.getInstance("PKIX");
1596:                    } catch (Exception e) {
1597:                        log.log(Level.SEVERE,
1598:                                "WSS1518.failedto.validate.certificate", e);
1599:                        throw new CertificateValidationCallback.CertificateValidationException(
1600:                                e.getMessage(), e);
1601:                    }
1602:
1603:                    try {
1604:                        builder.build(parameters);
1605:                    } catch (Exception e) {
1606:                        log.log(Level.SEVERE,
1607:                                "WSS1518.failedto.validate.certificate", e);
1608:                        throw new CertificateValidationCallback.CertificateValidationException(
1609:                                e.getMessage(), e);
1610:                    }
1611:                    return true;
1612:                }
1613:
1614:                private boolean isSelfCert(X509Certificate cert)
1615:                        throws CertificateValidationCallback.CertificateValidationException {
1616:                    try {
1617:                        Enumeration aliases = keyStore.aliases();
1618:                        while (aliases.hasMoreElements()) {
1619:                            String alias = (String) aliases.nextElement();
1620:                            if (keyStore.isKeyEntry(alias)) {
1621:                                X509Certificate x509Cert = (X509Certificate) keyStore
1622:                                        .getCertificate(alias);
1623:                                if (x509Cert != null) {
1624:                                    if (x509Cert.equals(cert))
1625:                                        return true;
1626:                                }
1627:                            }
1628:                        }
1629:                        return false;
1630:                    } catch (Exception e) {
1631:                        log.log(Level.SEVERE,
1632:                                "WSS1518.failedto.validate.certificate", e);
1633:                        throw new CertificateValidationCallback.CertificateValidationException(
1634:                                e.getMessage(), e);
1635:                    }
1636:                }
1637:            }
1638:
1639:            private X509Certificate getCertificateFromTrustStoreForThumbprint(
1640:                    byte[] ski) throws IOException {
1641:
1642:                try {
1643:                    if (trustStore == null && certStore == null)
1644:                        return null;
1645:                    if (trustStore != null) {
1646:                        Enumeration aliases = trustStore.aliases();
1647:                        while (aliases.hasMoreElements()) {
1648:                            String alias = (String) aliases.nextElement();
1649:                            Certificate cert = trustStore.getCertificate(alias);
1650:                            if (cert == null || !"X.509".equals(cert.getType())) {
1651:                                continue;
1652:                            }
1653:                            X509Certificate x509Cert = (X509Certificate) cert;
1654:                            byte[] keyId = getThumbprintIdentifier(x509Cert);
1655:                            if (keyId == null) {
1656:                                // Cert does not contain a key identifier
1657:                                continue;
1658:                            }
1659:                            if (Arrays.equals(ski, keyId)) {
1660:                                return x509Cert;
1661:                            }
1662:                        }
1663:                    }
1664:                } catch (Exception e) {
1665:                    log.log(Level.SEVERE, "WSS1526.failedto.getcertificate", e);
1666:                    throw new RuntimeException(e);
1667:                }
1668:                //now search in CertStore if present
1669:                if (this .certStore != null) {
1670:                    CertSelector selector = new DigestCertSelector(ski,
1671:                            MessageConstants.SHA1_DIGEST);
1672:                    Collection certs = null;
1673:                    try {
1674:                        certs = certStore.getCertificates(selector);
1675:                    } catch (CertStoreException ex) {
1676:                        log.log(Level.SEVERE,
1677:                                "WSS1530.exception.in.certstore.lookup", ex);
1678:                        throw new RuntimeException(ex);
1679:                    }
1680:                    if (certs.size() > 0) {
1681:                        return (X509Certificate) certs.iterator().next();
1682:                    }
1683:                }
1684:
1685:                return null;
1686:            }
1687:
1688:            public static byte[] getThumbprintIdentifier(X509Certificate cert)
1689:                    throws XWSSecurityException {
1690:                byte[] thumbPrintIdentifier = null;
1691:
1692:                try {
1693:                    thumbPrintIdentifier = MessageDigest.getInstance("SHA-1")
1694:                            .digest(cert.getEncoded());
1695:                } catch (NoSuchAlgorithmException ex) {
1696:                    log.log(Level.SEVERE, "WSS1519.no.digest.algorithm");
1697:                    throw new XWSSecurityException(
1698:                            "Digest algorithm SHA-1 not found");
1699:                } catch (CertificateEncodingException ex) {
1700:                    log.log(Level.SEVERE, "WSS1520.error.getting.rawContent");
1701:                    throw new XWSSecurityException(
1702:                            "Error while getting certificate's raw content");
1703:                }
1704:                return thumbPrintIdentifier;
1705:            }
1706:
1707:            public PrivateKey getPrivateKeyForThumbprint(byte[] ski)
1708:                    throws IOException {
1709:
1710:                try {
1711:                    if (keyStore == null)
1712:                        return null;
1713:                    Enumeration aliases = keyStore.aliases();
1714:                    while (aliases.hasMoreElements()) {
1715:                        String alias = (String) aliases.nextElement();
1716:                        if (!keyStore.isKeyEntry(alias))
1717:                            continue;
1718:                        Certificate cert = keyStore.getCertificate(alias);
1719:                        if (cert == null || !"X.509".equals(cert.getType())) {
1720:                            continue;
1721:                        }
1722:                        X509Certificate x509Cert = (X509Certificate) cert;
1723:                        byte[] keyId = getThumbprintIdentifier(x509Cert);
1724:                        if (keyId == null) {
1725:                            // Cert does not contain a key identifier
1726:                            continue;
1727:                        }
1728:                        if (Arrays.equals(ski, keyId)) {
1729:                            // Asuumed key password same as the keystore password
1730:                            return (PrivateKey) keyStore.getKey(alias,
1731:                                    this .keyPassword);
1732:                        }
1733:                    }
1734:                } catch (Exception e) {
1735:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1736:                    throw new RuntimeException(e);
1737:                }
1738:                return null;
1739:            }
1740:
1741:            private Class loadClassSilent(String classname) {
1742:                if (classname == null) {
1743:                    return null;
1744:                }
1745:                Class ret = null;
1746:                ClassLoader loader = Thread.currentThread()
1747:                        .getContextClassLoader();
1748:                if (loader != null) {
1749:                    try {
1750:                        ret = loader.loadClass(classname);
1751:                        return ret;
1752:                    } catch (ClassNotFoundException e) {
1753:                        // ignore
1754:                        if (log.isLoggable(Level.FINE)) {
1755:                            log.log(Level.FINE,
1756:                                    "LoadClassSilent: could not load class "
1757:                                            + classname, e);
1758:                        }
1759:                    }
1760:                }
1761:                // if context classloader didnt work, try this
1762:                loader = this .getClass().getClassLoader();
1763:                if (loader != null) {
1764:                    try {
1765:                        ret = loader.loadClass(classname);
1766:                        return ret;
1767:                    } catch (ClassNotFoundException e) {
1768:                        // ignore
1769:                        if (log.isLoggable(Level.FINE)) {
1770:                            log.log(Level.FINE,
1771:                                    "LoadClassSilent: could not load class "
1772:                                            + classname, e);
1773:                        }
1774:                    }
1775:                }
1776:                return null;
1777:            }
1778:
1779:            private Class loadClass(String classname)
1780:                    throws XWSSecurityException {
1781:                if (classname == null) {
1782:                    return null;
1783:                }
1784:                Class ret = null;
1785:                ClassLoader loader = Thread.currentThread()
1786:                        .getContextClassLoader();
1787:                if (loader != null) {
1788:                    try {
1789:                        ret = loader.loadClass(classname);
1790:                        return ret;
1791:                    } catch (ClassNotFoundException e) {
1792:                        // ignore
1793:                        if (log.isLoggable(Level.FINE)) {
1794:                            log.log(Level.FINE,
1795:                                    "LoadClass: could not load class "
1796:                                            + classname, e);
1797:                        }
1798:                    }
1799:                }
1800:                // if context classloader didnt work, try this
1801:                loader = this .getClass().getClassLoader();
1802:                try {
1803:                    ret = loader.loadClass(classname);
1804:                    return ret;
1805:                } catch (ClassNotFoundException e) {
1806:                    // ignore
1807:                    if (log.isLoggable(Level.FINE)) {
1808:                        log.log(Level.FINE, "LoadClass: could not load class "
1809:                                + classname, e);
1810:                    }
1811:                }
1812:                log.log(Level.SEVERE, "WSS1521.error.getting.userClass");
1813:                throw new XWSSecurityException("Could not find User Class "
1814:                        + classname);
1815:            }
1816:
1817:            private long toLong(String lng) throws XWSSecurityException {
1818:                if (lng == null) {
1819:                    return 0;
1820:                }
1821:                Long ret = 0L;
1822:                ret = Long.valueOf(lng);
1823:                try {
1824:                    ret = Long.valueOf(lng);
1825:                } catch (Exception e) {
1826:                    log.log(Level.SEVERE, "WSS1522.error.getting.longValue");
1827:                    throw new XWSSecurityException(e);
1828:                }
1829:                return ret;
1830:            }
1831:
1832:            private void initNewInstances() throws XWSSecurityException {
1833:
1834:                try {
1835:
1836:                    if (usernameCbHandler != null) {
1837:                        usernameHandler = (CallbackHandler) usernameCbHandler
1838:                                .newInstance();
1839:                    } else {
1840:                        if (log.isLoggable(Level.FINE)) {
1841:                            log.log(Level.FINE,
1842:                                    "Got NULL for Username Callback Handler");
1843:                        }
1844:                    }
1845:                    if (passwordCbHandler != null) {
1846:                        passwordHandler = (CallbackHandler) passwordCbHandler
1847:                                .newInstance();
1848:                    } else {
1849:                        if (log.isLoggable(Level.FINE)) {
1850:                            log.log(Level.FINE,
1851:                                    "Got NULL for Password Callback Handler");
1852:                        }
1853:                    }
1854:
1855:                    if (samlCbHandler != null) {
1856:                        samlHandler = (CallbackHandler) samlCbHandler
1857:                                .newInstance();
1858:                    }
1859:
1860:                    if (usernameValidator != null) {
1861:                        pwValidator = (PasswordValidationCallback.PasswordValidator) usernameValidator
1862:                                .newInstance();
1863:                    }
1864:
1865:                    if (timestampValidator != null) {
1866:                        tsValidator = (TimestampValidationCallback.TimestampValidator) timestampValidator
1867:                                .newInstance();
1868:                    }
1869:
1870:                    if (samlValidator != null) {
1871:                        sValidator = (SAMLAssertionValidator) samlValidator
1872:                                .newInstance();
1873:                    }
1874:
1875:                    if (certificateValidator != null) {
1876:                        certValidator = (CertificateValidationCallback.CertificateValidator) certificateValidator
1877:                                .newInstance();
1878:                    }
1879:
1880:                    if (this .certstoreCbHandler != null) {
1881:                        this .certstoreHandler = (CallbackHandler) this .certstoreCbHandler
1882:                                .newInstance();
1883:                    }
1884:
1885:                } catch (Exception e) {
1886:                    log
1887:                            .log(
1888:                                    Level.SEVERE,
1889:                                    "WSS1523.error.getting.newInstance.CallbackHandler",
1890:                                    e);
1891:                    throw new XWSSecurityException(e);
1892:                }
1893:                if (this .certstoreHandler != null) {
1894:                    //keep the certstore handy...
1895:                    CertStoreCallback cb = new CertStoreCallback();
1896:                    Callback[] callbacks = new Callback[] { cb };
1897:                    try {
1898:                        this .certstoreHandler.handle(callbacks);
1899:                        this .certStore = cb.getCertStore();
1900:                    } catch (UnsupportedCallbackException ex) {
1901:                        log.log(Level.SEVERE,
1902:                                "WSS1529.exception.in.certstore.callback", ex);
1903:                        throw new XWSSecurityException(ex);
1904:                    } catch (IOException ex) {
1905:                        log.log(Level.SEVERE,
1906:                                "WSS1529.exception.in.certstore.callback", ex);
1907:                        throw new XWSSecurityException(ex);
1908:                    }
1909:                }
1910:
1911:            }
1912:
1913:            private X509Certificate getCertificateFromTrustStoreForSAML(
1914:                    PublicKey pk) throws IOException {
1915:                try {
1916:                    if (trustStore == null && certStore == null)
1917:                        return null;
1918:                    if (trustStore != null) {
1919:                        Enumeration aliases = trustStore.aliases();
1920:                        while (aliases.hasMoreElements()) {
1921:                            String alias = (String) aliases.nextElement();
1922:                            Certificate cert = trustStore.getCertificate(alias);
1923:                            if (cert == null || !"X.509".equals(cert.getType())) {
1924:                                continue;
1925:                            }
1926:                            X509Certificate x509Cert = (X509Certificate) cert;
1927:                            if (x509Cert.getPublicKey().equals(pk)) {
1928:                                return x509Cert;
1929:                            }
1930:                        }
1931:                    }
1932:                } catch (Exception e) {
1933:                    log.log(Level.SEVERE, "WSS1526.failedto.getcertificate", e);
1934:                    throw new RuntimeException(e);
1935:                }
1936:                if (certStore != null) {
1937:                    CertSelector selector = new PublicKeyCertSelector(pk);
1938:                    Collection certs = null;
1939:                    try {
1940:                        certs = certStore.getCertificates(selector);
1941:                    } catch (CertStoreException ex) {
1942:                        log.log(Level.SEVERE,
1943:                                "WSS1530.exception.in.certstore.lookup", ex);
1944:                        throw new RuntimeException(ex);
1945:                    }
1946:                    if (certs.size() > 0) {
1947:                        return (X509Certificate) certs.iterator().next();
1948:                    }
1949:
1950:                }
1951:                return null;
1952:            }
1953:
1954:            private PrivateKey getPrivateKeyFromKeyStore(PublicKey pk)
1955:                    throws IOException {
1956:                try {
1957:                    Enumeration aliases = keyStore.aliases();
1958:                    while (aliases.hasMoreElements()) {
1959:                        String alias = (String) aliases.nextElement();
1960:                        if (!keyStore.isKeyEntry(alias)) {
1961:                            continue;
1962:                        } else {
1963:                            // Just returning the first one here
1964:                            PrivateKey key = (PrivateKey) keyStore.getKey(
1965:                                    alias, this .keyPassword);
1966:                            return key;
1967:                        }
1968:                    }
1969:                } catch (Exception e) {
1970:                    log.log(Level.SEVERE, "WSS1505.failedto.getkey", e);
1971:                    throw new RuntimeException(e);
1972:                }
1973:                return null;
1974:            }
1975:
1976:            private String resolveHome(String url) {
1977:                if (url == null) {
1978:                    return null;
1979:                }
1980:                if (url.startsWith("$WSIT_HOME")) {
1981:                    String wsitHome = System.getProperty("WSIT_HOME");
1982:                    if (wsitHome != null) {
1983:                        String ret = url.replace("$WSIT_HOME", wsitHome);
1984:                        return ret;
1985:                    } else {
1986:                        log
1987:                                .log(Level.SEVERE,
1988:                                        "WSS1524.unableto.resolve.URI.WSIT_HOME.notset");
1989:                        throw new RuntimeException(
1990:                                "The following config URL: "
1991:                                        + url
1992:                                        + " in the WSDL could not be resolved because System Property WSIT_HOME was not set");
1993:                    }
1994:                } else {
1995:                    return url;
1996:                }
1997:            }
1998:
1999:            private void initKeyPassword() {
2000:                //NOTE: this is called only when this.keyPwd is non-null
2001:                // check if this.keyPwd is a CBH
2002:                try {
2003:                    Class cbh = this .loadClassSilent(this .keyPwd);
2004:                    if (cbh != null) {
2005:                        CallbackHandler hdlr = (CallbackHandler) cbh
2006:                                .newInstance();
2007:                        javax.security.auth.callback.PasswordCallback pc = new javax.security.auth.callback.PasswordCallback(
2008:                                "KeyPassword", false);
2009:                        Callback[] cbs = new Callback[] { pc };
2010:                        hdlr.handle(cbs);
2011:                        this .keyPassword = ((javax.security.auth.callback.PasswordCallback) cbs[0])
2012:                                .getPassword();
2013:                    } else {
2014:                        //the user supplied value is a Password for the key alias
2015:                        this .keyPassword = this .keyPwd.toCharArray();
2016:                    }
2017:                } catch (java.lang.InstantiationException ex) {
2018:                    log.log(Level.SEVERE,
2019:                            "WSS1528.failed.initialize.key.password", ex);
2020:                    throw new RuntimeException(ex);
2021:                } catch (java.io.IOException e) {
2022:                    log.log(Level.SEVERE,
2023:                            "WSS1528.failed.initialize.key.password", e);
2024:                    throw new RuntimeException(e);
2025:                } catch (java.lang.IllegalAccessException ie) {
2026:                    log.log(Level.SEVERE,
2027:                            "WSS1528.failed.initialize.key.password", ie);
2028:                    throw new RuntimeException(ie);
2029:                } catch (javax.security.auth.callback.UnsupportedCallbackException ue) {
2030:                    log.log(Level.SEVERE,
2031:                            "WSS1528.failed.initialize.key.password", ue);
2032:                    throw new RuntimeException(ue);
2033:                }
2034:            }
2035:
2036:            private X509Certificate getDynamicCertificate(Map context,
2037:                    KeyStore trustStore) {
2038:
2039:                X509Certificate cert = null;
2040:
2041:                Subject requesterSubject = getRequesterSubject(context);
2042:                if (requesterSubject != null) {
2043:                    Set publicCredentials = requesterSubject
2044:                            .getPublicCredentials();
2045:                    for (Iterator it = publicCredentials.iterator(); it
2046:                            .hasNext();) {
2047:                        Object cred = it.next();
2048:                        if (cred instanceof  java.security.cert.X509Certificate) {
2049:                            cert = (java.security.cert.X509Certificate) cred;
2050:                        }
2051:                    }
2052:                    if (cert != null) {
2053:                        return cert;
2054:                    }
2055:                }
2056:                /*
2057:                String keyId = (String)context.get(MessageConstants.REQUESTER_KEYID);
2058:                String issuerName = (String)context.get(MessageConstants.REQUESTER_ISSUERNAME);
2059:                BigInteger issuerSerial = (BigInteger)context.get(MessageConstants.REQUESTER_SERIAL);
2060:                 
2061:                if (keyId != null) {
2062:                    try {
2063:                        cert = getMatchingCertificate(keyId.getBytes(), trustStore);
2064:                        if (cert != null)
2065:                            return cert;
2066:                    } catch (XWSSecurityException e) {}
2067:                } else if ((issuerName != null) && (issuerSerial != null)) {
2068:                    try {
2069:                        cert = getMatchingCertificate(issuerSerial, issuerName, trustStore);
2070:                        if (cert != null)
2071:                            return cert;
2072:                    } catch (XWSSecurityException e) {}
2073:                } */
2074:                if (log.isLoggable(Level.FINE)) {
2075:                    log
2076:                            .log(Level.FINE,
2077:                                    "Could not locate Incoming Client Certificate in Caller Subject");
2078:                }
2079:
2080:                return null;
2081:            }
2082:
2083:            public Subject getRequesterSubject(final Map context) {
2084:                //return (Subject)context.get(MessageConstants.AUTH_SUBJECT);
2085:                Subject otherPartySubject = (Subject) context
2086:                        .get(MessageConstants.AUTH_SUBJECT);
2087:                if (otherPartySubject != null) {
2088:                    return otherPartySubject;
2089:                }
2090:                otherPartySubject = (Subject) AccessController
2091:                        .doPrivileged(new PrivilegedAction() {
2092:                            public Object run() {
2093:                                Subject otherPartySubj = new Subject();
2094:                                context.put(MessageConstants.AUTH_SUBJECT,
2095:                                        otherPartySubj);
2096:                                return otherPartySubj;
2097:                            }
2098:                        });
2099:                return otherPartySubject;
2100:            }
2101:
2102:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.