com.sun.xml.wss.impl.misc.WSITProviderSecurityEnvironment Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of wsit-impl Show documentation
Show all versions of wsit-impl Show documentation
This module contains the Metro WSIT runtime code.
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/*
* WSITProviderSecurityEnvironment.java
*
* Created on November 12, 2006, 1:29 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.sun.xml.wss.impl.misc;
import com.sun.xml.wss.AliasSelector;
import com.sun.xml.wss.impl.callback.SAMLAssertionValidator;
import java.io.IOException;
import java.security.cert.CertSelector;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.util.Collection;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.message.callback.CertStoreCallback;
import javax.security.auth.message.callback.PasswordValidationCallback;
import javax.security.auth.message.callback.PrivateKeyCallback;
import javax.security.auth.message.callback.SecretKeyCallback;
import javax.security.auth.message.callback.TrustStoreCallback;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.X509CertSelector;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Set;
import java.util.Date;
import java.util.Timer;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.GregorianCalendar;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.x500.X500Principal;
import javax.security.auth.x500.X500PrivateCredential;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.xml.ws.api.server.Container;
import com.sun.xml.ws.security.impl.kerberos.KerberosContext;
import com.sun.xml.ws.security.impl.kerberos.KerberosLogin;
import com.sun.xml.ws.security.opt.impl.util.SOAPUtil;
import com.sun.xml.ws.api.ResourceLoader;
import com.sun.xml.ws.api.server.WSEndpoint;
import com.sun.xml.wss.NonceManager;
import com.sun.xml.wss.ProcessingContext;
import com.sun.xml.wss.RealmAuthenticationAdapter;
import com.sun.xml.wss.impl.MessageConstants;
import com.sun.xml.wss.SecurityEnvironment;
import com.sun.xml.wss.XWSSConstants;
import com.sun.xml.wss.XWSSecurityException;
import com.sun.xml.wss.impl.SecurityHeaderException;
import com.sun.xml.wss.core.Timestamp;
import com.sun.xml.wss.impl.callback.SAMLCallback;
import com.sun.xml.wss.impl.policy.mls.PrivateKeyBinding;
import com.sun.xml.wss.core.reference.X509SubjectKeyIdentifier;
import com.sun.xml.wss.impl.XWSSecurityRuntimeException;
import com.sun.xml.wss.impl.callback.CertificateValidationCallback;
import com.sun.xml.wss.impl.callback.RuntimeProperties;
import com.sun.xml.wss.impl.callback.SAMLValidator;
import com.sun.xml.wss.impl.callback.TimestampValidationCallback;
import com.sun.xml.wss.impl.callback.ValidatorExtension;
import com.sun.xml.wss.saml.Assertion;
//import com.sun.xml.wss.saml.assertion.AuthorityBinding;
import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
import com.sun.xml.wss.impl.configuration.DynamicApplicationContext;
import java.security.AccessController;
import javax.xml.stream.XMLStreamReader;
import javax.xml.ws.BindingProvider;
import org.ietf.jgss.GSSName;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import java.security.PrivilegedAction;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.xml.wss.logging.LogDomainConstants;
import com.sun.xml.wss.logging.LogStringsMessages;
import com.sun.xml.wss.util.XWSSUtil;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.LoginContext;
import org.ietf.jgss.GSSCredential;
/**
*
* @author kumar.jayanti
*/
public class WSITProviderSecurityEnvironment implements SecurityEnvironment {
/* menu of module options - includes algorithm Ids, keystore aliases etc., */
private Map _securityOptions;
/* Callbacks */
private CallbackHandler _handler;
/* Map of aliases-key passwords obtained via Module Options */
//Map aliases_keypwds = null;
// value of the maximum skew between the local times of two
// systems (in milliseconds).
// Keeping it 1 minute.
protected final long MAX_CLOCK_SKEW = MessageConstants.MAX_CLOCK_SKEW;
// milliseconds (set to 5 mins), time for which a timestamp is considered fresh
protected final long TIMESTAMP_FRESHNESS_LIMIT = MessageConstants.TIMESTAMP_FRESHNESS_LIMIT;
/** logger */
protected static final Logger log = Logger.getLogger(
LogDomainConstants.WSS_API_DOMAIN,LogDomainConstants.WSS_API_DOMAIN_BUNDLE);
private static final SimpleDateFormat calendarFormatter1 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private static final SimpleDateFormat calendarFormatter2 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
// Nonce Cache
NonceCache nonceCache = null;
// Nonce clean-up timer
static final boolean USE_DAEMON_THREAD = true;
static final Timer nonceCleanupTimer = new Timer(USE_DAEMON_THREAD);
private String myAlias;
private String keyPwd;
private String peerEntityAlias;
private String myUsername;
private String myPassword;
private String samlCBH;
private String sV;
private Class samlCbHandler;
private CallbackHandler samlHandler= null;
private Class samlValidator;
private SAMLAssertionValidator sValidator;
private String krbLoginModule = null;
private String krbServicePrincipal = null;
private boolean krbCredentialDelegation = false;
private String mcs;
private String tfl;
private String mna;
protected long maxClockSkewG;
protected long timestampFreshnessLimitG;
protected long maxNonceAge = MessageConstants.MAX_NONCE_AGE;
private boolean isAppClient = true;
private X509Certificate selfCertificate = null;
private String certSelectorClassName;
private String crlSelectorClassName;
private Class certSelectorClass;
private Class crlSelectorClass;
protected String revocationEnabledAttr;
protected boolean revocationEnabled = false;
private String keystoreCertSelectorClassName;
private String truststoreCertSelectorClassName;
private Class keystoreCertSelectorClass;
private Class truststoreCertSelectorClass;
private Container container = null;
private String useXWSSCallbacksStr;
private boolean useXWSSCallbacks=false;
private CertificateValidationCallback.CertificateValidator certValidator;
private Class certificateValidator;
private Class usernameValidator;
private Class timestampValidator;
private com.sun.xml.wss.impl.callback.PasswordValidationCallback.PasswordValidator pwValidator;
private TimestampValidationCallback.TimestampValidator tsValidator;
private String jaasLoginModuleForKeystore;
private Subject loginContextSubjectForKeystore;
private String keyStoreCBH;
private CallbackHandler keystoreCbHandlerClass;
/** Creates a new instance of WSITProviderSecurityEnvironment */
@SuppressWarnings("empty-statement")
public WSITProviderSecurityEnvironment(CallbackHandler handler, Map options, Properties configAssertions)
throws XWSSecurityException {
_handler = new PriviledgedHandler(handler);
_securityOptions = options;
if (_securityOptions != null) {
String mo_aliases = (String) _securityOptions.get("ALIASES");
String mo_keypwds = (String) _securityOptions.get("PASSWORDS");
if (mo_aliases != null && mo_keypwds != null) {
StringTokenizer aliases = new StringTokenizer(mo_aliases, " ");
StringTokenizer keypwds = new StringTokenizer(mo_keypwds, " ");
if (aliases.countTokens() != keypwds.countTokens()) {
;
}// log.INFO
//while (aliases.hasMoreElements()) {
// aliases_keypwds.put(aliases.nextToken(), keypwds.nextToken());
//}
}
container = (Container) _securityOptions.get("CONTAINER");
}
//store the relevant config assertions here
this.myAlias = configAssertions.getProperty(DefaultCallbackHandler.MY_ALIAS);
this.keyPwd = configAssertions.getProperty(DefaultCallbackHandler.KEY_PASSWORD);
this.peerEntityAlias = configAssertions.getProperty(DefaultCallbackHandler.PEER_ENTITY_ALIAS);
this.krbLoginModule = configAssertions.getProperty(DefaultCallbackHandler.KRB5_LOGIN_MODULE);
this.krbServicePrincipal = configAssertions.getProperty(DefaultCallbackHandler.KRB5_SERVICE_PRINCIPAL);
this.krbCredentialDelegation = Boolean.valueOf(configAssertions.getProperty(DefaultCallbackHandler.KRB5_CREDENTIAL_DELEGATION));
this.myUsername = configAssertions.getProperty(DefaultCallbackHandler.MY_USERNAME);
this.myPassword = configAssertions.getProperty(DefaultCallbackHandler.MY_PASSWORD);
this.samlCBH = configAssertions.getProperty(DefaultCallbackHandler.SAML_CBH);
if (this.samlCBH != null) {
samlCbHandler = loadClass(samlCBH);
}
if (samlCbHandler != null) {
try {
samlHandler = (CallbackHandler) samlCbHandler.newInstance();
} catch (InstantiationException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0715_EXCEPTION_CREATING_NEWINSTANCE(), ex);
throw new XWSSecurityException(ex);
} catch (IllegalAccessException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0715_EXCEPTION_CREATING_NEWINSTANCE(), ex);
throw new XWSSecurityException(ex);
}
}
sV = configAssertions.getProperty(DefaultCallbackHandler.SAML_VALIDATOR);
if (sV != null) {
samlValidator = loadClass(sV);
}
if (samlValidator != null) {
try {
sValidator = (SAMLAssertionValidator) samlValidator.newInstance();
} catch (InstantiationException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0715_EXCEPTION_CREATING_NEWINSTANCE(), ex);
throw new XWSSecurityException(ex);
} catch (IllegalAccessException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0715_EXCEPTION_CREATING_NEWINSTANCE(), ex);
throw new XWSSecurityException(ex);
}
}
mcs = configAssertions.getProperty(DefaultCallbackHandler.MAX_CLOCK_SKEW_PROPERTY);
tfl = configAssertions.getProperty(DefaultCallbackHandler.TIMESTAMP_FRESHNESS_LIMIT_PROPERTY);
mna = configAssertions.getProperty(DefaultCallbackHandler.MAX_NONCE_AGE_PROPERTY);
revocationEnabledAttr = configAssertions.getProperty(DefaultCallbackHandler.REVOCATION_ENABLED);
if (revocationEnabledAttr != null) {
this.revocationEnabled = Boolean.parseBoolean(revocationEnabledAttr);
}
maxClockSkewG = SecurityUtil.toLong(mcs);
timestampFreshnessLimitG = SecurityUtil.toLong(tfl);
if (mna != null) {
maxNonceAge = SecurityUtil.toLong(mna);
}
useXWSSCallbacksStr = configAssertions.getProperty(DefaultCallbackHandler.USE_XWSS_CALLBACKS);
if (useXWSSCallbacksStr != null) {
this.useXWSSCallbacks = Boolean.parseBoolean(useXWSSCallbacksStr);
}
String cV = configAssertions.getProperty(DefaultCallbackHandler.CERTIFICATE_VALIDATOR);
certificateValidator = loadClass(cV);
String uV = configAssertions.getProperty(DefaultCallbackHandler.USERNAME_VALIDATOR);
String tV = configAssertions.getProperty(DefaultCallbackHandler.TIMESTAMP_VALIDATOR);
usernameValidator = loadClass(uV);
timestampValidator = loadClass(tV);
try {
if (certificateValidator != null) {
certValidator = (CertificateValidationCallback.CertificateValidator) certificateValidator.newInstance();
}
if (usernameValidator != null) {
pwValidator = (com.sun.xml.wss.impl.callback.PasswordValidationCallback.PasswordValidator) usernameValidator.newInstance();
}
if (timestampValidator != null) {
tsValidator = (TimestampValidationCallback.TimestampValidator) timestampValidator.newInstance();
}
} catch (Exception e) {
log.log(Level.SEVERE, com.sun.xml.wss.logging.impl.misc.LogStringsMessages.WSS_1523_ERROR_GETTING_NEW_INSTANCE_CALLBACK_HANDLER(), e);
throw new XWSSecurityException(e);
}
//determine if we are in an AppClient
NameCallback nameCallback = new NameCallback("Username: ");
try {
Callback[] cbs = new Callback[]{nameCallback};
_handler.handle(cbs);
} catch (javax.security.auth.callback.UnsupportedCallbackException e) {
this.isAppClient = false;
} catch (Exception e) {
this.isAppClient = false;
}
this.certSelectorClassName = configAssertions.getProperty(DefaultCallbackHandler.CERTSTORE_CERTSELECTOR);
this.crlSelectorClassName = configAssertions.getProperty(DefaultCallbackHandler.CERTSTORE_CRLSELECTOR);
this.certSelectorClass = loadClass(this.certSelectorClassName);
this.crlSelectorClass = loadClass(this.crlSelectorClassName);
this.keystoreCertSelectorClassName = configAssertions.getProperty(DefaultCallbackHandler.KEYSTORE_CERTSELECTOR);
this.truststoreCertSelectorClassName = configAssertions.getProperty(DefaultCallbackHandler.TRUSTSTORE_CERTSELECTOR);
keystoreCertSelectorClass = loadClass(this.keystoreCertSelectorClassName);
truststoreCertSelectorClass = loadClass(this.truststoreCertSelectorClassName);
jaasLoginModuleForKeystore = configAssertions.getProperty(DefaultCallbackHandler.JAAS_KEYSTORE_LOGIN_MODULE);
keyStoreCBH = configAssertions.getProperty(DefaultCallbackHandler.KEYSTORE_CBH);
loginContextSubjectForKeystore = initJAASKeyStoreLoginModule();
//keep the self certificate handy
// if (_handler != null && this.myAlias != null) {
// try {
// PrivateKeyCallback.Request request =
// new PrivateKeyCallback.AliasRequest(this.myAlias);
// PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
//
// Callback[] callbacks = new Callback[] { pkCallback };
// _handler.handle(callbacks);
// Certificate[] chain = pkCallback.getChain();
// if (chain != null) {
// selfCertificate = (X509Certificate)chain[0];
// }
// } catch (Exception ex) {
// //ignore for now
// }
// }
}
/*
* @throws XWSSecurityException
*/
public PrivateKey getPrivateKey(Map context, String alias)
throws XWSSecurityException {
if (alias == null && context != null) {
Object obj = context.get(XWSSConstants.PRIVATEKEY_PROPERTY);
PrivateKey key = null;
if (obj instanceof PrivateKey) {
key = (PrivateKey) obj;
return key;
}
}
PrivateKey privateKey = null;
try {
PrivateKeyCallback.Request request =
new PrivateKeyCallback.AliasRequest(alias);
PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
callbacks = new Callback[] {props, pkCallback };
} else {
callbacks = new Callback[] { pkCallback };
}
_handler.handle(callbacks);
privateKey = (PrivateKey) pkCallback.getKey();
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback.AliasRequest"),
new Object[] { "PrivateKeyCallback.AliasRequest"});
log.log(Level.SEVERE,LogStringsMessages.WSS_0217_CALLBACKHANDLER_HANDLE_EXCEPTION_LOG(),e);
throw new XWSSecurityException(e);
}
if (privateKey == null) {
log.log(Level.SEVERE,LogStringsMessages.WSS_0222_CANNOT_LOCATE_PRIVKEY(alias), new Object[] {alias});
throw new XWSSecurityException(
"Unable to locate private key for the alias: " + alias);
}
return privateKey;
}
/*
* Retrieves the PrivateKey corresponding to the cert
* with the given KeyIdentifier value
*
* @param keyIdentifier an Opaque identifier indicating
* the X509 certificate
*
* @return the PrivateKey corresponding to the cert
* with the given KeyIdentifier value
*
* @throws XWSSecurityException
*/
public PrivateKey getPrivateKey(Map context, byte[] keyIdentifier)
throws XWSSecurityException {
if (context != null) {
Object obj = context.get(XWSSConstants.PRIVATEKEY_PROPERTY);
PrivateKey key = null;
if (obj instanceof PrivateKey) {
key = (PrivateKey) obj;
Object cert = context.get(XWSSConstants.CERTIFICATE_PROPERTY);
if (XWSSUtil.matchesProgrammaticInfo(cert, keyIdentifier, MessageConstants.KEY_INDETIFIER_TYPE) != null) {
return key;
}
}
}
/*
use PrivateKeyCallback
*/
try {
Subject subject = getSubject(context);
if (subject != null) {
Set set = subject.getPrivateCredentials(X500PrivateCredential.class);
if (set != null) {
Iterator it = set.iterator();
while (it.hasNext()) {
X500PrivateCredential cred = (X500PrivateCredential)it.next();
if (matchesKeyIdentifier(Base64.decode(keyIdentifier),
cred.getCertificate()))
return cred.getPrivateKey();
}
}
}
PrivateKeyCallback.Request request =
new PrivateKeyCallback.SubjectKeyIDRequest(keyIdentifier);
PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
callbacks = new Callback[] {props, pkCallback };
} else {
callbacks = new Callback[] { pkCallback };
}
_handler.handle(callbacks);
return pkCallback.getKey();
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback.SubjectKeyIDRequest"),
new Object[] { "PrivateKeyCallback.SubjectKeyIDRequest"});
log.log(Level.SEVERE,LogStringsMessages.WSS_0217_CALLBACKHANDLER_HANDLE_EXCEPTION_LOG(),e);
throw new XWSSecurityException(e);
}
}
/*
* Retrieves the PrivateKey corresponding to the given cert
*
* @param cert an X509 certificate
*
* @return the PrivateKey corresponding to the cert
*
* @throws XWSSecurityException
*/
public PrivateKey getPrivateKey(Map context, X509Certificate cert)
throws XWSSecurityException {
/*
use PrivateKeyCallback
*/
try {
if (context != null) {
Object obj = context.get(XWSSConstants.CERTIFICATE_PROPERTY);
if (cert != null && cert.equals(obj)) {
Object key = context.get(XWSSConstants.PRIVATEKEY_PROPERTY);
if (key != null && key instanceof PrivateKey) {
return (PrivateKey) key;
}
}
}
Subject subject = getSubject(context);
if (subject != null) {
Set set = subject.getPrivateCredentials(X500PrivateCredential.class);
if (set != null) {
String issuerName = com.sun.org.apache.xml.internal.security.utils.RFC2253Parser.normalize(
cert.getIssuerDN().getName());
Iterator it = set.iterator();
while (it.hasNext()) {
X500PrivateCredential cred = (X500PrivateCredential)it.next();
X509Certificate x509Cert = cred.getCertificate();
BigInteger serialNo = x509Cert.getSerialNumber();
String currentIssuerName =
com.sun.org.apache.xml.internal.security.utils.RFC2253Parser.normalize(
x509Cert.getIssuerDN().getName());
if (serialNo.equals(cert.getSerialNumber()) &&
currentIssuerName.equals(issuerName)) {
return cred.getPrivateKey();
}
}
}
}
PrivateKeyCallback.Request request =
new PrivateKeyCallback.IssuerSerialNumRequest(
cert.getIssuerX500Principal(), cert.getSerialNumber());
PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
callbacks = new Callback[] {props, pkCallback };
} else {
callbacks = new Callback[] { pkCallback };
}
_handler.handle(callbacks);
return pkCallback.getKey();
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback.IssuerSerialNumRequest"),
new Object[] { "PrivateKeyCallback.IssuerSerialNumRequest"});
log.log(Level.SEVERE,LogStringsMessages.WSS_0217_CALLBACKHANDLER_HANDLE_EXCEPTION_LOG(),e);
throw new XWSSecurityException(e);
}
}
/*
* Retrieves the matching PrivateKey corresponding to cert whose
* SerialNumber and IssuerName are given
*
* @param serialNumber X509Certificate SerialNumber
* @param issuerName X509Certificate IssuerName
*
* @return PrivateKey
*
* @throws XWSSecurityException
*/
public PrivateKey getPrivateKey(Map context, BigInteger serialNumber, String issuerName)
throws XWSSecurityException {
/*
use PrivateKeyCallback
*/
try {
if (context != null) {
Object obj = context.get(XWSSConstants.CERTIFICATE_PROPERTY);
if (XWSSUtil.matchesProgrammaticInfo(obj, serialNumber, issuerName) != null) {
PrivateKey key = XWSSUtil.getProgrammaticPrivateKey(context);
if (key != null) {
return key;
}
}
}
Subject subject = getSubject(context);
if (subject != null) {
Set set = subject.getPrivateCredentials(X500PrivateCredential.class);
if (set != null) {
Iterator it = set.iterator();
while (it.hasNext()) {
X500PrivateCredential cred = (X500PrivateCredential)it.next();
X509Certificate x509Cert = cred.getCertificate();
BigInteger serialNo = x509Cert.getSerialNumber();
String currentIssuerName =
com.sun.org.apache.xml.internal.security.utils.RFC2253Parser.normalize(
x509Cert.getIssuerDN().getName());
if (serialNo.equals(serialNumber) &&
currentIssuerName.equals(issuerName)) {
return cred.getPrivateKey();
}
}
}
}
PrivateKeyCallback.Request request =
new PrivateKeyCallback.IssuerSerialNumRequest(
new X500Principal(issuerName), serialNumber);
PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
callbacks = new Callback[]{props, pkCallback};
} else {
callbacks = new Callback[]{pkCallback};
}
_handler.handle(callbacks);
return pkCallback.getKey();
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback.IssuerSerialNumRequest"),
new Object[] { "PrivateKeyCallback.IssuerSerialNumRequest"});
log.log(Level.SEVERE,LogStringsMessages.WSS_0217_CALLBACKHANDLER_HANDLE_EXCEPTION_LOG(),e);
throw new XWSSecurityException(e);
}
}
/**
* Retrieves a reasonable default value for the current user's
* X509Certificate if one exists.
*
* @return the default certificate for the current user
*
* @param keyIdentifier an Opaque identifier indicating
* the X509 certificate.
* @throws XWSSecurityException
*/
public X509Certificate getDefaultCertificate(Map context)
throws XWSSecurityException {
/*
use PrivateKeyCallback to get the
certChain - return the first certificate
*/
if (context != null) {
Object obj = context.get(XWSSConstants.CERTIFICATE_PROPERTY);
if (obj != null && obj instanceof X509Certificate) {
return (X509Certificate) obj;
}
}
Subject subject = getSubject(context);
if (subject != null) {
Set set = subject.getPublicCredentials(X509Certificate.class);
if (set != null && set.size() == 1)
return ((X509Certificate)(set.toArray())[0]);
}
if (this.myAlias != null || this.keystoreCertSelectorClass != null) {
return this.getCertificate(context, this.myAlias, true);
}
PrivateKeyCallback pkCallback = new PrivateKeyCallback(null);
Callback[] _callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
_callbacks = new Callback[]{props, pkCallback};
} else {
_callbacks = new Callback[]{pkCallback};
}
try {
_handler.handle(_callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback with null argument"),
new Object[] { "PrivateKeyCallback with null argument"});
log.log(Level.SEVERE,LogStringsMessages.WSS_0217_CALLBACKHANDLER_HANDLE_EXCEPTION_LOG(),e);
throw new XWSSecurityException(e);
}
Certificate[] chain = pkCallback.getChain();
if (chain == null) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0296_NULL_CHAIN_CERT());
throw new XWSSecurityException(
"Empty certificate chain returned by PrivateKeyCallback");
}
return (X509Certificate)chain[0];
}
/**
* Authenticate the user against a list of known username-password
* pairs.
*
* @param username
* @param password
* @return true if the username-password pair is valid
*/
public boolean authenticateUser(Map context,String username, String password)
throws XWSSecurityException {
if (pwValidator != null) {
com.sun.xml.wss.impl.callback.PasswordValidationCallback.PlainTextPasswordRequest request =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback.PlainTextPasswordRequest(username, password);
com.sun.xml.wss.impl.callback.PasswordValidationCallback passwordValidationCallback =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback(request);
ProcessingContext.copy(passwordValidationCallback.getRuntimeProperties(), context);
passwordValidationCallback.setValidator(pwValidator);
return passwordValidationCallback.getResult();
}
/*
use PasswordValidationCallback
*/
char[] pwd = (password == null) ? null : password.toCharArray();
PasswordValidationCallback pvCallback = new PasswordValidationCallback(
this.getRequesterSubject(context),username, pwd);
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties xwsscb = new RuntimeProperties(context);
callbacks = new Callback[]{xwsscb, pvCallback};
} else {
callbacks = new Callback[]{pvCallback};
}
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION( "Authenticating User against list of Known username-password pairs"),
new Object[] { "Authenticating User against list of Known username-password pairs"});
throw new XWSSecurityException(e);
}
// zero the password
if (pwd != null)
pvCallback.clearPassword();
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,"Username Authentication done for " + username);
}
return pvCallback.getResult();
}
/**
* Authenticate the user against a list of known usernames
* @param username
* @return password if the username is valid
*/
public String authenticateUser(Map context,String username)
throws XWSSecurityException {
String password = null;
if (pwValidator != null) {
com.sun.xml.wss.impl.callback.PasswordValidationCallback.DerivedKeyPasswordRequest request =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback.DerivedKeyPasswordRequest(username);
com.sun.xml.wss.impl.callback.PasswordValidationCallback passwordValidationCallback =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback(request);
ProcessingContext.copy(passwordValidationCallback.getRuntimeProperties(), context);
if(pwValidator != null && pwValidator instanceof com.sun.xml.wss.impl.callback.PasswordValidationCallback.DerivedKeyPasswordValidator){
((com.sun.xml.wss.impl.callback.PasswordValidationCallback.DerivedKeyPasswordValidator)pwValidator).setPassword(request);
passwordValidationCallback.setValidator(pwValidator);
}
passwordValidationCallback.getResult();
password = request.getPassword();
}
return password;
}
/**
* Authenticate the user given the password digest.
*
* @param username
* @param passwordDigest
* @param nonce
* @param created
* @return true if the password digest is valid
*/
public boolean authenticateUser(
Map context,
String username,
String passwordDigest,
String nonce,
String created)
throws XWSSecurityException {
boolean result = false;
if (pwValidator != null) {
com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest request =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, created);
com.sun.xml.wss.impl.callback.PasswordValidationCallback passwordValidationCallback =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback(request);
ProcessingContext.copy(passwordValidationCallback.getRuntimeProperties(), context);
if(pwValidator != null && pwValidator instanceof com.sun.xml.wss.impl.callback.PasswordValidationCallback.WsitDigestPasswordValidator){
((com.sun.xml.wss.impl.callback.PasswordValidationCallback.WsitDigestPasswordValidator)pwValidator).setPassword(request);
passwordValidationCallback.setValidator(pwValidator);
}
return passwordValidationCallback.getResult();
}
if (this.useXWSSCallbacks) {
com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest request =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest(
username, passwordDigest, nonce, created);
com.sun.xml.wss.impl.callback.PasswordValidationCallback passwordValidationCallback =
new com.sun.xml.wss.impl.callback.PasswordValidationCallback(request);
ProcessingContext.copy(passwordValidationCallback.getRuntimeProperties(), context);
Callback[] callbacks = new Callback[]{passwordValidationCallback};
try {
_handler.handle(callbacks);
if (passwordValidationCallback.getValidator() != null) {
result = passwordValidationCallback.getResult();
if (result == true) {
CallerPrincipalCallback pvCallback = new CallerPrincipalCallback(getSubject(context), username);
callbacks = new Callback[]{pvCallback};
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("CallerPrincipalCallback"),
new Object[]{"CallerPrincipalCallback"});
throw new XWSSecurityRuntimeException(e);
}
}
return result;
}
} catch (UnsupportedCallbackException ex) {
//ignore if they don't support and try other routes
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "The Supplied JMAC CallbackHandler does not support com.sun.xml.wss.impl.callback.PasswordValidationCallback.DigestPasswordRequest");
}
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0225_FAILED_PASSWORD_VALIDATION_CALLBACK(), e);
throw new XWSSecurityException(e);
}
}
try {
RealmAuthenticationAdapter adapter = RealmAuthenticationAdapter.newInstance(null);
if (adapter != null) {
result = adapter.authenticate(getSubject(context), username, passwordDigest, nonce, created, context);
} else {
log.log(Level.SEVERE, LogStringsMessages.WSS_0295_PASSWORD_VAL_NOT_CONFIG_USERNAME_VAL());
throw new XWSSecurityException("Error: No PasswordValidator Configured for UsernameToken Validation");
}
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0225_FAILED_PASSWORD_VALIDATION_CALLBACK(), e);
throw new XWSSecurityException(e);
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Username Authentication done for " + username);
}
return result;
}
/**
* Validate an X509Certificate.
* @return true, if the cert is a valid one, false o/w.
* @throws XWSSecurityException
* if there is some problem during validation.
*/
public boolean validateCertificate(X509Certificate cert, Map context)
throws XWSSecurityException {
if (this.certValidator != null) {
CertificateValidationCallback certValCallback = new CertificateValidationCallback(cert, context);
certValCallback.setValidator(certValidator);
certValCallback.setRevocationEnabled(revocationEnabled);
return certValCallback.getResult();
}
if (this.useXWSSCallbacks) {
CertificateValidationCallback certValCallback = new CertificateValidationCallback(cert, context);
certValCallback.setRevocationEnabled(revocationEnabled);
Callback[] callbacks = new Callback[]{certValCallback};
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0223_FAILED_CERTIFICATE_VALIDATION());
throw SOAPUtil.newSOAPFaultException(
MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
"Certificate validation failed",
e);
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Certificate Validation called on certificate " + cert.getSubjectDN());
}
return certValCallback.getResult();
}
/*
use TrustStore and CertStore
*/
try {
cert.checkValidity();
} catch (CertificateExpiredException e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0298_X_509_EXPIRED(), e);
throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
"X509Certificate Expired", e);
} catch (CertificateNotYetValidException e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0299_X_509_NOT_VALID(), e);
throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
"X509Certificate not yet valid", e);
}
// for self-signed certificate
if(cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal())){
if(isTrustedSelfSigned(cert)){
return true;
}else{
log.log(Level.SEVERE, com.sun.xml.wss.logging.impl.misc.LogStringsMessages.WSS_1533_X_509_SELF_SIGNED_CERTIFICATE_NOT_VALID());
throw new XWSSecurityException("Validation of self signed certificate failed");
}
}
//check keyUsage
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(cert);
PKIXBuilderParameters parameters;
CertPathValidator certPathValidator = null;
CertPath certPath = null;
List certChainList = new ArrayList();
boolean caFound = false;
Principal certChainIssuer = null;
int noOfEntriesInTrustStore = 0;
boolean isIssuerCertMatched = false;
try {
Callback[] callbacks = null;
CertStoreCallback csCallback = null;
TrustStoreCallback tsCallback = null;
if (tsCallback == null && csCallback == null) {
csCallback = new CertStoreCallback();
tsCallback = new TrustStoreCallback();
callbacks = new Callback[] { csCallback, tsCallback };
} else if (csCallback == null) {
csCallback = new CertStoreCallback();
callbacks = new Callback[] { csCallback };
} else if (tsCallback == null) {
tsCallback = new TrustStoreCallback();
callbacks = new Callback[] { tsCallback };
}
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("Validate an X509Certificate"),
new Object[] { "Validate an X509Certificate"});
throw new XWSSecurityException(e);
}
Certificate[] certChain = null;
String certAlias = tsCallback.getTrustStore().getCertificateAlias(cert);
if(certAlias!= null){
certChain = tsCallback.getTrustStore().getCertificateChain(certAlias);
}
if(certChain == null){
certChainList.add(cert);
certChainIssuer = cert.getIssuerX500Principal();
noOfEntriesInTrustStore = tsCallback.getTrustStore().size();
}else{
certChainList = Arrays.asList(certChain);
}
while(!caFound && noOfEntriesInTrustStore-- != 0 && certChain == null){
Enumeration aliases = tsCallback.getTrustStore().aliases();
while (aliases.hasMoreElements()){
String alias = (String) aliases.nextElement();
Certificate certificate = tsCallback.getTrustStore().getCertificate(alias);
if (certificate == null || !"X.509".equals(certificate.getType()) || certChainList.contains(certificate)) {
continue;
}
X509Certificate x509Cert = (X509Certificate) certificate;
if(certChainIssuer.equals(x509Cert.getSubjectX500Principal())){
certChainList.add(certificate);
if(x509Cert.getSubjectX500Principal().equals(x509Cert.getIssuerX500Principal())){
caFound = true;
break;
}else{
certChainIssuer = x509Cert.getIssuerDN();
if(!isIssuerCertMatched){
isIssuerCertMatched = true;
}
}
}else{
continue;
}
}
if(!caFound){
if(!isIssuerCertMatched){
break;
}else{
isIssuerCertMatched = false;
}
}
}
try{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certPath = cf.generateCertPath(certChainList);
certPathValidator = CertPathValidator.getInstance("PKIX");
}catch(Exception e){
log.log(Level.SEVERE, com.sun.xml.wss.logging.impl.misc.LogStringsMessages.WSS_1518_FAILEDTO_VALIDATE_CERTIFICATE(), e);
throw new CertificateValidationCallback.CertificateValidationException(e.getMessage(), e);
}
parameters = new PKIXBuilderParameters(tsCallback.getTrustStore(), certSelector);
parameters.setRevocationEnabled(revocationEnabled);
parameters.addCertStore(csCallback.getCertStore());
} catch (Exception e) {
// Log Message
log.log(Level.SEVERE, LogStringsMessages.WSS_0223_FAILED_CERTIFICATE_VALIDATION(), e);
throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
e.getMessage(), e);
}
try {
certPathValidator.validate(certPath, parameters);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0223_FAILED_CERTIFICATE_VALIDATION(), e);
throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
e.getMessage(), e);
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,"Certificate Validation called on certificate " + cert.getSubjectDN());
}
return true;
}
private Subject initJAASKeyStoreLoginModule() {
if (jaasLoginModuleForKeystore == null) {
return null;
}
LoginContext lc = null;
try {
if (keyStoreCBH != null) {
keystoreCbHandlerClass = (CallbackHandler) loadClass(keyStoreCBH).newInstance();
lc = new LoginContext(jaasLoginModuleForKeystore, keystoreCbHandlerClass);
}else {
lc = new LoginContext(jaasLoginModuleForKeystore);
}
lc.login();
return lc.getSubject();
} catch (InstantiationException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0817_KEYSTORE_LOGIN_MODULE_LOGIN_ERROR(), ex);
throw new XWSSecurityRuntimeException(ex);
} catch (IllegalAccessException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0817_KEYSTORE_LOGIN_MODULE_LOGIN_ERROR(), ex);
throw new XWSSecurityRuntimeException(ex);
} catch (XWSSecurityException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0817_KEYSTORE_LOGIN_MODULE_LOGIN_ERROR(), ex);
throw new XWSSecurityRuntimeException(ex);
} catch (LoginException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0817_KEYSTORE_LOGIN_MODULE_LOGIN_ERROR(), ex);
throw new XWSSecurityRuntimeException(ex);
}
}
private boolean isTrustedSelfSigned(X509Certificate cert) throws XWSSecurityException {
try {
Callback[] callbacks = null;
CertStoreCallback csCallback = null;
TrustStoreCallback tsCallback = null;
if (tsCallback == null && csCallback == null) {
csCallback = new CertStoreCallback();
tsCallback = new TrustStoreCallback();
callbacks = new Callback[]{csCallback, tsCallback};
} else if (csCallback == null) {
csCallback = new CertStoreCallback();
callbacks = new Callback[]{csCallback};
} else if (tsCallback == null) {
tsCallback = new TrustStoreCallback();
callbacks = new Callback[]{tsCallback};
}
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("Validate an X509Certificate"),
new Object[]{"Validate an X509Certificate"});
throw new XWSSecurityException(e);
}
if (tsCallback.getTrustStore() == null) {
return false;
}
Enumeration aliases = tsCallback.getTrustStore().aliases();
while (aliases.hasMoreElements()) {
String alias = (String) aliases.nextElement();
Certificate certificate = tsCallback.getTrustStore().getCertificate(alias);
if (certificate == null || !"X.509".equals(certificate.getType())) {
continue;
}
X509Certificate x509Cert = (X509Certificate) certificate;
if (x509Cert != null && x509Cert.equals(cert)) {
return true;
}
}
return false;
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0223_FAILED_CERTIFICATE_VALIDATION(), e);
throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
e.getMessage(), e);
}
}
/**
* @param keyIdMatch
* KeyIdentifier to search for
* @return the matching Certificate
*/
public X509Certificate getMatchingCertificate(Map context, byte[] keyIdMatch)
throws XWSSecurityException {
Subject subject = getSubject(context);
if (subject != null) {
Set set = subject.getPrivateCredentials(X500PrivateCredential.class);
if (set != null) {
Iterator it = set.iterator();
while (it.hasNext()) {
X500PrivateCredential cred = (X500PrivateCredential)it.next();
X509Certificate cert = cred.getCertificate();
if (matchesKeyIdentifier(keyIdMatch, cert))
return cert;
}
}
}
PrivateKeyCallback.Request request = new PrivateKeyCallback.SubjectKeyIDRequest(
keyIdMatch);
PrivateKeyCallback pkCallback = new PrivateKeyCallback(request);
CertStoreCallback csCallback = new CertStoreCallback();
TrustStoreCallback tsCallback = new TrustStoreCallback();
Callback[] callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
callbacks = new Callback[]{props, pkCallback, tsCallback, csCallback};
} else {
callbacks = new Callback[]{pkCallback, tsCallback, csCallback};
}
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION("PrivateKeyCallback.SubjectKeyIDRequest"),
new Object[] { "PrivateKeyCallback.SubjectKeyIDRequest"});
throw new XWSSecurityException(e);
}
Certificate[] chain = pkCallback.getChain();
if (chain != null) {
if (chain.length == 1) {
return (X509Certificate)chain[0];
}
for (int i=0; i 0) {
cert = (X509Certificate)certs.iterator().next();
}
}
}
}
if (cert == null && this.truststoreCertSelectorClass != null) {
TrustStoreCallback tsCallback = new TrustStoreCallback();
Callback[] _callbacks = null;
if (this.useXWSSCallbacks) {
RuntimeProperties props = new RuntimeProperties(context);
_callbacks = new Callback[]{props, tsCallback};
} else {
_callbacks = new Callback[]{tsCallback};
}
try {
_handler.handle(_callbacks);
} catch (IOException ex) {
log.log(Level.SEVERE,LogStringsMessages.WSS_0221_CANNOT_LOCATE_CERT(alias), new Object[] {alias});
throw new XWSSecurityException(ex);
} catch (UnsupportedCallbackException ex) {
log.log(Level.SEVERE,LogStringsMessages.WSS_0221_CANNOT_LOCATE_CERT(alias), new Object[] {alias});
throw new XWSSecurityException(ex);
}
KeyStore trustStore = tsCallback.getTrustStore();
if (trustStore != null) {
if (this.truststoreCertSelectorClass != null) {
CertSelector selector = XWSSUtil.getCertSelector(truststoreCertSelectorClass, context);
if (selector != null) {
Enumeration aliases=null;
try {
aliases = trustStore.aliases();
} catch (KeyStoreException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0813_FAILEDTO_GETCERTIFICATE(), ex);
throw new RuntimeException(ex);
}
while (aliases.hasMoreElements()) {
String currAlias = (String) aliases.nextElement();
Certificate thisCertificate = null;
try {
thisCertificate = trustStore.getCertificate(currAlias);
} catch (KeyStoreException ex) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0813_FAILEDTO_GETCERTIFICATE(), ex);
throw new RuntimeException(ex);
}
if ((thisCertificate instanceof X509Certificate)
&& selector.match(thisCertificate)) {
return (X509Certificate)thisCertificate;
}
}
}
}
}
}
if (cert == null) {
cert = getDynamicCertificate(context);
}
}
}
if (cert == null) {
log.log(Level.SEVERE,LogStringsMessages.WSS_0221_CANNOT_LOCATE_CERT(actualAlias));
throw new XWSSecurityException(
"Unable to locate certificate for the alias '" + actualAlias + "'");
}
return cert;
}
private boolean isMyCert(X509Certificate certificate, Map context) {
try {
X509Certificate cert = getDefaultCertificate(context);
if (cert != null && cert.equals(certificate)) {
return true;
}
} catch (XWSSecurityException ex) {
//ignore
}
return false;
}
private Class loadUsingResourceLoader(String classname) {
Class ret = null;
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Entered loadUsingResourceLoader to load class.." + classname);
}
if (container != null) {
// find the ResourceLoader implementation
final ResourceLoader loader = container.getSPI(ResourceLoader.class);
if (loader != null) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Obtained Non null ResourceLoader instance....");
}
try {
// JCAP's SPI implementation will return the directory from where the class(es) can be loaded
final URL classpathUrl = loader.getResource(classname);
// load the class using the URL
ClassLoader parent = this.getClass().getClassLoader();
URLClassLoader classloader = URLClassLoader.newInstance(new URL[]{classpathUrl}, parent);
ret = classloader.loadClass(classname);
return ret;
} catch (ClassNotFoundException ex) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Failed load class using ResourceLoader instance....", ex);
}
} catch (MalformedURLException e) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Failed load class using ResourceLoader instance....", e);
}
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Failed to obtain ResourceLoader instance....");
}
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Failed to obtain \"Container\" for getting ResourceLoader SPI ....");
}
}
return null;
}
private boolean matchesKeyIdentifier(
byte[] keyIdMatch,
X509Certificate x509Cert) throws XWSSecurityException {
byte[] keyId = X509SubjectKeyIdentifier.getSubjectKeyIdentifier(x509Cert);
if (keyId == null) {
// Cert does not contain a key identifier
return false;
}
if (Arrays.equals(keyIdMatch, keyId)) {
return true;
}
return false;
}
private boolean matchesThumbPrint(
byte[] keyIdMatch,
X509Certificate x509Cert) throws XWSSecurityException {
byte[] keyId = XWSSUtil.getThumbprintIdentifier(x509Cert);
if (keyId == null) {
// Cert does not contain a key identifier
return false;
}
if (Arrays.equals(keyIdMatch, keyId)) {
return true;
}
return false;
}
private X509Certificate getMatchingCertificate(
byte[] keyIdMatch,
KeyStore kStore)
throws XWSSecurityException {
if (kStore == null) {
return null;
}
try {
Enumeration enum1 = kStore.aliases();
while (enum1.hasMoreElements()) {
String alias = (String) enum1.nextElement();
Certificate cert = kStore.getCertificate(alias);
if (cert == null || !"X.509".equals(cert.getType())) {
continue;
}
X509Certificate x509Cert = (X509Certificate) cert;
byte[] keyId = X509SubjectKeyIdentifier.getSubjectKeyIdentifier(x509Cert);
if (keyId == null) {
// Cert does not contain a key identifier
continue;
}
if (Arrays.equals(keyIdMatch, keyId)) {
return x509Cert;
}
}
} catch (KeyStoreException kEx) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0706_NO_MATCHING_CERT(keyIdMatch),
new Object[] { keyIdMatch });
throw new XWSSecurityException(
"No Matching Certificate for :"
+ new String(keyIdMatch) + " found in KeyStore.", kEx);
}
return null;
}
private X509Certificate getMatchingCertificate(
byte[] keyIdMatch,
KeyStore kStore,
String valueType)
throws XWSSecurityException {
if (MessageConstants.KEY_INDETIFIER_TYPE.equals(valueType)){
return getMatchingCertificate(keyIdMatch, kStore);
}
if (!MessageConstants.THUMB_PRINT_TYPE.equals(valueType)) {
throw new XWSSecurityException(
"Internal Error : Unsupported Valuetype :"
+ valueType + " passed to getMatchingCertificate()");
}
// now handle thumbprint here
if (kStore == null) {
return null;
}
try {
Enumeration enum1 = kStore.aliases();
while (enum1.hasMoreElements()) {
String alias = (String) enum1.nextElement();
Certificate cert = kStore.getCertificate(alias);
if (cert == null || !"X.509".equals(cert.getType())) {
continue;
}
X509Certificate x509Cert = (X509Certificate) cert;
byte[] keyId = XWSSUtil.getThumbprintIdentifier(x509Cert);
if (Arrays.equals(keyIdMatch, keyId)) {
return x509Cert;
}
}
} catch (KeyStoreException kEx) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0706_NO_MATCHING_CERT(keyIdMatch),
new Object[] { keyIdMatch });
throw new XWSSecurityException(
"No Matching Certificate for :"
+ new String(keyIdMatch) + " found in KeyStore.", kEx);
}
return null;
}
private boolean matchesIssuerSerialAndName(
BigInteger serialNumberMatch,
String issuerNameMatch,
X509Certificate x509Cert) {
BigInteger serialNumber = x509Cert.getSerialNumber();
String issuerName =
com.sun.org.apache.xml.internal.security.utils.RFC2253Parser.normalize(
x509Cert.getIssuerDN().getName());
if (serialNumber.equals(serialNumberMatch)
&& issuerName.equals(issuerNameMatch)) {
return true;
}
return false;
}
private X509Certificate getMatchingCertificate(
BigInteger serialNumber,
String issuerName,
KeyStore kStore)
throws XWSSecurityException {
if (kStore == null) {
return null;
}
try {
Enumeration enum1 = kStore.aliases();
while (enum1.hasMoreElements()) {
String alias = (String) enum1.nextElement();
Certificate cert = kStore.getCertificate(alias);
if (cert == null || !"X.509".equals(cert.getType())) {
continue;
}
X509Certificate x509Cert = (X509Certificate) cert;
BigInteger serialNo = x509Cert.getSerialNumber();
String currentIssuerName =
com.sun.org.apache.xml.internal.security.utils.RFC2253Parser.normalize(
x509Cert.getIssuerDN().getName());
if (serialNo.equals(serialNumber) &&
currentIssuerName.equals(issuerName)) {
return x509Cert;
}
}
} catch (KeyStoreException kEx) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0706_NO_MATCHING_CERT(issuerName + " : " + serialNumber),
new Object[] { issuerName + " : " + serialNumber });
throw new XWSSecurityException(
"No Matching Certificate for :"
+ issuerName + " : " + serialNumber + " found in KeyStore.", kEx);
}
return null;
}
private X509Certificate getMatchingCertificate(
PublicKey publicKey,
KeyStore kStore)
throws XWSSecurityException {
if (kStore == null) {
return null;
}
try {
Enumeration enum1 = kStore.aliases();
while (enum1.hasMoreElements()) {
String alias = (String) enum1.nextElement();
Certificate cert = kStore.getCertificate(alias);
if (cert == null || !"X.509".equals(cert.getType())) {
continue;
}
X509Certificate x509Cert = (X509Certificate) cert;
if (x509Cert.getPublicKey().equals(publicKey))
return x509Cert;
}
} catch (KeyStoreException kEx) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0706_NO_MATCHING_CERT(publicKey),
new Object[] { publicKey });
throw new XWSSecurityException(
"No Matching Certificate for :"
+ publicKey + " found in KeyStore.", kEx);
}
return null;
}
public void updateOtherPartySubject(
Subject subject,
String username,
String password) {
CallerPrincipalCallback pvCallback = new CallerPrincipalCallback(subject, username);
Callback[] callbacks = new Callback[] { pvCallback };
try {
_handler.handle(callbacks);
} catch (Exception e) {
log.log(Level.SEVERE, LogStringsMessages.WSS_0216_CALLBACKHANDLER_HANDLE_EXCEPTION( "CallerPrincipalCallback"),
new Object[] { "CallerPrincipalCallback"});
throw new XWSSecurityRuntimeException(e);
}
}
public void updateOtherPartySubject(
final Subject subject,
final X509Certificate cert) {
Principal principal = cert.getSubjectX500Principal();
AccessController.doPrivileged(
new PrivilegedAction