001: /*
002:
003: * $Id: AuthenticationTokenFilter.java,v 1.8 2007/08/01 11:05:51 ashutoshshahi Exp $
004:
005: */
006:
007: /*
008: * The contents of this file are subject to the terms
009: * of the Common Development and Distribution License
010: * (the License). You may not use this file except in
011: * compliance with the License.
012: *
013: * You can obtain a copy of the license at
014: * https://glassfish.dev.java.net/public/CDDLv1.0.html.
015: * See the License for the specific language governing
016: * permissions and limitations under the License.
017: *
018: * When distributing Covered Code, include this CDDL
019: * Header Notice in each file and include the License file
020: * at https://glassfish.dev.java.net/public/CDDLv1.0.html.
021: * If applicable, add the following below the CDDL Header,
022: * with the fields enclosed by brackets [] replaced by
023: * you own identifying information:
024: * "Portions Copyrighted [year] [name of copyright owner]"
025: *
026: * Copyright 2006 Sun Microsystems Inc. All Rights Reserved
027: */
028: package com.sun.xml.wss.impl.filter;
029:
030: import com.sun.xml.ws.security.opt.api.keyinfo.TokenBuilder;
031: import com.sun.xml.ws.security.opt.impl.keyinfo.X509TokenBuilder;
032: import com.sun.xml.ws.security.opt.impl.JAXBFilterProcessingContext;
033: import com.sun.xml.ws.security.opt.impl.util.NamespaceContextEx;
034: import java.security.cert.X509Certificate;
035: import com.sun.xml.wss.ProcessingContext;
036: import com.sun.xml.wss.XWSSecurityException;
037: import com.sun.xml.wss.impl.FilterProcessingContext;
038: import com.sun.xml.wss.impl.MessageConstants;
039: import com.sun.xml.wss.impl.SecurableSoapMessage;
040: import com.sun.xml.wss.impl.XMLUtil;
041: import com.sun.xml.wss.logging.LogDomainConstants;
042:
043: import com.sun.xml.wss.core.SecurityHeader;
044: import com.sun.xml.wss.core.UsernameToken;
045: import com.sun.xml.wss.core.Timestamp;
046: import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
047: import com.sun.xml.wss.impl.policy.mls.TimestampPolicy;
048:
049: import java.util.logging.Level;
050: import java.util.logging.Logger;
051:
052: import javax.xml.soap.SOAPElement;
053: import javax.xml.soap.SOAPPart;
054:
055: import com.sun.xml.wss.impl.callback.DynamicPolicyCallback;
056: import com.sun.xml.wss.impl.configuration.DynamicApplicationContext;
057: import com.sun.xml.wss.impl.policy.mls.MessagePolicy;
058: import com.sun.xml.wss.impl.configuration.StaticApplicationContext;
059: import com.sun.xml.wss.impl.misc.DefaultSecurityEnvironmentImpl;
060: import com.sun.xml.wss.impl.misc.NonceContainer;
061: import com.sun.xml.wss.impl.policy.StaticPolicyContext;
062: import com.sun.xml.wss.impl.HarnessUtil;
063: import org.w3c.dom.NodeList;
064:
065: import com.sun.xml.wss.impl.misc.SecurityUtil;
066:
067: public class AuthenticationTokenFilter {
068:
069: private static final Logger log = Logger.getLogger(
070: LogDomainConstants.IMPL_FILTER_DOMAIN,
071: LogDomainConstants.IMPL_FILTER_DOMAIN_BUNDLE);
072:
073: /**
074: * @param context
075: * @throws XWSSecurityException
076: */
077: public static void processUserNameToken(
078: FilterProcessingContext context)
079: throws XWSSecurityException {
080: if (context.isInboundMessage()) {
081: getUserNameTokenFromMessage(context);
082: } else {
083: addUserNameTokenToMessage(context);
084: }
085: }
086:
087: public static void processSamlToken(FilterProcessingContext context)
088: throws XWSSecurityException {
089: if (context.isInboundMessage()) {
090: ImportSamlAssertionFilter.process(context);
091: } else {
092: ExportSamlAssertionFilter.process(context);
093: }
094: }
095:
096: private static void getUserNameTokenFromMessage(
097: FilterProcessingContext context)
098: throws XWSSecurityException {
099:
100: SecurableSoapMessage secureMessage = context
101: .getSecurableSoapMessage();
102: SecurityHeader wsseSecurity = secureMessage
103: .findSecurityHeader();
104: UsernameToken token = null;
105:
106: if (context.getMode() == FilterProcessingContext.ADHOC) {
107: //AuthenticationTokenPolicy policy = (AuthenticationTokenPolicy)context.getSecurityPolicy();
108: if (context.makeDynamicPolicyCallback()) {
109: try {
110:
111: AuthenticationTokenPolicy policy = ((AuthenticationTokenPolicy) context
112: .getSecurityPolicy());
113:
114: AuthenticationTokenPolicy.UsernameTokenBinding userNamePolicy = (AuthenticationTokenPolicy.UsernameTokenBinding) policy
115: .getFeatureBinding();
116: userNamePolicy.isReadOnly(true);
117:
118: DynamicApplicationContext dynamicContext = new DynamicApplicationContext(
119: context.getPolicyContext());
120:
121: dynamicContext.setMessageIdentifier(context
122: .getMessageIdentifier());
123: dynamicContext.inBoundMessage(true);
124: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
125: userNamePolicy, dynamicContext);
126: ProcessingContext.copy(dynamicContext
127: .getRuntimeProperties(), context
128: .getExtraneousProperties());
129: HarnessUtil.makeDynamicPolicyCallback(
130: dynamicCallback, context
131: .getSecurityEnvironment()
132: .getCallbackHandler());
133:
134: policy
135: .setFeatureBinding((AuthenticationTokenPolicy.UsernameTokenBinding) dynamicCallback
136: .getSecurityPolicy());
137: //context.setSecurityPolicy(policy);
138: } catch (Exception e) {
139: // log
140: throw new XWSSecurityException(e);
141: }
142: }
143: AuthenticationTokenPolicy policy = (AuthenticationTokenPolicy) context
144: .getSecurityPolicy();
145:
146: NodeList nodeList = wsseSecurity.getElementsByTagNameNS(
147: MessageConstants.WSSE_NS,
148: MessageConstants.USERNAME_TOKEN_LNAME);
149: if (nodeList.getLength() <= 0) {
150: log.log(Level.SEVERE, "WSS1400.nousername.found");
151: throw new XWSSecurityException(
152: "No Username token found ,Receiver requirement not met");
153: } else if (nodeList.getLength() > 1) {
154: log.log(Level.SEVERE,
155: "WSS1401.morethanone.username.found");
156: throw new XWSSecurityException(
157: "More than one Username token found, Receiver requirement not met");
158: } else {
159: SOAPElement userNameTokenElement = (SOAPElement) nodeList
160: .item(0);
161: token = new UsernameToken(userNameTokenElement, policy
162: .isBSP());
163: token.isBSP(policy.isBSP());
164: }
165: } else {
166:
167: if (context.getMode() == FilterProcessingContext.POSTHOC) {
168: log.log(Level.SEVERE, "WSS1402.error.posthoc");
169: throw new XWSSecurityException(
170: "Internal Error: Called UsernameTokenFilter in POSTHOC Mode");
171: }
172:
173: try {
174: token = new UsernameToken(wsseSecurity
175: .getCurrentHeaderElement());
176: } catch (XWSSecurityException ex) {
177: log.log(Level.SEVERE, "WSS1403.import.username.token");
178: throw SecurableSoapMessage
179: .newSOAPFaultException(
180: MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
181: "Exception while importing Username Password Token",
182: ex);
183: }
184: }
185:
186: String username = token.getUsername();
187: String password = token.getPassword();
188: String passwordDigest = token.getPasswordDigest();
189: String passwordType = token.getPasswordType();
190: String nonce = token.getNonce();
191: String created = token.getCreated();
192: boolean authenticated = false;
193:
194: if (context.getMode() == FilterProcessingContext.ADHOC) {
195:
196: AuthenticationTokenPolicy policy = (AuthenticationTokenPolicy) context
197: .getSecurityPolicy();
198: AuthenticationTokenPolicy.UsernameTokenBinding utBinding = (AuthenticationTokenPolicy.UsernameTokenBinding) policy
199: .getFeatureBinding();
200:
201: // do policy checks
202: if (utBinding.getDigestOn() && (passwordDigest == null)) {
203: log.log(Level.SEVERE, "WSS1404.notmet.digested");
204: throw new XWSSecurityException(
205: "Receiver Requirement for Digested "
206: + "Password has not been met");
207: }
208:
209: if (!utBinding.getDigestOn() && (passwordDigest != null)) {
210: log.log(Level.SEVERE, "WSS1405.notmet.plaintext");
211: throw new XWSSecurityException(
212: "Receiver Requirement for Plain-Text "
213: + "Password has not been met, Received token has Password-Digest");
214: }
215:
216: if (utBinding.getUseNonce() && (nonce == null)) {
217: log.log(Level.SEVERE, "WSS1406.notmet.nonce");
218: throw new XWSSecurityException(
219: "Receiver Requirement for nonce "
220: + "has not been met");
221: }
222:
223: if (!utBinding.getUseNonce() && (nonce != null)) {
224: log.log(Level.SEVERE, "WSS1407.notmet.nononce");
225: throw new XWSSecurityException(
226: "Receiver Requirement for no nonce "
227: + "has not been met, Received token has a nonce specified");
228: }
229: } else if (context.getMode() == FilterProcessingContext.WSDL_POLICY) {
230: //try to infer a Policy here
231: AuthenticationTokenPolicy.UsernameTokenBinding sp = new AuthenticationTokenPolicy.UsernameTokenBinding();
232: if (passwordDigest != null) {
233: sp.setDigestOn(true);
234: }
235: if (nonce != null) {
236: sp.setUseNonce(true);
237: }
238: ((MessagePolicy) context.getInferredSecurityPolicy())
239: .append(sp);
240: }
241:
242: try {
243: if (MessageConstants.PASSWORD_TEXT_NS == passwordType) {
244: authenticated = context.getSecurityEnvironment()
245: .authenticateUser(
246: context.getExtraneousProperties(),
247: username, password);
248: } else {
249: authenticated = context.getSecurityEnvironment()
250: .authenticateUser(
251: context.getExtraneousProperties(),
252: username, passwordDigest, nonce,
253: created);
254: }
255:
256: if (!authenticated) {
257: log.log(Level.SEVERE,
258: "WSS1408.failed.sender.authentication");
259: XWSSecurityException xwse = new XWSSecurityException(
260: "Invalid Username Password Pair");
261: throw SecurableSoapMessage
262: .newSOAPFaultException(
263: MessageConstants.WSSE_FAILED_AUTHENTICATION,
264: "Authentication of Username Password Token Failed",
265: xwse);
266: }
267:
268: if (MessageConstants.debug) {
269: log.log(Level.FINEST, "Password Validated.....");
270: }
271:
272: long maxClockSkew = Timestamp.MAX_CLOCK_SKEW;
273: long freshnessLmt = Timestamp.TIMESTAMP_FRESHNESS_LIMIT;
274: long maxNonceAge = UsernameToken.MAX_NONCE_AGE;
275:
276: if (context.getMode() == FilterProcessingContext.ADHOC) {
277:
278: AuthenticationTokenPolicy authPolicy = (AuthenticationTokenPolicy) context
279: .getSecurityPolicy();
280:
281: AuthenticationTokenPolicy.UsernameTokenBinding policy = (AuthenticationTokenPolicy.UsernameTokenBinding) authPolicy
282: .getFeatureBinding();
283:
284: if (created != null) {
285: TimestampPolicy tPolicy = (TimestampPolicy) policy
286: .getFeatureBinding();
287: maxClockSkew = tPolicy.getMaxClockSkew();
288: freshnessLmt = tPolicy.getTimestampFreshness();
289: }
290: maxNonceAge = policy.getMaxNonceAge();
291: }
292:
293: if (created != null) {
294: context.getSecurityEnvironment().validateCreationTime(
295: context.getExtraneousProperties(), created,
296: maxClockSkew, freshnessLmt);
297: }
298:
299: if (MessageConstants.debug && created != null) {
300: log.log(Level.FINEST, "CreationTime Validated.....");
301: }
302:
303: if (nonce != null) {
304:
305: if (context.getHandler() != null) {
306: //need to use NonceContainer here
307: StaticPolicyContext pc = context.getPolicyContext();
308: String applicationId = null;
309: if ((pc != null)
310: && (pc instanceof StaticApplicationContext)) {
311: applicationId = ((StaticApplicationContext) pc)
312: .getApplicationContextRoot();
313: }
314: if (applicationId != null) {
315: if (!validateAndCacheNonce(applicationId,
316: nonce, created, maxNonceAge)) {
317: XWSSecurityException xwse = new XWSSecurityException(
318: "Invalid/Repeated Nonce value for Username Token");
319: throw SecurableSoapMessage
320: .newSOAPFaultException(
321: MessageConstants.WSSE_FAILED_AUTHENTICATION,
322: "Invalid/Repeated Nonce value for Username Token",
323: xwse);
324: }
325: } else {
326: //log a WARNING that we are unable to validate nonce since no ApplicationId was provided
327: if (MessageConstants.debug) {
328: log
329: .log(Level.WARNING,
330: "Unable to validate nonce since no ApplicationId was provided");
331: }
332: }
333:
334: } else {
335: if (!context.getSecurityEnvironment()
336: .validateAndCacheNonce(nonce, created,
337: maxNonceAge)) {
338: XWSSecurityException xwse = new XWSSecurityException(
339: "Invalid/Repeated Nonce value for Username Token");
340: throw SecurableSoapMessage
341: .newSOAPFaultException(
342: MessageConstants.WSSE_FAILED_AUTHENTICATION,
343: "Invalid/Repeated Nonce value for Username Token",
344: xwse);
345: }
346: }
347: }
348:
349: } catch (XWSSecurityException xwsse) {
350: throw SecurableSoapMessage.newSOAPFaultException(
351: MessageConstants.WSSE_FAILED_AUTHENTICATION, xwsse
352: .getMessage(), xwsse);
353: }
354:
355: context.getSecurityEnvironment().updateOtherPartySubject(
356: DefaultSecurityEnvironmentImpl.getSubject(context),
357: username, password);
358:
359: }
360:
361: /**
362: * @param context
363: * @throws XWSSecurityException
364: * @return
365: */
366: public static AuthenticationTokenPolicy.UsernameTokenBinding resolveUserNameTokenData(
367: FilterProcessingContext context,
368: UsernameToken token,
369: com.sun.xml.ws.security.opt.impl.tokens.UsernameToken unToken,
370: AuthenticationTokenPolicy policy)
371: throws XWSSecurityException {
372:
373: if (!context.makeDynamicPolicyCallback()) {
374:
375: AuthenticationTokenPolicy.UsernameTokenBinding userNamePolicy = (AuthenticationTokenPolicy.UsernameTokenBinding) policy
376: .getFeatureBinding();
377: String userName = userNamePolicy.getUsername();
378: String password = userNamePolicy.getPassword();
379:
380: if (userName == null || "".equals(userName)) {
381: userName = context.getSecurityEnvironment()
382: .getUsername(context.getExtraneousProperties());
383: }
384:
385: if (userName == null || "".equals(userName)) {
386: log.log(Level.SEVERE,
387: "WSS1409.error.creating.usernametoken");
388: throw new XWSSecurityException(
389: "Username has not been set");
390: }
391:
392: if (token != null)
393: token.setUsername(userName);
394: else
395: unToken.setUsernameValue(userName);
396:
397: if (!userNamePolicy.hasNoPassword()
398: && (password == null || "".equals(password))) {
399: password = context.getSecurityEnvironment()
400: .getPassword(context.getExtraneousProperties());
401: }
402: if (!userNamePolicy.hasNoPassword()) {
403: if (token != null)
404: token.setPassword(password);
405: else
406: unToken.setPasswordValue(password);
407: }
408: return userNamePolicy;
409:
410: } else {
411: try {
412: //((AuthenticationTokenPolicy)policy).isReadOnly(true);
413: AuthenticationTokenPolicy.UsernameTokenBinding userNamePolicy = (AuthenticationTokenPolicy.UsernameTokenBinding) policy
414: .getFeatureBinding();
415: userNamePolicy.isReadOnly(true);
416:
417: DynamicApplicationContext dynamicContext = new DynamicApplicationContext(
418: context.getPolicyContext());
419:
420: dynamicContext.setMessageIdentifier(context
421: .getMessageIdentifier());
422: dynamicContext.inBoundMessage(false);
423: DynamicPolicyCallback dynamicCallback = new DynamicPolicyCallback(
424: userNamePolicy, dynamicContext);
425: ProcessingContext.copy(dynamicContext
426: .getRuntimeProperties(), context
427: .getExtraneousProperties());
428: HarnessUtil.makeDynamicPolicyCallback(dynamicCallback,
429: context.getSecurityEnvironment()
430: .getCallbackHandler());
431:
432: AuthenticationTokenPolicy.UsernameTokenBinding resolvedPolicy = (AuthenticationTokenPolicy.UsernameTokenBinding) dynamicCallback
433: .getSecurityPolicy();
434:
435: if (token != null) {
436: token.setUsername(resolvedPolicy.getUsername());
437: token.setPassword(resolvedPolicy.getPassword());
438: } else {
439: unToken.setUsernameValue(resolvedPolicy
440: .getUsername());
441: unToken.setPasswordValue(resolvedPolicy
442: .getPassword());
443: }
444: return resolvedPolicy;
445:
446: } catch (Exception e) {
447: // log
448: throw new XWSSecurityException(e);
449: }
450: }
451: }
452:
453: /**
454: *
455: * @param context
456: * @throws XWSSecurityException
457: */
458: public static void addUserNameTokenToMessage(
459: FilterProcessingContext context)
460: throws XWSSecurityException {
461: if (context instanceof JAXBFilterProcessingContext) {
462: JAXBFilterProcessingContext opContext = (JAXBFilterProcessingContext) context;
463: com.sun.xml.ws.security.opt.impl.outgoing.SecurityHeader secHeader = opContext
464: .getSecurityHeader();
465: AuthenticationTokenPolicy authPolicy = (AuthenticationTokenPolicy) context
466: .getSecurityPolicy();
467: com.sun.xml.ws.security.opt.impl.tokens.UsernameToken unToken = new com.sun.xml.ws.security.opt.impl.tokens.UsernameToken(
468: opContext.getSOAPVersion());
469:
470: AuthenticationTokenPolicy.UsernameTokenBinding policy = resolveUserNameTokenData(
471: opContext, null, unToken, authPolicy);
472:
473: if (policy.getUseNonce()) {
474: unToken.setNonce(policy.getNonce());
475: }
476: if (policy.getDigestOn()) {
477: unToken.setDigestOn();
478: }
479:
480: if (policy.getUseNonce() || policy.getDigestOn()) {
481: String creationTime = "";
482: TimestampPolicy tPolicy = (TimestampPolicy) policy
483: .getFeatureBinding();
484: creationTime = tPolicy.getCreationTime();
485: unToken.setCreationTime(creationTime);
486: }
487:
488: if (policy.hasNoPassword()) {
489: String creationTime = "";
490: TimestampPolicy tPolicy = (TimestampPolicy) policy
491: .getFeatureBinding();
492: creationTime = tPolicy.getCreationTime();
493: unToken.setCreationTime(creationTime);
494: }
495:
496: String wsuId = policy.getUUID();
497: if (wsuId != null && !wsuId.equals("")) {
498: unToken.setId(wsuId);
499: }
500: secHeader.add(unToken);
501: } else {
502: SecurableSoapMessage secureMessage = context
503: .getSecurableSoapMessage();
504: SOAPPart soapPart = secureMessage.getSOAPPart();
505:
506: AuthenticationTokenPolicy authPolicy = (AuthenticationTokenPolicy) context
507: .getSecurityPolicy();
508: UsernameToken token = new UsernameToken(soapPart, "");
509:
510: AuthenticationTokenPolicy.UsernameTokenBinding policy = resolveUserNameTokenData(
511: context, token, null, authPolicy);
512:
513: if (policy.getUseNonce()) {
514: token.setNonce(policy.getNonce());
515: }
516: if (policy.getDigestOn()) {
517: token.setDigestOn();
518: }
519:
520: if (policy.getUseNonce() || policy.getDigestOn()) {
521: String creationTime = "";
522: TimestampPolicy tPolicy = (TimestampPolicy) policy
523: .getFeatureBinding();
524: creationTime = tPolicy.getCreationTime();
525: token.setCreationTime(creationTime);
526: }
527:
528: if (policy.hasNoPassword()) {
529: String creationTime = "";
530: TimestampPolicy tPolicy = (TimestampPolicy) policy
531: .getFeatureBinding();
532: creationTime = tPolicy.getCreationTime();
533: token.setCreationTime(creationTime);
534: }
535: SecurityHeader wsseSecurity = secureMessage
536: .findOrCreateSecurityHeader();
537: String wsuId = policy.getUUID();
538: if (wsuId != null && !wsuId.equals("")) {
539: XMLUtil.setWsuIdAttr(token.getAsSoapElement(), wsuId);
540: }
541: wsseSecurity.insertHeaderBlock(token);
542: }
543: }
544:
545: /**
546: * Validate the nonce in the UsernameToken and cache the nonce
547: * @param nonce
548: * @param created
549: * @return
550: */
551: public static boolean validateAndCacheNonce(String applicationId,
552: String nonce, String created, long maxNonceAge) {
553: return NonceContainer.validateAndCacheNonce(applicationId,
554: nonce, created, maxNonceAge);
555: }
556:
557: public static void processX509Token(FilterProcessingContext context)
558: throws XWSSecurityException {
559:
560: if (context.isInboundMessage()) {
561: return;
562: }
563:
564: AuthenticationTokenPolicy authPolicy = (AuthenticationTokenPolicy) context
565: .getSecurityPolicy();
566: AuthenticationTokenPolicy.X509CertificateBinding policy = (AuthenticationTokenPolicy.X509CertificateBinding) authPolicy
567: .getFeatureBinding();
568:
569: X509Certificate cert = context.getSecurityEnvironment()
570: .getDefaultCertificate(
571: context.getExtraneousProperties());
572: if (cert == null) {
573: throw new XWSSecurityException(
574: "No default X509 certificate was provided");
575: }
576:
577: AuthenticationTokenPolicy.X509CertificateBinding policyClone = (AuthenticationTokenPolicy.X509CertificateBinding) policy
578: .clone();
579: policyClone.setX509Certificate(cert);
580:
581: if (context instanceof JAXBFilterProcessingContext) {
582: JAXBFilterProcessingContext opContext = (JAXBFilterProcessingContext) context;
583: ((NamespaceContextEx) opContext.getNamespaceContext())
584: .addWSSNS();
585: TokenBuilder x509TokenBuilder = new X509TokenBuilder(
586: opContext, policyClone);
587: x509TokenBuilder.process();
588: } else {
589: SecurableSoapMessage secureMessage = context
590: .getSecurableSoapMessage();
591: String wsuId = policy.getUUID();
592: if (wsuId == null) {
593: wsuId = secureMessage.generateId();
594: }
595: SecurityUtil.checkIncludeTokenPolicy(context, policyClone,
596: wsuId);
597: }
598: //X509SecurityToken token = new X509SecurityToken(secureMessage.getSOAPPart(), cert, wsuId);
599: //wsseSecurity.insertHeaderBlock(token);
600: }
601:
602: }
|