0001: /*
0002: * $Id: DefaultSecurityEnvironmentImpl.java,v 1.27 2007/09/13 12:42:21 kumarjayanti 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.ProcessingContext;
0030: import com.sun.xml.wss.RealmAuthenticationAdapter;
0031: import java.math.BigInteger;
0032: import java.security.Key;
0033: import java.security.Principal;
0034: import java.security.PrivateKey;
0035: import java.security.PublicKey;
0036: import java.security.cert.X509Certificate;
0037: import java.text.SimpleDateFormat;
0038: import java.util.Calendar;
0039: import java.util.Date;
0040: import java.util.GregorianCalendar;
0041: import java.util.Properties;
0042: import java.util.Timer;
0043: import java.util.Map;
0044: import java.util.logging.Level;
0045: import java.util.logging.Logger;
0046: import java.security.AccessController;
0047: import java.security.PrivilegedAction;
0048: import javax.crypto.SecretKey;
0049: import javax.security.auth.Subject;
0050: import javax.security.auth.callback.Callback;
0051: import javax.security.auth.callback.CallbackHandler;
0052: import javax.security.auth.callback.UnsupportedCallbackException;
0053: import javax.security.auth.x500.X500Principal;
0054: import javax.xml.namespace.QName;
0055: import com.sun.xml.wss.core.Timestamp;
0056: import com.sun.xml.wss.impl.FilterProcessingContext;
0057: import com.sun.xml.wss.logging.LogDomainConstants;
0058: import com.sun.xml.wss.impl.MessageConstants;
0059: import com.sun.xml.wss.XWSSecurityException;
0060: import com.sun.xml.wss.impl.WssSoapFaultException;
0061: import com.sun.xml.wss.SecurityEnvironment;
0062: import com.sun.xml.wss.impl.SecurableSoapMessage;
0063: import com.sun.xml.wss.impl.callback.PasswordCallback;
0064: import com.sun.xml.wss.impl.callback.PasswordValidationCallback;
0065: import com.sun.xml.wss.impl.callback.UsernameCallback;
0066: import com.sun.xml.wss.impl.callback.SignatureKeyCallback;
0067: import com.sun.xml.wss.impl.callback.EncryptionKeyCallback;
0068: import com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback;
0069: import com.sun.xml.wss.impl.callback.DecryptionKeyCallback;
0070: import com.sun.xml.wss.impl.callback.CertificateValidationCallback;
0071: import com.sun.xml.wss.impl.callback.DynamicPolicyCallback;
0072: import com.sun.xml.wss.impl.callback.TimestampValidationCallback;
0073: import com.sun.xml.wss.saml.Assertion;
0074: import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0075: import com.sun.xml.wss.impl.configuration.DynamicApplicationContext;
0076: import javax.xml.stream.XMLStreamReader;
0077: import org.w3c.dom.Element;
0078: import org.w3c.dom.Document;
0079:
0080: //TODO: support PrefixNamespaceMappingCallback
0081: public class DefaultSecurityEnvironmentImpl implements
0082: SecurityEnvironment {
0083:
0084: static final boolean USE_DAEMON_THREAD = true;
0085: static final Timer nonceCleanupTimer = new Timer(USE_DAEMON_THREAD);
0086:
0087: // Zone offset
0088: private static final long offset;
0089:
0090: static {
0091: Calendar c = new GregorianCalendar();
0092: long calculatedOffset = c.get(Calendar.ZONE_OFFSET);
0093: if (c.getTimeZone().inDaylightTime(c.getTime())) {
0094: calculatedOffset += c.getTimeZone().getDSTSavings();
0095: }
0096: offset = calculatedOffset;
0097: }
0098:
0099: // Nonce Cache
0100: private NonceCache nonceCache = null;
0101:
0102: /** logger */
0103: protected static final Logger log = Logger.getLogger(
0104: LogDomainConstants.WSS_API_DOMAIN,
0105: LogDomainConstants.WSS_API_DOMAIN_BUNDLE);
0106:
0107: // milliseconds (set to 5 mins), time for which a timestamp is considered fresh
0108: private final SimpleDateFormat calendarFormatter1 = new SimpleDateFormat(
0109: "yyyy-MM-dd'T'HH:mm:ss'Z'");
0110: private final SimpleDateFormat calendarFormatter2 = new SimpleDateFormat(
0111: "yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
0112:
0113: private CallbackHandler callbackHandler = null;
0114: private boolean isDefaultHandler = false;
0115:
0116: private X509Certificate selfCertificate = null;
0117: private Properties configAssertions = null;
0118:
0119: public DefaultSecurityEnvironmentImpl(CallbackHandler cHandler) {
0120: callbackHandler = cHandler;
0121: if (callbackHandler instanceof DefaultCallbackHandler) {
0122: isDefaultHandler = true;
0123: }
0124: // keep the self certificate handy
0125: if (callbackHandler != null) {
0126: try {
0127: X509Certificate defaultCert = null;
0128: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0129: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0130: privKeyRequest);
0131: Callback[] callbacks = new Callback[] { sigKeyCallback };
0132: callbackHandler.handle(callbacks);
0133: selfCertificate = privKeyRequest.getX509Certificate();
0134: } catch (Exception e) {
0135: //ignore for now
0136: }
0137: }
0138: }
0139:
0140: public DefaultSecurityEnvironmentImpl(CallbackHandler cHandler,
0141: Properties confAssertions) {
0142: this .configAssertions = confAssertions;
0143: callbackHandler = cHandler;
0144: if (callbackHandler instanceof DefaultCallbackHandler) {
0145: isDefaultHandler = true;
0146: }
0147: //store the relevant config assertions here
0148: String myAlias = configAssertions
0149: .getProperty(DefaultCallbackHandler.MY_ALIAS);
0150: // keep the self certificate handy
0151: if (callbackHandler != null && myAlias != null) {
0152: try {
0153: X509Certificate defaultCert = null;
0154: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0155: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0156: privKeyRequest);
0157: Callback[] callbacks = new Callback[] { sigKeyCallback };
0158: callbackHandler.handle(callbacks);
0159: selfCertificate = privKeyRequest.getX509Certificate();
0160: } catch (Exception e) {
0161: //ignore for now
0162: }
0163: }
0164: }
0165:
0166: /*
0167: * Applicable only for the signing case
0168: */
0169: public X509Certificate getDefaultCertificate(Map context)
0170: throws XWSSecurityException {
0171:
0172: X509Certificate defaultCert = null;
0173:
0174: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0175: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0176: privKeyRequest);
0177: //we want to give all runtime properties to be used by CertSelectors
0178: if (context != null /*&& !isDefaultHandler*/) {
0179: ProcessingContext.copy(sigKeyCallback
0180: .getRuntimeProperties(), context);
0181: }
0182: Callback[] callbacks = new Callback[] { sigKeyCallback };
0183: try {
0184: callbackHandler.handle(callbacks);
0185: } catch (Exception e) {
0186: log
0187: .log(
0188: Level.SEVERE,
0189: "WSS0216.callbackhandler.handle.exception",
0190: new Object[] { "SignatureKeyCallback.DefaultPrivKeyCertRequest" });
0191: log.log(Level.SEVERE,
0192: "WSS0217.callbackhandler.handle.exception.log", e);
0193: throw new XWSSecurityException(e);
0194: }
0195: defaultCert = privKeyRequest.getX509Certificate();
0196:
0197: if (defaultCert == null) {
0198: log.log(Level.SEVERE, "WSS0218.cannot.locate.default.cert");
0199: throw new XWSSecurityException(
0200: "Unable to locate a default certificate");
0201: }
0202: return defaultCert;
0203: }
0204:
0205: public SignatureKeyCallback.PrivKeyCertRequest getDefaultPrivKeyCertRequest(
0206: Map context) throws XWSSecurityException {
0207:
0208: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0209: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0210: privKeyRequest);
0211: //we want all runtime props to be available to certSelectors
0212: //if (!isDefaultHandler) {
0213: ProcessingContext.copy(sigKeyCallback.getRuntimeProperties(),
0214: context);
0215: //}
0216: Callback[] callbacks = new Callback[] { sigKeyCallback };
0217: try {
0218: callbackHandler.handle(callbacks);
0219: } catch (Exception e) {
0220: log
0221: .log(
0222: Level.SEVERE,
0223: "WSS0216.callbackhandler.handle.exception",
0224: new Object[] { "SignatureKeyCallback.DefaultPrivKeyCertRequest" });
0225: log.log(Level.SEVERE,
0226: "WSS0217.callbackhandler.handle.exception.log", e);
0227: throw new XWSSecurityException(e);
0228: }
0229: return privKeyRequest;
0230: }
0231:
0232: public SignatureKeyCallback.AliasPrivKeyCertRequest getAliasPrivKeyCertRequest(
0233: String certIdentifier) throws XWSSecurityException {
0234:
0235: SignatureKeyCallback.AliasPrivKeyCertRequest request = new SignatureKeyCallback.AliasPrivKeyCertRequest(
0236: certIdentifier);
0237:
0238: SignatureKeyCallback sigCallback = new SignatureKeyCallback(
0239: request);
0240: Callback[] callback = new Callback[] { sigCallback };
0241: try {
0242: callbackHandler.handle(callback);
0243: } catch (Exception e) {
0244: log
0245: .log(
0246: Level.SEVERE,
0247: "WSS0216.callbackhandler.handle.exception",
0248: new Object[] { "SignatureKeyCallback.AliasPrivKeyCertRequest" });
0249: log.log(Level.SEVERE,
0250: "WSS0217.callbackhandler.handle.exception.log", e);
0251: throw new XWSSecurityException(e);
0252: }
0253: return request;
0254: }
0255:
0256: public PrivateKey getDefaultPrivateKey(Map context)
0257: throws XWSSecurityException {
0258:
0259: PrivateKey defaultPrivKey = null;
0260:
0261: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
0262: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0263: privKeyRequest);
0264: //we want to give all runtime props to CertSelector(s)
0265: //if (!isDefaultHandler) {
0266: ProcessingContext.copy(sigKeyCallback.getRuntimeProperties(),
0267: context);
0268: //}
0269: Callback[] callbacks = new Callback[] { sigKeyCallback };
0270: try {
0271: callbackHandler.handle(callbacks);
0272: } catch (Exception e) {
0273: log
0274: .log(
0275: Level.SEVERE,
0276: "WSS0216.callbackhandler.handle.exception",
0277: new Object[] { "SignatureKeyCallback.DefaultPrivKeyCertRequest" });
0278: log.log(Level.SEVERE,
0279: "WSS0217.callbackhandler.handle.exception.log", e);
0280: throw new XWSSecurityException(e);
0281: }
0282: defaultPrivKey = privKeyRequest.getPrivateKey();
0283:
0284: if (defaultPrivKey == null) {
0285: log.log(Level.SEVERE,
0286: "WSS0219.cannot.locate.default.privkey");
0287: throw new XWSSecurityException(
0288: "Unable to locate a default certificate");
0289: }
0290: return defaultPrivKey;
0291: }
0292:
0293: public SecretKey getSecretKey(Map context, String alias,
0294: boolean encryptMode) throws XWSSecurityException {
0295:
0296: SecretKey symmetricKey = null;
0297:
0298: if (encryptMode) {
0299: EncryptionKeyCallback.SymmetricKeyRequest symmKeyRequest = new EncryptionKeyCallback.AliasSymmetricKeyRequest(
0300: alias);
0301: EncryptionKeyCallback encKeyCallback = new EncryptionKeyCallback(
0302: symmKeyRequest);
0303: if (!isDefaultHandler) {
0304: ProcessingContext.copy(encKeyCallback
0305: .getRuntimeProperties(), context);
0306: }
0307: Callback[] callbacks = new Callback[] { encKeyCallback };
0308: try {
0309: callbackHandler.handle(callbacks);
0310: } catch (Exception e) {
0311: log
0312: .log(
0313: Level.SEVERE,
0314: "WSS0216.callbackhandler.handle.exception",
0315: new Object[] { "EncryptionKeyCallback.AliasSymmetricKeyRequest" });
0316: log.log(Level.SEVERE,
0317: "WSS0217.callbackhandler.handle.exception.log",
0318: e);
0319: throw new XWSSecurityException(e);
0320: }
0321: symmetricKey = symmKeyRequest.getSymmetricKey();
0322: } else {
0323: DecryptionKeyCallback.SymmetricKeyRequest symmKeyRequest = new DecryptionKeyCallback.AliasSymmetricKeyRequest(
0324: alias);
0325: DecryptionKeyCallback decryptKeyCallback = new DecryptionKeyCallback(
0326: symmKeyRequest);
0327: if (!isDefaultHandler) {
0328: ProcessingContext.copy(decryptKeyCallback
0329: .getRuntimeProperties(), context);
0330: }
0331: Callback[] callbacks = new Callback[] { decryptKeyCallback };
0332: try {
0333: callbackHandler.handle(callbacks);
0334: } catch (Exception e) {
0335: log
0336: .log(
0337: Level.SEVERE,
0338: "WSS0216.callbackhandler.handle.exception",
0339: new Object[] { "DecryptionKeyCallback.AliasSymmetricKeyRequest" });
0340: log.log(Level.SEVERE,
0341: "WSS0217.callbackhandler.handle.exception.log",
0342: e);
0343: throw new XWSSecurityException(e);
0344: }
0345: symmetricKey = symmKeyRequest.getSymmetricKey();
0346: }
0347:
0348: if (symmetricKey == null) {
0349: log.log(Level.SEVERE,
0350: "WSS0220.cannot.locate.symmetrickey.for.decrypt");
0351: throw new XWSSecurityException(
0352: "Could not locate the symmetric key for alias '"
0353: + alias + "'");
0354: }
0355: return symmetricKey;
0356: }
0357:
0358: public X509Certificate getCertificate(Map context, String alias,
0359: boolean forSigning) throws XWSSecurityException {
0360:
0361: X509Certificate cert = null;
0362:
0363: if (((alias == null) || ("".equals(alias)) && forSigning))
0364: return getDefaultCertificate(context);
0365:
0366: if (forSigning) {
0367: SignatureKeyCallback.PrivKeyCertRequest certRequest = new SignatureKeyCallback.AliasPrivKeyCertRequest(
0368: alias);
0369: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0370: certRequest);
0371: if (!isDefaultHandler) {
0372: ProcessingContext.copy(sigKeyCallback
0373: .getRuntimeProperties(), context);
0374: }
0375: Callback[] callbacks = new Callback[] { sigKeyCallback };
0376: try {
0377: callbackHandler.handle(callbacks);
0378: } catch (Exception e) {
0379: log
0380: .log(
0381: Level.SEVERE,
0382: "WSS0216.callbackhandler.handle.exception",
0383: new Object[] { "SignatureKeyCallback.AliasPrivKeyCertRequest" });
0384: log.log(Level.SEVERE,
0385: "WSS0217.callbackhandler.handle.exception.log",
0386: e);
0387: throw new XWSSecurityException(e);
0388: }
0389: cert = certRequest.getX509Certificate();
0390: } else {
0391: EncryptionKeyCallback.X509CertificateRequest certRequest = new EncryptionKeyCallback.AliasX509CertificateRequest(
0392: alias);
0393: EncryptionKeyCallback encKeyCallback = new EncryptionKeyCallback(
0394: certRequest);
0395: //incase of EncryptionKeyCallback.AliasX509Request we need all runtime, properties
0396: //so we can pass them to CertSelector(s) if any...
0397: //if (!isDefaultHandler) {
0398: ProcessingContext.copy(encKeyCallback
0399: .getRuntimeProperties(), context);
0400: //} else {
0401: // encKeyCallback.getRuntimeProperties().
0402: // put(MessageConstants.AUTH_SUBJECT, context.get(MessageConstants.AUTH_SUBJECT));
0403: //}
0404: Callback[] callbacks = new Callback[] { encKeyCallback };
0405: try {
0406: callbackHandler.handle(callbacks);
0407: } catch (Exception e) {
0408: log
0409: .log(
0410: Level.SEVERE,
0411: "WSS0216.callbackhandler.handle.exception",
0412: new Object[] { "EncryptionKeyCallback.AliasX509CertificateRequest" });
0413: log.log(Level.SEVERE,
0414: "WSS0217.callbackhandler.handle.exception.log",
0415: e);
0416: throw new XWSSecurityException(e);
0417: }
0418: cert = certRequest.getX509Certificate();
0419: }
0420:
0421: if (cert == null) {
0422: String val = forSigning ? "Signature" : "Key Ecnryption";
0423: log.log(Level.SEVERE, "WSS0221.cannot.locate.cert",
0424: new Object[] { val });
0425: throw new XWSSecurityException(
0426: "Unable to locate certificate for the alias '"
0427: + alias + "'");
0428: }
0429: return cert;
0430: }
0431:
0432: public X509Certificate getCertificate(Map context,
0433: PublicKey publicKey, boolean forSign)
0434: throws XWSSecurityException {
0435: if (forSign) {
0436: SignatureVerificationKeyCallback.PublicKeyBasedRequest pubKeyReq = new SignatureVerificationKeyCallback.PublicKeyBasedRequest(
0437: publicKey);
0438: SignatureVerificationKeyCallback verifyKeyCallback = new SignatureVerificationKeyCallback(
0439: pubKeyReq);
0440: if (!isDefaultHandler) {
0441: ProcessingContext.copy(verifyKeyCallback
0442: .getRuntimeProperties(), context);
0443: }
0444: Callback[] callbacks = new Callback[] { verifyKeyCallback };
0445: try {
0446: callbackHandler.handle(callbacks);
0447: } catch (UnsupportedCallbackException e1) {
0448: //ignore;
0449: } catch (Exception e) {
0450: log
0451: .log(
0452: Level.SEVERE,
0453: "WSS0216.callbackhandler.handle.exception",
0454: new Object[] { "SignatureVerificationKeyCallback.PublicKeyBasedRequest" });
0455: log.log(Level.SEVERE,
0456: "WSS0217.callbackhandler.handle.exception.log",
0457: e);
0458: throw new XWSSecurityException(e);
0459: }
0460: return pubKeyReq.getX509Certificate();
0461: } else {
0462: EncryptionKeyCallback.PublicKeyBasedRequest pubKeyReq = new EncryptionKeyCallback.PublicKeyBasedRequest(
0463: publicKey);
0464: EncryptionKeyCallback encCallback = new EncryptionKeyCallback(
0465: pubKeyReq);
0466: if (!isDefaultHandler) {
0467: ProcessingContext.copy(encCallback
0468: .getRuntimeProperties(), context);
0469: }
0470: Callback[] callbacks = new Callback[] { encCallback };
0471: try {
0472: callbackHandler.handle(callbacks);
0473: } catch (UnsupportedCallbackException e1) {
0474: //ignore;
0475: } catch (Exception e) {
0476: log
0477: .log(
0478: Level.SEVERE,
0479: "WSS0216.callbackhandler.handle.exception",
0480: new Object[] { "EncryptionKeyCallback.PublicKeyBasedRequest" });
0481: log.log(Level.SEVERE,
0482: "WSS0217.callbackhandler.handle.exception.log",
0483: e);
0484: throw new XWSSecurityException(e);
0485: }
0486: return pubKeyReq.getX509Certificate();
0487: }
0488: }
0489:
0490: public PrivateKey getPrivateKey(Map context, String alias)
0491: throws XWSSecurityException {
0492:
0493: PrivateKey privKey = null;
0494:
0495: if (alias == null)
0496: return getDefaultPrivateKey(context);
0497:
0498: SignatureKeyCallback.PrivKeyCertRequest privKeyRequest = new SignatureKeyCallback.AliasPrivKeyCertRequest(
0499: alias);
0500: SignatureKeyCallback sigKeyCallback = new SignatureKeyCallback(
0501: privKeyRequest);
0502: if (!isDefaultHandler) {
0503: ProcessingContext.copy(sigKeyCallback
0504: .getRuntimeProperties(), context);
0505: }
0506: Callback[] callbacks = new Callback[] { sigKeyCallback };
0507: try {
0508: callbackHandler.handle(callbacks);
0509: } catch (Exception e) {
0510: log
0511: .log(
0512: Level.SEVERE,
0513: "WSS0216.callbackhandler.handle.exception",
0514: new Object[] { "SignatureKeyCallback.AliasPrivKeyCertRequest" });
0515: log.log(Level.SEVERE,
0516: "WSS0217.callbackhandler.handle.exception.log", e);
0517: throw new XWSSecurityException(e);
0518: }
0519: privKey = privKeyRequest.getPrivateKey();
0520:
0521: if (privKey == null) {
0522: log.log(Level.SEVERE, "WSS0222.cannot.locate.privkey",
0523: new Object[] { alias });
0524: throw new XWSSecurityException(
0525: "Unable to locate private key for the alias "
0526: + alias);
0527: }
0528: return privKey;
0529: }
0530:
0531: public PrivateKey getPrivateKey(Map context, byte[] identifier,
0532: String valueType) throws XWSSecurityException {
0533: if (MessageConstants.KEY_INDETIFIER_TYPE.equals(valueType)) {
0534: return getPrivateKey(context, identifier);
0535: }
0536:
0537: PrivateKey privateKey = null;
0538:
0539: DecryptionKeyCallback.PrivateKeyRequest privKeyRequest = new DecryptionKeyCallback.ThumbprintBasedRequest(
0540: identifier);
0541: DecryptionKeyCallback decryptKeyCallback = new DecryptionKeyCallback(
0542: privKeyRequest);
0543: if (!isDefaultHandler) {
0544: ProcessingContext.copy(decryptKeyCallback
0545: .getRuntimeProperties(), context);
0546: }
0547: Callback[] callbacks = new Callback[] { decryptKeyCallback };
0548: try {
0549: callbackHandler.handle(callbacks);
0550: } catch (Exception e) {
0551: log
0552: .log(
0553: Level.SEVERE,
0554: "WSS0216.callbackhandler.handle.exception",
0555: new Object[] { "DecryptionKeyCallback.ThumbprintBasedRequest" });
0556: log.log(Level.SEVERE,
0557: "WSS0217.callbackhandler.handle.exception.log", e);
0558: throw new XWSSecurityException(e);
0559: }
0560: privateKey = privKeyRequest.getPrivateKey();
0561:
0562: if (privateKey == null) {
0563: // not found so throw an exception
0564: log.log(Level.SEVERE, "WSS0222.cannot.locate.privkey",
0565: new Object[] { identifier });
0566: throw new XWSSecurityException(
0567: "No Matching private key for "
0568: + Base64.encode(identifier)
0569: + " thumb print identifier found");
0570: }
0571: return privateKey;
0572: }
0573:
0574: public PrivateKey getPrivateKey(Map context, byte[] keyIdentifier)
0575: throws XWSSecurityException {
0576:
0577: PrivateKey privateKey = null;
0578:
0579: DecryptionKeyCallback.PrivateKeyRequest privKeyRequest = new DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest(
0580: keyIdentifier);
0581: DecryptionKeyCallback decryptKeyCallback = new DecryptionKeyCallback(
0582: privKeyRequest);
0583: if (!isDefaultHandler) {
0584: ProcessingContext.copy(decryptKeyCallback
0585: .getRuntimeProperties(), context);
0586: }
0587: Callback[] callbacks = new Callback[] { decryptKeyCallback };
0588: try {
0589: callbackHandler.handle(callbacks);
0590: } catch (Exception e) {
0591: log
0592: .log(
0593: Level.SEVERE,
0594: "WSS0216.callbackhandler.handle.exception",
0595: new Object[] { "DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest" });
0596: log.log(Level.SEVERE,
0597: "WSS0217.callbackhandler.handle.exception.log", e);
0598: throw new XWSSecurityException(e);
0599: }
0600: privateKey = privKeyRequest.getPrivateKey();
0601:
0602: if (privateKey == null) {
0603: // not found so throw an exception
0604: log.log(Level.SEVERE, "WSS0222.cannot.locate.privkey",
0605: new Object[] { keyIdentifier });
0606: throw new XWSSecurityException(
0607: "No Matching private key for "
0608: + Base64.encode(keyIdentifier)
0609: + " subject key identifier found");
0610: }
0611: return privateKey;
0612: }
0613:
0614: public PrivateKey getPrivateKey(Map context,
0615: BigInteger serialNumber, String issuerName)
0616: throws XWSSecurityException {
0617:
0618: PrivateKey privateKey = null;
0619:
0620: DecryptionKeyCallback.PrivateKeyRequest privKeyRequest = new DecryptionKeyCallback.X509IssuerSerialBasedRequest(
0621: issuerName, serialNumber);
0622: DecryptionKeyCallback decryptKeyCallback = new DecryptionKeyCallback(
0623: privKeyRequest);
0624: if (!isDefaultHandler) {
0625: ProcessingContext.copy(decryptKeyCallback
0626: .getRuntimeProperties(), context);
0627: }
0628: Callback[] callbacks = new Callback[] { decryptKeyCallback };
0629: try {
0630: callbackHandler.handle(callbacks);
0631: } catch (Exception e) {
0632: log
0633: .log(
0634: Level.SEVERE,
0635: "WSS0216.callbackhandler.handle.exception",
0636: new Object[] { "DecryptionKeyCallback.X509IssuerSerialBasedRequest" });
0637: log.log(Level.SEVERE,
0638: "WSS0217.callbackhandler.handle.exception.log", e);
0639: throw new XWSSecurityException(e);
0640: }
0641: privateKey = privKeyRequest.getPrivateKey();
0642:
0643: if (privateKey == null) {
0644: // not found so throw an exception
0645: log.log(Level.SEVERE, "WSS0222.cannot.locate.privkey",
0646: new Object[] { serialNumber + ":" + issuerName });
0647: throw new XWSSecurityException(
0648: "No Matching private key for serial number "
0649: + serialNumber + " and issuer name "
0650: + issuerName + " found");
0651: }
0652:
0653: return privateKey;
0654: }
0655:
0656: public PublicKey getPublicKey(Map context, byte[] identifier,
0657: String valueType) throws XWSSecurityException {
0658: return getCertificate(context, identifier, valueType)
0659: .getPublicKey();
0660: }
0661:
0662: public PublicKey getPublicKey(Map context, byte[] keyIdentifier)
0663: throws XWSSecurityException {
0664: return getCertificate(context, keyIdentifier).getPublicKey();
0665: }
0666:
0667: public X509Certificate getCertificate(Map context,
0668: byte[] identifier, String valueType)
0669: throws XWSSecurityException {
0670: if (MessageConstants.KEY_INDETIFIER_TYPE.equals(valueType)) {
0671: return getCertificate(context, identifier);
0672: }
0673:
0674: //Else if it is Thumbprint
0675: X509Certificate cert = null;
0676:
0677: SignatureVerificationKeyCallback.X509CertificateRequest certRequest = new SignatureVerificationKeyCallback.ThumbprintBasedRequest(
0678: identifier);
0679: SignatureVerificationKeyCallback verifyKeyCallback = new SignatureVerificationKeyCallback(
0680: certRequest);
0681: if (!isDefaultHandler) {
0682: ProcessingContext.copy(verifyKeyCallback
0683: .getRuntimeProperties(), context);
0684: }
0685: Callback[] callbacks = new Callback[] { verifyKeyCallback };
0686: try {
0687: callbackHandler.handle(callbacks);
0688: } catch (Exception e) {
0689: log
0690: .log(
0691: Level.SEVERE,
0692: "WSS0216.callbackhandler.handle.exception",
0693: new Object[] { "SignatureVerificationKeyCallback.ThumbprintBasedRequest" });
0694: log.log(Level.SEVERE,
0695: "WSS0217.callbackhandler.handle.exception.log", e);
0696: throw new XWSSecurityException(e);
0697:
0698: }
0699: cert = certRequest.getX509Certificate();
0700:
0701: if (cert == null) {
0702: // not found so throw an exception
0703: log.log(Level.SEVERE, "WSS0221.cannot.locate.cert",
0704: new Object[] { identifier });
0705: throw new XWSSecurityException(
0706: "No Matching public key for "
0707: + Base64.encode(identifier)
0708: + " thumb print identifier found");
0709: }
0710: return cert;
0711: }
0712:
0713: public X509Certificate getCertificate(Map context,
0714: byte[] keyIdentifier) throws XWSSecurityException {
0715:
0716: X509Certificate cert = null;
0717:
0718: SignatureVerificationKeyCallback.X509CertificateRequest certRequest = new SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest(
0719: keyIdentifier);
0720: SignatureVerificationKeyCallback verifyKeyCallback = new SignatureVerificationKeyCallback(
0721: certRequest);
0722: if (!isDefaultHandler) {
0723: ProcessingContext.copy(verifyKeyCallback
0724: .getRuntimeProperties(), context);
0725: }
0726: Callback[] callbacks = new Callback[] { verifyKeyCallback };
0727: try {
0728: callbackHandler.handle(callbacks);
0729: } catch (Exception e) {
0730: log
0731: .log(
0732: Level.SEVERE,
0733: "WSS0216.callbackhandler.handle.exception",
0734: new Object[] { "SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest" });
0735: log.log(Level.SEVERE,
0736: "WSS0217.callbackhandler.handle.exception.log", e);
0737: throw new XWSSecurityException(e);
0738:
0739: }
0740: cert = certRequest.getX509Certificate();
0741:
0742: if (cert == null) {
0743: // not found so throw an exception
0744: log.log(Level.SEVERE, "WSS0221.cannot.locate.cert",
0745: new Object[] { keyIdentifier });
0746: throw new XWSSecurityException(
0747: "No Matching public key for "
0748: + Base64.encode(keyIdentifier)
0749: + " subject key identifier found");
0750: }
0751: return cert;
0752: }
0753:
0754: public PublicKey getPublicKey(Map context, BigInteger serialNumber,
0755: String issuerName) throws XWSSecurityException {
0756:
0757: return getCertificate(context, serialNumber, issuerName)
0758: .getPublicKey();
0759: }
0760:
0761: public X509Certificate getCertificate(Map context,
0762: BigInteger serialNumber, String issuerName)
0763: throws XWSSecurityException {
0764:
0765: X509Certificate cert = null;
0766:
0767: SignatureVerificationKeyCallback.X509CertificateRequest certRequest = new SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest(
0768: issuerName, serialNumber);
0769: SignatureVerificationKeyCallback verifyKeyCallback = new SignatureVerificationKeyCallback(
0770: certRequest);
0771: if (!isDefaultHandler) {
0772: ProcessingContext.copy(verifyKeyCallback
0773: .getRuntimeProperties(), context);
0774: }
0775: Callback[] callbacks = new Callback[] { verifyKeyCallback };
0776: try {
0777: callbackHandler.handle(callbacks);
0778: } catch (Exception e) {
0779: log
0780: .log(
0781: Level.SEVERE,
0782: "WSS0216.callbackhandler.handle.exception",
0783: new Object[] { "SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest" });
0784: log.log(Level.SEVERE,
0785: "WSS0217.callbackhandler.handle.exception.log", e);
0786: throw new XWSSecurityException(e);
0787: }
0788: cert = certRequest.getX509Certificate();
0789:
0790: if (cert == null) {
0791: // not found so throw an exception
0792: log.log(Level.SEVERE, "WSS0221.cannot.locate.cert",
0793: new Object[] { serialNumber + ":" + issuerName });
0794: throw new XWSSecurityException(
0795: "No Matching public key for serial number "
0796: + serialNumber + " and issuer name "
0797: + issuerName + " found");
0798: }
0799:
0800: return cert;
0801: }
0802:
0803: public boolean validateCertificate(X509Certificate cert)
0804: throws XWSSecurityException {
0805:
0806: CertificateValidationCallback certValCallback = new CertificateValidationCallback(
0807: cert);
0808: Callback[] callbacks = new Callback[] { certValCallback };
0809: try {
0810: callbackHandler.handle(callbacks);
0811: } catch (Exception e) {
0812: log.log(Level.SEVERE,
0813: "WSS0223.failed.certificate.validation");
0814: throw newSOAPFaultException(
0815: MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
0816: "Certificate validation failed", e);
0817: }
0818: if (log.isLoggable(Level.FINE)) {
0819: log.log(Level.FINE,
0820: "Certificate Validation called on certificate "
0821: + cert.getSubjectDN());
0822: }
0823: return certValCallback.getResult();
0824: }
0825:
0826: public void updateOtherPartySubject(final Subject subject,
0827: final String username, final String password) {
0828: //do nothing....
0829: }
0830:
0831: private void updateUsernameInSubject(final Subject subject,
0832: final String username, final String password) {
0833:
0834: AccessController.doPrivileged(new PrivilegedAction() {
0835:
0836: public Object run() {
0837: String x500Name = "CN=" + username;
0838: Principal principal = new X500Principal(x500Name);
0839: subject.getPrincipals().add(principal);
0840: if (password != null) {
0841: subject.getPrivateCredentials().add(password);
0842: }
0843: return null; // nothing to return
0844: }
0845: });
0846: }
0847:
0848: public void updateOtherPartySubject(final Subject subject,
0849: final X509Certificate cert) {
0850: AccessController.doPrivileged(new PrivilegedAction() {
0851: public Object run() {
0852: Principal principal = cert.getSubjectX500Principal();
0853: subject.getPrincipals().add(principal);
0854: subject.getPublicCredentials().add(cert);
0855: return null; // nothing to return
0856: }
0857: });
0858: }
0859:
0860: public void updateOtherPartySubject(final Subject subject,
0861: final Assertion assertion) {
0862: AccessController.doPrivileged(new PrivilegedAction() {
0863: public Object run() {
0864: subject.getPublicCredentials().add(assertion);
0865: return null; // nothing to return
0866: }
0867: });
0868: }
0869:
0870: public void updateOtherPartySubject(final Subject subject,
0871: final Key secretKey) {
0872: AccessController.doPrivileged(new PrivilegedAction() {
0873: public Object run() {
0874: subject.getPublicCredentials().add(secretKey);
0875: return null; // nothing to return
0876: }
0877: });
0878: }
0879:
0880: public void updateOtherPartySubject(final Subject subject,
0881: final String ek) {
0882: AccessController.doPrivileged(new PrivilegedAction() {
0883: public Object run() {
0884: String encryptedKey = "EK" + ek;
0885: subject.getPublicCredentials().add(encryptedKey);
0886: return null; // nothing to return
0887: }
0888: });
0889: }
0890:
0891: public static Subject getSubject(final Map context) {
0892: Subject otherPartySubject = (Subject) context
0893: .get(MessageConstants.AUTH_SUBJECT);
0894: if (otherPartySubject != null) {
0895: return otherPartySubject;
0896: }
0897: otherPartySubject = (Subject) AccessController
0898: .doPrivileged(new PrivilegedAction() {
0899: public Object run() {
0900: Subject otherPartySubj = new Subject();
0901: context.put(MessageConstants.AUTH_SUBJECT,
0902: otherPartySubj);
0903: return otherPartySubj;
0904: }
0905: });
0906: return otherPartySubject;
0907: }
0908:
0909: public static Subject getSubject(
0910: final FilterProcessingContext context) {
0911: Subject otherPartySubject = (Subject) context
0912: .getExtraneousProperty(MessageConstants.AUTH_SUBJECT);
0913: if (otherPartySubject != null) {
0914: return otherPartySubject;
0915: }
0916: otherPartySubject = (Subject) AccessController
0917: .doPrivileged(new PrivilegedAction() {
0918: public Object run() {
0919: Subject otherPartySubj = new Subject();
0920: context.setExtraneousProperty(
0921: MessageConstants.AUTH_SUBJECT,
0922: otherPartySubj);
0923: return otherPartySubj;
0924: }
0925: });
0926: return otherPartySubject;
0927: }
0928:
0929: public PrivateKey getPrivateKey(Map context, X509Certificate cert)
0930: throws XWSSecurityException {
0931:
0932: PrivateKey privateKey = null;
0933:
0934: DecryptionKeyCallback.PrivateKeyRequest privateKeyRequest = new DecryptionKeyCallback.X509CertificateBasedRequest(
0935: cert);
0936: DecryptionKeyCallback decryptKeyCallback = new DecryptionKeyCallback(
0937: privateKeyRequest);
0938: if (!isDefaultHandler) {
0939: ProcessingContext.copy(decryptKeyCallback
0940: .getRuntimeProperties(), context);
0941: }
0942: Callback[] callbacks = new Callback[] { decryptKeyCallback };
0943: try {
0944: callbackHandler.handle(callbacks);
0945: } catch (Exception e) {
0946: log
0947: .log(
0948: Level.SEVERE,
0949: "WSS0216.callbackhandler.handle.exception",
0950: new Object[] { "DecryptionKeyCallback.X509CertificateBasedRequest" });
0951: log.log(Level.SEVERE,
0952: "WSS0217.callbackhandler.handle.exception.log", e);
0953: throw new XWSSecurityException(e);
0954: }
0955: privateKey = privateKeyRequest.getPrivateKey();
0956:
0957: if (privateKey == null) {
0958: log.log(Level.SEVERE, "WSS0222.cannot.locate.privkey",
0959: new Object[] { "given certificate" });
0960: throw new XWSSecurityException(
0961: "Could not retrieve private Key matching the given certificate");
0962: }
0963: return privateKey;
0964: }
0965:
0966: public PrivateKey getPrivateKey(Map context, PublicKey publicKey,
0967: boolean forSign) throws XWSSecurityException {
0968: if (forSign) {
0969: SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest req = new SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest(
0970: publicKey);
0971: SignatureKeyCallback skc = new SignatureKeyCallback(req);
0972: if (!isDefaultHandler) {
0973: ProcessingContext.copy(skc.getRuntimeProperties(),
0974: context);
0975: }
0976: Callback[] callbacks = new Callback[] { skc };
0977: try {
0978: callbackHandler.handle(callbacks);
0979: } catch (Exception e) {
0980: log
0981: .log(
0982: Level.SEVERE,
0983: "WSS0216.callbackhandler.handle.exception",
0984: new Object[] { "SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest" });
0985: log.log(Level.SEVERE,
0986: "WSS0217.callbackhandler.handle.exception.log",
0987: e);
0988: throw new XWSSecurityException(e);
0989: }
0990: return req.getPrivateKey();
0991: } else {
0992: DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest req = new DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest(
0993: publicKey);
0994: DecryptionKeyCallback dkc = new DecryptionKeyCallback(req);
0995: if (!isDefaultHandler) {
0996: ProcessingContext.copy(dkc.getRuntimeProperties(),
0997: context);
0998: }
0999: Callback[] callbacks = new Callback[] { dkc };
1000: try {
1001: callbackHandler.handle(callbacks);
1002: } catch (Exception e) {
1003: log
1004: .log(
1005: Level.SEVERE,
1006: "WSS0216.callbackhandler.handle.exception",
1007: new Object[] { "DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest" });
1008: log.log(Level.SEVERE,
1009: "WSS0217.callbackhandler.handle.exception.log",
1010: e);
1011: throw new XWSSecurityException(e);
1012: }
1013: return req.getPrivateKey();
1014: }
1015: }
1016:
1017: public Subject getSubject() {
1018: log.log(Level.SEVERE, "WSS0224.unsupported.AssociatedSubject");
1019: throw new UnsupportedOperationException(
1020: "This environment does not have an associated Subject");
1021: }
1022:
1023: public boolean authenticateUser(Map context, String username,
1024: String passwordDigest, String nonce, String created)
1025: throws XWSSecurityException {
1026:
1027: PasswordValidationCallback.DigestPasswordRequest request = new PasswordValidationCallback.DigestPasswordRequest(
1028: username, passwordDigest, nonce, created);
1029: PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
1030: request);
1031: if (!isDefaultHandler) {
1032: ProcessingContext.copy(passwordValidationCallback
1033: .getRuntimeProperties(), context);
1034: }
1035: Callback[] callbacks = new Callback[] { passwordValidationCallback };
1036: try {
1037: callbackHandler.handle(callbacks);
1038: } catch (Exception e) {
1039: log.log(Level.SEVERE,
1040: "WSS0225.error.PasswordValidationCallback", e);
1041: throw new XWSSecurityException(e);
1042: }
1043: if (log.isLoggable(Level.FINE)) {
1044: log.log(Level.FINE, "Username Authentication done for "
1045: + username);
1046: }
1047: return passwordValidationCallback.getResult();
1048: }
1049:
1050: public boolean authenticateUser(Map context, String username,
1051: String password) throws XWSSecurityException {
1052:
1053: PasswordValidationCallback.PlainTextPasswordRequest request = new PasswordValidationCallback.PlainTextPasswordRequest(
1054: username, password);
1055: PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
1056: request);
1057: if (!isDefaultHandler) {
1058: ProcessingContext.copy(passwordValidationCallback
1059: .getRuntimeProperties(), context);
1060: }
1061: Callback[] callbacks = new Callback[] { passwordValidationCallback };
1062: boolean result = false;
1063: try {
1064: callbackHandler.handle(callbacks);
1065: RealmAuthenticationAdapter adapter = passwordValidationCallback
1066: .getRealmAuthenticationAdapter();
1067: if (passwordValidationCallback.getValidator() != null) {
1068: result = passwordValidationCallback.getResult();
1069: updateUsernameInSubject(getSubject(context), username,
1070: password);
1071: } else if (adapter != null) {
1072: result = adapter.authenticate(getSubject(context),
1073: username, password);
1074: } else {
1075: log.log(Level.SEVERE,
1076: "WSS0295.password.val.not.config.username.val");
1077: throw new XWSSecurityException(
1078: "Error: No PasswordValidator Configured for UsernameToken Validation");
1079: }
1080: } catch (Exception e) {
1081: log.log(Level.SEVERE,
1082: "WSS0225.error.PasswordValidationCallback", e);
1083: throw new XWSSecurityException(e);
1084: }
1085: return result;
1086: }
1087:
1088: //Default creation time validation code. This will be
1089: //executed when user does not provide TimestampVlidation.
1090: private void defaultValidateCreationTime(String creationTime,
1091: long maxClockSkew, long timestampFreshnessLimit)
1092: throws XWSSecurityException {
1093:
1094: Date created = null;
1095: try {
1096: synchronized (calendarFormatter1) {
1097: created = calendarFormatter1.parse(creationTime);
1098: }
1099: } catch (java.text.ParseException e) {
1100: synchronized (calendarFormatter2) {
1101: try {
1102: created = calendarFormatter2.parse(creationTime);
1103: } catch (java.text.ParseException ex) {
1104: log
1105: .log(
1106: Level.SEVERE,
1107: "WSS0226.failed.Validating.DefaultCreationTime",
1108: ex);
1109: throw new XWSSecurityException(ex);
1110: }
1111: }
1112: }
1113:
1114: Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew,
1115: timestampFreshnessLimit);
1116:
1117: if (created.before(current)) {
1118: log.log(Level.SEVERE, "WSS0227.invalid.older.CreationTime");
1119: throw new XWSSecurityException(
1120: "The creation time is older than "
1121: + " currenttime - timestamp-freshness-limit - max-clock-skew");
1122: }
1123:
1124: Date currentTime = getGMTDateWithSkewAdjusted(
1125: new GregorianCalendar(), maxClockSkew, true);
1126: if (currentTime.before(created)) {
1127: log.log(Level.SEVERE, "WSS0228.invalid.ahead.CreationTime");
1128: throw new XWSSecurityException(
1129: "The creation time is ahead of the current time.");
1130: }
1131: }
1132:
1133: /**
1134: *
1135: * @param creationTime
1136: * @throws XWSSecurityException
1137: * @return
1138: */
1139: public void validateCreationTime(Map context, String creationTime,
1140: long maxClockSkew, long timestampFreshnessLimit)
1141: throws XWSSecurityException {
1142:
1143: TimestampValidationCallback.UTCTimestampRequest request = new TimestampValidationCallback.UTCTimestampRequest(
1144: creationTime, null, maxClockSkew,
1145: timestampFreshnessLimit);
1146:
1147: request.isUsernameToken(true);
1148: TimestampValidationCallback timestampValidationCallback = new TimestampValidationCallback(
1149: request);
1150: if (!isDefaultHandler) {
1151: ProcessingContext.copy(timestampValidationCallback
1152: .getRuntimeProperties(), context);
1153: }
1154: Callback[] callbacks = new Callback[] { timestampValidationCallback };
1155: try {
1156: callbackHandler.handle(callbacks);
1157: } catch (UnsupportedCallbackException e) {
1158: defaultValidateCreationTime(creationTime, maxClockSkew,
1159: timestampFreshnessLimit);
1160: return;
1161: } catch (Exception e) {
1162: log.log(Level.SEVERE,
1163: "WSS0226.failed.Validating.DefaultCreationTime");
1164: throw new XWSSecurityException(e);
1165: }
1166:
1167: try {
1168: timestampValidationCallback.getResult();
1169: } catch (TimestampValidationCallback.TimestampValidationException e) {
1170: log.log(Level.SEVERE,
1171: "WSS0229.failed.Validating.TimeStamp", e);
1172: throw new XWSSecurityException(e);
1173: }
1174: }
1175:
1176: //TODO implement this using callbacks
1177: public boolean validateSamlIssuer(String issuer) {
1178: log.log(Level.SEVERE,
1179: "WSS0230.unsupported.Validating.SAMLIssuer");
1180: throw new UnsupportedOperationException(
1181: "SAML Issuer Validation not yet supported");
1182: }
1183:
1184: //TODO implement this using callbacks
1185: public boolean validateSamlUser(String user, String domain,
1186: String format) {
1187: log
1188: .log(Level.SEVERE,
1189: "WSS0231.unsupported.Validating.SAMLUser");
1190: throw new UnsupportedOperationException(
1191: "SAML User Validation not yet supported");
1192: }
1193:
1194: public String getUsername(Map context) throws XWSSecurityException {
1195: UsernameCallback usernameCallback = new UsernameCallback();
1196: /*if (!isDefaultHandler) {*/
1197: ProcessingContext.copy(usernameCallback.getRuntimeProperties(),
1198: context);
1199: /*}*/
1200: Callback[] callbacks = new Callback[] { usernameCallback };
1201: try {
1202: callbackHandler.handle(callbacks);
1203: } catch (Exception e) {
1204: log.log(Level.SEVERE,
1205: "WSS0216.callbackhandler.handle.exception",
1206: new Object[] { "UsernameCallback" });
1207: log.log(Level.SEVERE,
1208: "WSS0217.callbackhandler.handle.exception.log", e);
1209: throw new XWSSecurityException(e);
1210: }
1211: return usernameCallback.getUsername();
1212: }
1213:
1214: public String getPassword(Map context) throws XWSSecurityException {
1215: PasswordCallback passwordCallback = new PasswordCallback();
1216: /*if (!isDefaultHandler) {*/
1217: ProcessingContext.copy(passwordCallback.getRuntimeProperties(),
1218: context);
1219: /*}*/
1220: Callback[] callbacks = new Callback[] { passwordCallback };
1221: try {
1222: callbackHandler.handle(callbacks);
1223: } catch (Exception e) {
1224: log.log(Level.SEVERE,
1225: "WSS0225.failed.PasswordValidationCallback", e);
1226: throw new XWSSecurityException(e.getMessage(), e);
1227: }
1228: return passwordCallback.getPassword();
1229: }
1230:
1231: //Default expiration time validation code. This will be
1232: //executed when user does not provide TimestampVlidation.
1233: private void defaultValidateExpirationTime(String expirationTime,
1234: long maxClockSkew, long timestampFreshnessLimit)
1235: throws XWSSecurityException {
1236:
1237: if (expirationTime != null) {
1238: Date expires;
1239: try {
1240: synchronized (calendarFormatter1) {
1241: expires = calendarFormatter1.parse(expirationTime);
1242: }
1243: } catch (java.text.ParseException pe) {
1244: synchronized (calendarFormatter2) {
1245: try {
1246: expires = calendarFormatter2
1247: .parse(expirationTime);
1248: } catch (java.text.ParseException e) {
1249: log.log(Level.SEVERE,
1250: "WSS0394.error.parsing.expirationtime");
1251: throw new XWSSecurityException(e);
1252: }
1253: }
1254: }
1255:
1256: Date currentTime = getGMTDateWithSkewAdjusted(
1257: new GregorianCalendar(), maxClockSkew, false);
1258: if (expires.before(currentTime)) {
1259: log.log(Level.SEVERE,
1260: "WSS0393.current.ahead.of.expires");
1261: throw new XWSSecurityException(
1262: "The current time is ahead of the expiration time in Timestamp");
1263: }
1264: }
1265:
1266: }
1267:
1268: public void validateTimestamp(Map context, Timestamp timestamp,
1269: long maxClockSkew, long freshnessLimit)
1270: throws XWSSecurityException {
1271: validateTimestamp(context, timestamp.getCreated(), timestamp
1272: .getExpires(), maxClockSkew, freshnessLimit);
1273: }
1274:
1275: public void validateTimestamp(Map context, String created,
1276: String expires, long maxClockSkew, long freshnessLimit)
1277: throws XWSSecurityException {
1278: if (expiresBeforeCreated(created, expires)) {
1279: XWSSecurityException xwsse = new XWSSecurityException(
1280: "Message expired!");
1281: log.log(Level.SEVERE, "WSS0232.expired.Message");
1282: throw newSOAPFaultException(
1283: MessageConstants.WSU_MESSAGE_EXPIRED,
1284: "Message expired!", xwsse);
1285: }
1286:
1287: TimestampValidationCallback.UTCTimestampRequest request = new TimestampValidationCallback.UTCTimestampRequest(
1288: created, expires, maxClockSkew, freshnessLimit);
1289:
1290: TimestampValidationCallback timestampValidationCallback = new TimestampValidationCallback(
1291: request);
1292: if (!isDefaultHandler) {
1293: ProcessingContext.copy(timestampValidationCallback
1294: .getRuntimeProperties(), context);
1295: }
1296: Callback[] callbacks = new Callback[] { timestampValidationCallback };
1297: try {
1298: callbackHandler.handle(callbacks);
1299: } catch (UnsupportedCallbackException e) {
1300: //System.out.println("Validate Timestamp ...");
1301: defaultValidateCreationTime(created, maxClockSkew,
1302: freshnessLimit);
1303: defaultValidateExpirationTime(expires, maxClockSkew,
1304: freshnessLimit);
1305: return;
1306: } catch (Exception e) {
1307: log.log(Level.SEVERE,
1308: "WSS0229.failed.Validating.TimeStamp", e);
1309: throw new XWSSecurityException(e);
1310: }
1311:
1312: try {
1313: timestampValidationCallback.getResult();
1314: } catch (TimestampValidationCallback.TimestampValidationException e) {
1315: log.log(Level.SEVERE,
1316: "WSS0229.failed.Validating.TimeStamp", e);
1317: throw new XWSSecurityException(e);
1318: }
1319: }
1320:
1321: /**
1322: * Create and initialize a WssSoapFaultException. This method is used in
1323: * conjunction with generateClientFault.
1324: */
1325: public static WssSoapFaultException newSOAPFaultException(
1326: QName faultCode, String faultstring, Throwable th) {
1327: WssSoapFaultException sfe = new WssSoapFaultException(
1328: faultCode, faultstring, null, null);
1329: sfe.initCause(th);
1330: return sfe;
1331: }
1332:
1333: private static Date getGMTDateWithSkewAdjusted(Calendar c,
1334: long maxClockSkew, boolean addSkew) {
1335: //long offset = c.get(Calendar.ZONE_OFFSET);
1336: //if (c.getTimeZone().inDaylightTime(c.getTime())) {
1337: // offset += c.getTimeZone().getDSTSavings();
1338: //}
1339: long beforeTime = c.getTimeInMillis();
1340: long currentTime = beforeTime - offset;
1341:
1342: if (addSkew)
1343: currentTime = currentTime + maxClockSkew;
1344: else
1345: currentTime = currentTime - maxClockSkew;
1346:
1347: c.setTimeInMillis(currentTime);
1348: return c.getTime();
1349: }
1350:
1351: private static Date getFreshnessAndSkewAdjustedDate(
1352: long maxClockSkew, long timestampFreshnessLimit) {
1353: Calendar c = new GregorianCalendar();
1354: //long offset = c.get(Calendar.ZONE_OFFSET);
1355: //if (c.getTimeZone().inDaylightTime(c.getTime())) {
1356: // offset += c.getTimeZone().getDSTSavings();
1357: //}
1358: long beforeTime = c.getTimeInMillis();
1359: long currentTime = beforeTime - offset;
1360:
1361: // allow for clock_skew and timestamp_freshness
1362: long adjustedTime = currentTime - maxClockSkew
1363: - timestampFreshnessLimit;
1364: c.setTimeInMillis(adjustedTime);
1365:
1366: return c.getTime();
1367: }
1368:
1369: private boolean expiresBeforeCreated(String creationTime,
1370: String expirationTime) throws XWSSecurityException {
1371: Date created = null;
1372: Date expires = null;
1373: try {
1374: synchronized (calendarFormatter1) {
1375: created = calendarFormatter1.parse(creationTime);
1376: if (expirationTime != null) {
1377: expires = calendarFormatter1.parse(expirationTime);
1378: }
1379: }
1380: } catch (java.text.ParseException pe) {
1381: synchronized (calendarFormatter2) {
1382: try {
1383: created = calendarFormatter2.parse(creationTime);
1384: if (expirationTime != null) {
1385: expires = calendarFormatter2
1386: .parse(expirationTime);
1387: }
1388: } catch (java.text.ParseException xpe) {
1389: log.log(Level.SEVERE,
1390: "WSS0233.invalid.expire.before.creation",
1391: xpe);
1392: throw new XWSSecurityException(xpe.getMessage());
1393: }
1394: }
1395: }
1396:
1397: if ((expires != null) && expires.equals(created))
1398: return true;
1399:
1400: if ((expires != null) && expires.before(created))
1401: return true;
1402:
1403: return false;
1404: }
1405:
1406: public boolean validateAndCacheNonce(String nonce, String created,
1407: long maxNonceAge) throws XWSSecurityException {
1408:
1409: if ((nonceCache == null)
1410: || ((nonceCache != null) && nonceCache.wasCanceled())) {
1411: initNonceCache(maxNonceAge);
1412: }
1413:
1414: // check if the reclaimer Task is scheduled or not
1415: if (!nonceCache.isScheduled()) {
1416: if (log.isLoggable(Level.FINE))
1417: log.log(Level.FINE,
1418: "About to Store a new Nonce, but Reclaimer not Scheduled, so scheduling one"
1419: + nonceCache);
1420: setNonceCacheCleanup();
1421: }
1422:
1423: return nonceCache.validateAndCacheNonce(nonce, created);
1424: }
1425:
1426: public void validateSAMLAssertion(Map context, Element assertion)
1427: throws XWSSecurityException {
1428:
1429: AuthenticationTokenPolicy authPolicy = new AuthenticationTokenPolicy();
1430: AuthenticationTokenPolicy.SAMLAssertionBinding samlPolicy = (AuthenticationTokenPolicy.SAMLAssertionBinding) authPolicy
1431: .newSAMLAssertionFeatureBinding();
1432: samlPolicy.setAssertion(assertion);
1433:
1434: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
1435: samlPolicy, null);
1436: //let runtime properties be visible here
1437: if (!isDefaultHandler) {
1438: ProcessingContext.copy(dynamicCallback
1439: .getRuntimeProperties(), context);
1440: } else {
1441: dynamicCallback.getRuntimeProperties().put(
1442: MessageConstants.AUTH_SUBJECT,
1443: context.get(MessageConstants.AUTH_SUBJECT));
1444: }
1445: try {
1446: Callback[] callbacks = new Callback[] { dynamicCallback };
1447: callbackHandler.handle(callbacks);
1448: } catch (Exception e) {
1449: log.log(Level.SEVERE,
1450: "WSS0234.failed.Validate.SAMLAssertion", e);
1451: throw SecurableSoapMessage.newSOAPFaultException(
1452: MessageConstants.WSSE_FAILED_AUTHENTICATION,
1453: "Validation failed for SAML Assertion ", e);
1454: }
1455: }
1456:
1457: public Element locateSAMLAssertion(Map context, Element binding,
1458: String assertionId, Document ownerDoc)
1459: throws XWSSecurityException {
1460:
1461: AuthenticationTokenPolicy authPolicy = new AuthenticationTokenPolicy();
1462: AuthenticationTokenPolicy.SAMLAssertionBinding samlPolicy = (AuthenticationTokenPolicy.SAMLAssertionBinding) authPolicy
1463: .newSAMLAssertionFeatureBinding();
1464: samlPolicy.setAuthorityBinding(binding);
1465: samlPolicy.setAssertionId(assertionId);
1466:
1467: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
1468: samlPolicy, null);
1469: //let runtime props be visible here
1470: if (!isDefaultHandler) {
1471: ProcessingContext.copy(dynamicCallback
1472: .getRuntimeProperties(), context);
1473: }
1474: try {
1475: Callback[] callbacks = new Callback[] { dynamicCallback };
1476: callbackHandler.handle(callbacks);
1477: } catch (Exception e) {
1478: log.log(Level.SEVERE,
1479: "WSS0235.failed.locate.SAMLAssertion", e);
1480: throw new XWSSecurityException(e);
1481: }
1482: Element assertion = samlPolicy.getAssertion();
1483: if (assertion == null) {
1484: log.log(Level.SEVERE, "WSS0236.null.SAMLAssertion");
1485: throw new XWSSecurityException(
1486: "SAML Assertion not set into Policy by CallbackHandler");
1487: }
1488:
1489: return assertion;
1490: }
1491:
1492: public AuthenticationTokenPolicy.SAMLAssertionBinding populateSAMLPolicy(
1493: Map fpcontext,
1494: AuthenticationTokenPolicy.SAMLAssertionBinding policy,
1495: DynamicApplicationContext context)
1496: throws XWSSecurityException {
1497:
1498: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
1499: policy, context);
1500: if (!isDefaultHandler) {
1501: ProcessingContext.copy(dynamicCallback
1502: .getRuntimeProperties(), fpcontext);
1503: }
1504: try {
1505: Callback[] callbacks = new Callback[] { dynamicCallback };
1506: callbackHandler.handle(callbacks);
1507: } catch (Exception e) {
1508: log.log(Level.SEVERE,
1509: "WSS0237.failed.DynamicPolicyCallback", e);
1510: throw new XWSSecurityException(e);
1511: }
1512: return (AuthenticationTokenPolicy.SAMLAssertionBinding) dynamicCallback
1513: .getSecurityPolicy();
1514: }
1515:
1516: public CallbackHandler getCallbackHandler() {
1517: return callbackHandler;
1518: }
1519:
1520: private synchronized void initNonceCache(long maxNonceAge) {
1521:
1522: if (nonceCache == null) {
1523: if (maxNonceAge == 0) {
1524: nonceCache = new NonceCache();
1525: } else {
1526: nonceCache = new NonceCache(maxNonceAge);
1527: }
1528: if (log.isLoggable(Level.FINE))
1529: log.log(Level.FINE,
1530: "Creating NonceCache for first time....."
1531: + nonceCache);
1532: } else if (nonceCache.wasCanceled()) {
1533: if (maxNonceAge == 0) {
1534: nonceCache = new NonceCache();
1535: } else {
1536: nonceCache = new NonceCache(maxNonceAge);
1537: }
1538: if (log.isLoggable(Level.FINE))
1539: log.log(Level.FINE,
1540: "Re-creating NonceCache because it was canceled....."
1541: + nonceCache);
1542: }
1543: }
1544:
1545: private synchronized void setNonceCacheCleanup() {
1546:
1547: if (!nonceCache.isScheduled()) {
1548: if (log.isLoggable(Level.FINE))
1549: log.log(Level.FINE,
1550: "Scheduling Nonce Reclaimer task...... for "
1551: + this + ":" + nonceCache);
1552: nonceCleanupTimer.schedule(nonceCache, nonceCache
1553: .getMaxNonceAge(), // run it the first time after
1554: nonceCache.getMaxNonceAge()); //repeat every
1555: nonceCache.scheduled(true);
1556: }
1557: }
1558:
1559: private void validateSamlVersion(Assertion assertion) {
1560: BigInteger major = ((com.sun.xml.wss.saml.Assertion) assertion)
1561: .getMajorVersion();
1562: BigInteger minor = ((com.sun.xml.wss.saml.Assertion) assertion)
1563: .getMinorVersion();
1564:
1565: if (major.intValue() != 1) {
1566: log.log(Level.SEVERE, "WSS0404.saml.invalid.version");
1567: throw SecurableSoapMessage
1568: .newSOAPFaultException(
1569: MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1570: "Major version is not 1 for SAML Assertion:"
1571: + ((com.sun.xml.wss.saml.Assertion) assertion)
1572: .getAssertionID(),
1573: new Exception(
1574: "Major version is not 1 for SAML Assertion"));
1575: }
1576:
1577: if ((minor.intValue() != 0) && (minor.intValue() != 1)) {
1578: log.log(Level.SEVERE, "WSS0404.saml.invalid.version");
1579: throw SecurableSoapMessage
1580: .newSOAPFaultException(
1581: MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
1582: "Minor version is not 0/1 for SAML Assertion:"
1583: + ((com.sun.xml.wss.saml.Assertion) assertion)
1584: .getAssertionID(),
1585: new Exception(
1586: "Minor version is not 0/1 for SAML Assertion"));
1587: }
1588: }
1589:
1590: private void validateIssuer(SecurableSoapMessage secMessage,
1591: Assertion assertion) {
1592: }
1593:
1594: private void validateSamlUser(SecurableSoapMessage secMessage,
1595: Assertion assertion) {
1596: String user = null;
1597:
1598: }
1599:
1600: public void validateSAMLAssertion(Map context,
1601: XMLStreamReader assertion) throws XWSSecurityException {
1602:
1603: AuthenticationTokenPolicy authPolicy = new AuthenticationTokenPolicy();
1604: AuthenticationTokenPolicy.SAMLAssertionBinding samlPolicy = (AuthenticationTokenPolicy.SAMLAssertionBinding) authPolicy
1605: .newSAMLAssertionFeatureBinding();
1606: samlPolicy.setAssertion(assertion);
1607:
1608: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
1609: samlPolicy, null);
1610: if (!isDefaultHandler) {
1611: ProcessingContext.copy(dynamicCallback
1612: .getRuntimeProperties(), context);
1613: } else {
1614: dynamicCallback.getRuntimeProperties().put(
1615: MessageConstants.AUTH_SUBJECT,
1616: this .getSubject(context));
1617: }
1618: try {
1619: Callback[] callbacks = new Callback[] { dynamicCallback };
1620: callbackHandler.handle(callbacks);
1621: } catch (Exception e) {
1622: log.log(Level.SEVERE,
1623: "WSS0234.failed.Validate.SAMLAssertion", e);
1624: throw SecurableSoapMessage.newSOAPFaultException(
1625: MessageConstants.WSSE_FAILED_AUTHENTICATION,
1626: "Validation failed for SAML Assertion ", e);
1627: }
1628: }
1629:
1630: public void updateOtherPartySubject(final Subject subject,
1631: final XMLStreamReader assertion) {
1632: AccessController.doPrivileged(new PrivilegedAction() {
1633: public Object run() {
1634: subject.getPublicCredentials().add(assertion);
1635: return null; // nothing to return
1636: }
1637: });
1638: }
1639:
1640: public boolean isSelfCertificate(X509Certificate cert) {
1641: if (this .selfCertificate != null
1642: && this .selfCertificate.equals(cert)) {
1643: return true;
1644: }
1645: return false;
1646: }
1647:
1648: public void updateOtherPartySubject(Subject subject,
1649: Subject bootStrapSubject) {
1650: SecurityUtil.copySubject(subject, bootStrapSubject);
1651: }
1652:
1653: }
|