Source Code Cross Referenced for SecurityRecipient.java in  » 6.0-JDK-Modules-com.sun » xws-security » com » sun » xml » wss » impl » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules com.sun » xws security » com.sun.xml.wss.impl 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * $Id: SecurityRecipient.java,v 1.11 2007/08/24 09:12:50 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;
0028:
0029:        import com.sun.xml.wss.impl.policy.mls.EncryptionTarget;
0030:        import java.util.Iterator;
0031:        import java.util.ArrayList;
0032:        import java.util.List;
0033:        import java.util.Collection;
0034:        import javax.xml.soap.AttachmentPart;
0035:        import org.w3c.dom.Element;
0036:        import org.w3c.dom.Node;
0037:
0038:        import org.w3c.dom.NodeList;
0039:
0040:        import java.util.logging.Level;
0041:        import java.util.logging.Logger;
0042:
0043:        import javax.xml.soap.SOAPElement;
0044:        import javax.xml.soap.SOAPFactory;
0045:
0046:        import com.sun.xml.wss.core.SecurityHeader;
0047:
0048:        import com.sun.xml.wss.impl.policy.mls.WSSPolicy;
0049:        import com.sun.xml.wss.impl.policy.mls.SignaturePolicy;
0050:        import com.sun.xml.wss.impl.policy.mls.EncryptionPolicy;
0051:
0052:        import com.sun.xml.wss.impl.policy.SecurityPolicy;
0053:        import com.sun.xml.wss.impl.policy.StaticPolicyContext;
0054:
0055:        import com.sun.xml.wss.impl.filter.DumpFilter;
0056:        import com.sun.xml.wss.impl.filter.TimestampFilter;
0057:        import com.sun.xml.wss.impl.filter.SignatureFilter;
0058:        import com.sun.xml.wss.impl.filter.EncryptionFilter;
0059:        import com.sun.xml.wss.impl.filter.SignatureConfirmationFilter;
0060:        import com.sun.xml.wss.impl.filter.AuthenticationTokenFilter;
0061:
0062:        import com.sun.xml.wss.impl.policy.mls.MessagePolicy;
0063:        import com.sun.xml.wss.impl.configuration.StaticApplicationContext;
0064:        import com.sun.xml.wss.impl.configuration.DynamicApplicationContext;
0065:        import com.sun.xml.wss.impl.config.DeclarativeSecurityConfiguration;
0066:        import com.sun.xml.wss.impl.config.ApplicationSecurityConfiguration;
0067:
0068:        import com.sun.xml.wss.impl.callback.DynamicPolicyCallback;
0069:        import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
0070:        import com.sun.xml.wss.logging.LogDomainConstants;
0071:        import com.sun.xml.wss.*;
0072:        import com.sun.xml.wss.impl.policy.mls.Target;
0073:
0074:        /**
0075:         * This class exports a static Security Service for Verifying/Validating Security in an Inbound SOAPMessage.
0076:         * The policy to be applied for Verifying the Message and the SOAPMessage itself are
0077:         * supplied in an instance of a com.sun.xml.wss.ProcessingContext
0078:         * @see ProcessingContext
0079:         */
0080:        public class SecurityRecipient {
0081:
0082:            private static Logger log = Logger.getLogger(
0083:                    LogDomainConstants.WSS_API_DOMAIN,
0084:                    LogDomainConstants.WSS_API_DOMAIN_BUNDLE);
0085:
0086:            /**
0087:             * Validate security in an Inbound SOAPMessage.
0088:             * <P>
0089:             * Calling code should create com.sun.xml.wss.ProcessingContext object with
0090:             * runtime properties. Specifically, it should set SecurityPolicy, application
0091:             * CallbackHandler Or a SecurityEnvironment and static security policy context.
0092:             * The SecurityPolicy instance can be of the following types:
0093:             * <UL>
0094:             *  <LI> A concrete WSSPolicy
0095:             *  <LI> A MessagePolicy
0096:             *  <LI> A DynamicSecurityPolicy
0097:             * </UL>
0098:             *
0099:             * A DynamicSecurityPolicy can inturn resolve to the following:
0100:             * <UL>
0101:             *  <LI> A concrete WSSPolicy
0102:             *  <LI> A MessagePolicy
0103:             * </UL>
0104:             * <P>
0105:             * For cases when policy resolution does not happen accurately because the
0106:             * identification context was not available - for eg. operation name in
0107:             * the message is encrypted - resolution can happen to the enclosing
0108:             * container configuration.
0109:             * <P>
0110:             * Policy resolution can happen as follows:
0111:             * <P>
0112:             *   (a). Constructed StaticPolicyContext - identifying context associated with
0113:             *       configured security policies - is used for look-up of configured
0114:             *       MessagePolicy/DynamicSecurityPolicy/WSSPolicy instances
0115:             * <P>
0116:             *   (b). NOTE: Relevant only when the SecurityPolicy is an ApplicationSecurityConfiguration, or the
0117:             *        root element of the Security Configuration file that was used to generate the SecurityPolicy is
0118:             *        &lt;xwss:JAXRPCSecurity&gt;
0119:             * <P>
0120:             *       In case an identifying context can not be constructed because such
0121:             *       context has partly to be inferred from the message (for eg. operation
0122:             *       name contained as the element name of SOAPBody), the resolved container
0123:             *       configuration is used as follows:
0124:             * <P>
0125:             *       If C = {p1, p2....pn}
0126:             *          where pi belongs to collection of MessagePolicies held by the container.
0127:             * <P>
0128:             *       an in-bound message is processed without application of a policy, whence
0129:             *       a policy representation of the metadata contained in the security header
0130:             *       is constructed as each header element is processed (iteration).
0131:             * <P>
0132:             *       If P be such policy (MessagePolicy) that gets built upon each iteration, C
0133:             *       is reduced as follows:
0134:             * <P>
0135:             *          redux (P, C, M)
0136:             * <P>
0137:             *       where M is the SOAPMessage and
0138:             * <P>
0139:             *       redux:
0140:             * <P>
0141:             *          (1). eliminate all pi that are not loosely semantically equivalent where
0142:             *               the equivalence is checked as follows:
0143:             * <P>
0144:             *               (a). SignaturePolicy:  equivalence of FeatureBinding and KeyBinding
0145:             *                                      excepting target bindings contained in its
0146:             *                                      FeatureBinding
0147:             * <P>
0148:             *               (b). EncryptionPolicy: equivalence of FeatureBinding and KeyBinding
0149:             *                                      excepting target bindings contained in its
0150:             *                                      FeatureBinding
0151:             * <P>
0152:             *               (c). AuthenticationTokenPolicy: equivalence of Feature and Key Bindings
0153:             *
0154:             * <P>
0155:             *          (2). eliminate all pi whose target bindings contained with the FeatureBindings
0156:             *               are applicable to the message. Note that all required message parts should
0157:             *               be apparent post-processing, therefore, equivalence of target bindings
0158:             *               would be checked by comparison of Node sets of SOAPMessage constructed
0159:             *               using the inferred and those contained in C.
0160:             * <P>
0161:             *       After every such reduction, an attempt is made to resolve the policy identifier
0162:             *       (operation name) that can be used for policy resolution, which should be contained
0163:             *       in C and is used further for message processing.
0164:             * <P>
0165:             * @param context an instance of com.sun.xml.wss.ProcessingContext
0166:             * @exception com.sun.xml.wss.XWSSecurityException if there was an unexpected error
0167:             *     while verifying the message. OR if the security in the incoming
0168:             *     message violates the Security policy that was applied to the message.
0169:             * @exception WssSoapFaultException when security in the incoming message
0170:             *     is in direct violation of the OASIS WSS specification.
0171:             *     When a WssSoapFaultException is thrown the getFaultCode() method on the WssSoapFaultException
0172:             *     will return a <code>QName</code> which would correspond to the WSS defined fault.
0173:             */
0174:            public static void validateMessage(ProcessingContext context)
0175:                    throws XWSSecurityException {
0176:
0177:                HarnessUtil.validateContext(context);
0178:
0179:                SecurityPolicy policy = context.getSecurityPolicy();
0180:                StaticPolicyContext staticContext = context.getPolicyContext();
0181:
0182:                FilterProcessingContext fpContext = new FilterProcessingContext(
0183:                        context);
0184:                fpContext.isInboundMessage(true);
0185:
0186:                //MessagePolicy msgPolicy = (MessagePolicy) fpContext.getSecurityPolicy();
0187:                if (true /*msgPolicy.enableWSS11Policy()*/) {
0188:                    // set a property in context to determine if its WSS11
0189:                    fpContext.setExtraneousProperty(
0190:                            "EnableWSS11PolicyReceiver", "true");
0191:                }
0192:
0193:                //TODO: enable this after policy is available for incoming msgs
0194:                if (true /*msgPolicy.enableSignatureConfirmation()*/) {
0195:                    //For SignatureConfirmation
0196:                    //Set a list in extraneous property which will store all the received SignatureValues
0197:                    //If there was no Signature in incoming message this list will be empty
0198:                    List scList = new ArrayList();
0199:                    fpContext.setExtraneousProperty("receivedSignValues",
0200:                            scList);
0201:                }
0202:                if (policy != null) {
0203:
0204:                    if (PolicyTypeUtil.messagePolicy(policy)
0205:                            && !PolicyTypeUtil
0206:                                    .applicationSecurityConfiguration(policy)
0207:                            && ((MessagePolicy) policy).enableDynamicPolicy()
0208:                            && ((MessagePolicy) policy).size() == 0) {
0209:                        policy = new com.sun.xml.wss.impl.policy.mls.DynamicSecurityPolicy();
0210:                    }
0211:
0212:                    if (PolicyTypeUtil.dynamicSecurityPolicy(policy)) {
0213:
0214:                        // create dynamic callback context
0215:                        DynamicApplicationContext dynamicContext = new DynamicApplicationContext(
0216:                                staticContext);
0217:                        dynamicContext.setMessageIdentifier(context
0218:                                .getMessageIdentifier());
0219:                        dynamicContext.inBoundMessage(true);
0220:                        ProcessingContext.copy(dynamicContext
0221:                                .getRuntimeProperties(), context
0222:                                .getExtraneousProperties());
0223:
0224:                        // make dynamic policy callback
0225:                        DynamicPolicyCallback dpCallback = new DynamicPolicyCallback(
0226:                                policy, dynamicContext);
0227:                        HarnessUtil.makeDynamicPolicyCallback(dpCallback,
0228:                                context.getSecurityEnvironment()
0229:                                        .getCallbackHandler());
0230:
0231:                        SecurityPolicy result = dpCallback.getSecurityPolicy();
0232:                        fpContext.setSecurityPolicy(result);
0233:                        fpContext.setMode(FilterProcessingContext.ADHOC);
0234:
0235:                        if (PolicyTypeUtil.messagePolicy(result)) {
0236:                            processMessagePolicy(fpContext);
0237:                        } else if (result instanceof  WSSPolicy) {
0238:                            HarnessUtil.processWSSPolicy(fpContext);
0239:                        } else if (result != null) {
0240:                            log.log(Level.SEVERE, "WSS0260.invalid.DSP");
0241:                            throw new XWSSecurityException(
0242:                                    "Invalid dynamic security policy returned by callback handler");
0243:                        }
0244:
0245:                    } else if (policy instanceof  WSSPolicy) {
0246:                        //fpContext.enableDynamicPolicyCallback(((MessagePolicy)policy).enableDynamicPolicy());
0247:                        fpContext.setMode(FilterProcessingContext.ADHOC);
0248:                        HarnessUtil.processWSSPolicy(fpContext);
0249:                    } else if (PolicyTypeUtil.messagePolicy(policy)) {
0250:                        fpContext
0251:                                .enableDynamicPolicyCallback(((MessagePolicy) policy)
0252:                                        .enableDynamicPolicy());
0253:                        fpContext.setMode(FilterProcessingContext.ADHOC);
0254:                        processMessagePolicy(fpContext);
0255:                        checkForExtraSecurity(fpContext);
0256:                    } else if (PolicyTypeUtil
0257:                            .applicationSecurityConfiguration(policy)) {
0258:                        // policy c'd not be resolved accurately
0259:                        // resolution can be to the port level
0260:                        fpContext.setMode(FilterProcessingContext.POSTHOC);
0261:                        processApplicationSecurityConfiguration(fpContext);
0262:                        checkForExtraSecurity(fpContext);
0263:                    } else {
0264:                        log.log(Level.SEVERE,
0265:                                "WSS0251.invalid.SecurityPolicyInstance");
0266:                        throw new XWSSecurityException(
0267:                                "SecurityPolicy instance should be of type: "
0268:                                        + "WSSPolicy OR MessagePolicy OR DynamicSecurityPolicy "
0269:                                        + "OR ApplicationSecurityConfiguration");
0270:                    }
0271:
0272:                } else {
0273:                    pProcess(fpContext);
0274:                }
0275:
0276:                try {
0277:                    if (!fpContext.retainSecurityHeader()) {
0278:                        fpContext.getSecurableSoapMessage()
0279:                                .deleteSecurityHeader();
0280:                    } else {
0281:                        fpContext.getSecurableSoapMessage()
0282:                                .resetMustUnderstandOnSecHeader();
0283:                    }
0284:                    fpContext.getSOAPMessage().saveChanges();
0285:
0286:                } catch (Exception ex) {
0287:                    log.log(Level.SEVERE, "WSS0370.error.deleting.secheader",
0288:                            ex);
0289:                    throw new XWSSecurityException(ex);
0290:                }
0291:            }
0292:
0293:            /*
0294:             * @param fpContext com.sun.xml.wss.FilterProcessingContext
0295:             *
0296:             * @throws com.sun.xml.wss.XWSSecurityException
0297:             */
0298:            private static void processApplicationSecurityConfiguration(
0299:                    FilterProcessingContext fpContext)
0300:                    throws XWSSecurityException {
0301:
0302:                ApplicationSecurityConfiguration configuration = (ApplicationSecurityConfiguration) fpContext
0303:                        .getSecurityPolicy();
0304:
0305:                Collection mConfiguration = configuration
0306:                        .getAllReceiverPolicies();
0307:
0308:                fpContext.setSecurityPolicy(new MessagePolicy());
0309:
0310:                SOAPElement current = fpContext.getSecurableSoapMessage()
0311:                        .findSecurityHeader().getFirstChildElement();
0312:                MessagePolicy policy = null;
0313:                while (current != null) {
0314:                    fpContext.getSecurableSoapMessage().findSecurityHeader()
0315:                            .setCurrentHeaderElement(current);
0316:                    pProcessOnce(fpContext, current, false);
0317:                    if (!mConfiguration.isEmpty())
0318:                        try {
0319:                            MessagePolicy mp = (MessagePolicy) fpContext
0320:                                    .getSecurityPolicy();
0321:                            if (!mp.isEmpty()) {
0322:                                redux(mp, mConfiguration, fpContext
0323:                                        .getSecurableSoapMessage(), false);
0324:                            }
0325:                        } catch (Exception e) {
0326:                            log.log(Level.SEVERE,
0327:                                    "WSS0256.failed.configure.ASC", e);
0328:                            throw new XWSSecurityException(e);
0329:                        }
0330:                    policy = resolveMP(fpContext, configuration);
0331:                    if (policy != null) {
0332:                        if (!mConfiguration.contains(policy)) {
0333:                            // log
0334:                            StringBuffer buf = null;
0335:                            if (PolicyTypeUtil.messagePolicy(policy)) {
0336:                                for (int it = 0; it < policy.size(); it++) {
0337:                                    if (buf == null)
0338:                                        buf = new StringBuffer();
0339:                                    try {
0340:                                        buf.append(policy.get(it).getType()
0341:                                                + " ");
0342:                                    } catch (Exception e) {
0343:                                        //ignore
0344:                                    }
0345:                                }
0346:                                log.log(Level.SEVERE,
0347:                                        "WSS0261.invalid.Message.policyset");
0348:                                throw new XWSSecurityException(
0349:                                        "Message does not conform to configured policy : [ "
0350:                                                + buf.toString()
0351:                                                + "] policy set is not present in Receiver requirements.");
0352:                            } else {
0353:                                log.log(Level.SEVERE,
0354:                                        "WSS0262.invalid.Message.policytype");
0355:                                throw new XWSSecurityException(
0356:                                        "Message does not conform to configured policy : "
0357:                                                + policy.getType()
0358:                                                + " is not present in Receiver requirements.");
0359:                            }
0360:                        } else {
0361:                            MessagePolicy policyCopy = new MessagePolicy();
0362:                            int size = ((MessagePolicy) fpContext
0363:                                    .getSecurityPolicy()).size();
0364:                            int ppCount = 0;
0365:                            for (int i = 0; i < policy.size(); i++) {
0366:                                try {
0367:                                    WSSPolicy wp = (WSSPolicy) policy.get(i);
0368:                                    if (PolicyTypeUtil.isSecondaryPolicy(wp)) {
0369:                                        if (log.isLoggable(Level.FINEST)) {
0370:                                            log.log(Level.FINEST, wp.getType());
0371:                                        }
0372:                                        policyCopy.append(wp);
0373:                                    } else {
0374:                                        if (ppCount >= size) {
0375:                                            if (log.isLoggable(Level.FINEST)) {
0376:                                                log.log(Level.FINEST, wp
0377:                                                        .getType());
0378:                                            }
0379:                                            policyCopy.append(wp);
0380:                                        } else {
0381:                                            if (log.isLoggable(Level.FINEST)) {
0382:                                                log.log(Level.FINEST, "skipped"
0383:                                                        + wp.getType());
0384:                                            }
0385:                                        }
0386:                                        ppCount++;
0387:                                    }
0388:                                } catch (Exception e) {
0389:                                    log
0390:                                            .log(
0391:                                                    Level.SEVERE,
0392:                                                    "WSS0257.failedto.append.SecurityPolicy.MessagePolicy",
0393:                                                    e);
0394:                                    throw new XWSSecurityException(e);
0395:                                }
0396:                            }
0397:                            fpContext.setMode(FilterProcessingContext.ADHOC);
0398:                            fpContext.setSecurityPolicy(policyCopy);
0399:                            current = HarnessUtil.getNextElement(current);
0400:                            if (policy.dumpMessages()) {
0401:                                DumpFilter.process(fpContext);
0402:                            }
0403:                            processMessagePolicy(fpContext, current);
0404:                            break;
0405:                        }
0406:                    }
0407:
0408:                    current = HarnessUtil.getNextElement(current);
0409:                }
0410:                checkPolicyEquivalence(policy, mConfiguration);
0411:            }
0412:
0413:            /*
0414:             * @param context FilterProcessingContext
0415:             *
0416:             * @return policy MessagePolicy
0417:             *
0418:             * @throws XWSSecurityException
0419:             */
0420:            private static MessagePolicy resolveMP(
0421:                    FilterProcessingContext fpContext,
0422:                    ApplicationSecurityConfiguration configuration)
0423:                    throws XWSSecurityException {
0424:
0425:                String identifier = HarnessUtil
0426:                        .resolvePolicyIdentifier(fpContext.getSOAPMessage());
0427:
0428:                if (identifier == null)
0429:                    return null;
0430:
0431:                StaticPolicyContext context = fpContext.getPolicyContext();
0432:
0433:                //if (fpContext.isJAXRPCIntegration ()) {
0434:                // ILs are expected to turn on the FPContext flag
0435:                ((StaticApplicationContext) context)
0436:                        .setOperationIdentifier(identifier);
0437:                //} else {}
0438:
0439:                SecurityPolicy policy = configuration
0440:                        .getSecurityConfiguration((StaticApplicationContext) context);
0441:
0442:                MessagePolicy mPolicy = null;
0443:
0444:                if (PolicyTypeUtil.dynamicSecurityPolicy(policy)) {
0445:
0446:                    // create dynamic callback context
0447:                    DynamicApplicationContext dynamicContext = new DynamicApplicationContext(
0448:                            context);
0449:                    dynamicContext.setMessageIdentifier(fpContext
0450:                            .getMessageIdentifier());
0451:                    dynamicContext.inBoundMessage(true);
0452:                    ProcessingContext.copy(dynamicContext
0453:                            .getRuntimeProperties(), fpContext
0454:                            .getExtraneousProperties());
0455:
0456:                    // make dynamic policy callback
0457:                    DynamicPolicyCallback dpCallback = new DynamicPolicyCallback(
0458:                            policy, dynamicContext);
0459:                    HarnessUtil.makeDynamicPolicyCallback(dpCallback, fpContext
0460:                            .getSecurityEnvironment().getCallbackHandler());
0461:
0462:                    if (!(PolicyTypeUtil.messagePolicy(dpCallback
0463:                            .getSecurityPolicy()))) {
0464:                        log
0465:                                .log(Level.SEVERE,
0466:                                        "WSS0271.failedto.resolve.policy");
0467:                        throw new XWSSecurityException(
0468:                                "Policy has to resolve to MessagePolicy");
0469:                    } else {
0470:                        mPolicy = (MessagePolicy) dpCallback
0471:                                .getSecurityPolicy();
0472:                    }
0473:
0474:                } else if (PolicyTypeUtil
0475:                        .declarativeSecurityConfiguration(policy)) {
0476:
0477:                    DeclarativeSecurityConfiguration dsc = (DeclarativeSecurityConfiguration) policy;
0478:                    mPolicy = dsc.receiverSettings();
0479:                }
0480:
0481:                return mPolicy;
0482:            }
0483:
0484:            /*
0485:             * @param mPolicy MessagePolicy
0486:             * @param configuration Collection
0487:             * @param message SecurableSoapMessage
0488:             *
0489:             * @throws XWSSecurityException
0490:             */
0491:            private static void redux(MessagePolicy mPolicy,
0492:                    Collection configuration, SecurableSoapMessage message,
0493:                    boolean isSecondary) throws Exception {
0494:
0495:                /**
0496:                 * Re-visit: Handle BooleanComposer
0497:                 */
0498:
0499:                //TODO: secondary policies don't follow order
0500:                WSSPolicy policy = null;
0501:
0502:                int _spSize = mPolicy.getSecondaryPolicies().size() - 1;
0503:                if (isSecondary && _spSize >= 0) {
0504:                    policy = (WSSPolicy) mPolicy.getSecondaryPolicies().get(
0505:                            _spSize);
0506:                } else {
0507:                    int _pSize = mPolicy.getPrimaryPolicies().size() - 1;
0508:                    if (_pSize >= 0) {
0509:                        policy = (WSSPolicy) mPolicy.getPrimaryPolicies().get(
0510:                                _pSize);
0511:                    }
0512:                }
0513:                if (policy == null) {
0514:                    return;
0515:                }
0516:                ArrayList reduxx = new ArrayList();
0517:
0518:                Iterator i = configuration.iterator();
0519:                while (i.hasNext()) {
0520:                    try {
0521:                        MessagePolicy policyx = (MessagePolicy) i.next();
0522:                        int spSize = mPolicy.getSecondaryPolicies().size() - 1;
0523:                        ArrayList policyxList = policyx.getPrimaryPolicies();
0524:
0525:                        WSSPolicy wssPolicyx = null;
0526:                        if (isSecondary && spSize >= 0) {
0527:                            wssPolicyx = (WSSPolicy) policyx.get(spSize);
0528:                        } else {
0529:                            int pSize = mPolicy.getPrimaryPolicies().size() - 1;
0530:                            if (pSize >= 0 && pSize < policyxList.size()) {
0531:                                wssPolicyx = (WSSPolicy) policyxList.get(pSize);
0532:                            } else {
0533:                                continue;
0534:                            }
0535:                        }
0536:                        if (wssPolicyx != null) {
0537:
0538:                            if (!policy.equalsIgnoreTargets(wssPolicyx)) {
0539:                                reduxx.add(policyx);
0540:                            }
0541:                        }
0542:
0543:                    } catch (ClassCastException cce) {
0544:                        // ignore DynamicSecurityPolicies
0545:                        cce.printStackTrace();
0546:                        //log
0547:                        //throw new RuntimeException(cce);
0548:                    }
0549:                }
0550:
0551:                Iterator j = configuration.iterator();
0552:                while (j.hasNext()) {
0553:                    try {
0554:
0555:                        int spSize = mPolicy.getSecondaryPolicies().size() - 1;
0556:                        MessagePolicy policyy = ((MessagePolicy) j.next());
0557:                        ArrayList policyyList = policyy.getPrimaryPolicies();
0558:
0559:                        WSSPolicy wssPolicyy = null;
0560:                        if (isSecondary && spSize >= 0) {
0561:                            wssPolicyy = (WSSPolicy) policyy.get(spSize);
0562:                        } else {
0563:                            int pSize = mPolicy.getPrimaryPolicies().size() - 1;
0564:                            if (pSize >= 0 && pSize < policyyList.size()) {
0565:                                wssPolicyy = (WSSPolicy) policyyList.get(pSize);
0566:                            } else {
0567:                                continue;
0568:                            }
0569:                        }
0570:
0571:                        if (wssPolicyy != null) {
0572:                            if (!checkTargetBasedRequirements(policy,
0573:                                    wssPolicyy, message)) {
0574:                                reduxx.add(policyy);
0575:                            }
0576:                        }
0577:                    } catch (ClassCastException cce) {
0578:                        // ignore DynamicSecurityPolicies
0579:                        cce.printStackTrace();
0580:                        //log;
0581:                    }
0582:                }
0583:
0584:                configuration.removeAll(reduxx);
0585:            }
0586:
0587:            /*
0588:             * @param policy WSSPolicy
0589:             * @param message SecurableSoapMessage
0590:             *
0591:             * @return boolean if policy is applicable to message
0592:             */
0593:            private static boolean checkTargetBasedRequirements(
0594:                    WSSPolicy inferred, WSSPolicy configured,
0595:                    SecurableSoapMessage message) {
0596:                ArrayList inferredTargets = null;
0597:                ArrayList configuredTargets = null;
0598:                if (PolicyTypeUtil.encryptionPolicy(configured)
0599:                        && !PolicyTypeUtil.encryptionPolicy(inferred)) {
0600:                    return false;
0601:                }
0602:
0603:                if (PolicyTypeUtil.signaturePolicy(configured)
0604:                        && !PolicyTypeUtil.signaturePolicy(inferred)) {
0605:                    return false;
0606:                }
0607:
0608:                if (PolicyTypeUtil.signaturePolicy(inferred)
0609:                        && PolicyTypeUtil.signaturePolicy(configured)) {
0610:                    return verifySignatureTargets(inferred, configured, message);
0611:                } else if (PolicyTypeUtil.encryptionPolicy(inferred)
0612:                        && PolicyTypeUtil.encryptionPolicy(configured)) {
0613:                    return verifyEncryptionTargets(inferred, configured,
0614:                            message);
0615:                }
0616:                return false;
0617:            }
0618:
0619:            static boolean verifySignatureTargets(WSSPolicy inferred,
0620:                    WSSPolicy configured, SecurableSoapMessage message) {
0621:                ArrayList inferredTargets = null;
0622:                ArrayList configuredTargets = null;
0623:
0624:                inferredTargets = ((SignaturePolicy.FeatureBinding) inferred
0625:                        .getFeatureBinding()).getTargetBindings();
0626:                configuredTargets = ((SignaturePolicy.FeatureBinding) configured
0627:                        .getFeatureBinding()).getTargetBindings();
0628:
0629:                ArrayList inferredNodeSet = new ArrayList();
0630:                ArrayList configuredNodeSet = new ArrayList();
0631:                try {
0632:                    dereferenceTargets(inferredTargets, inferredNodeSet,
0633:                            message, false);
0634:                    dereferenceTargets(configuredTargets, configuredNodeSet,
0635:                            message, false);
0636:                } catch (XWSSecurityException xwsse) {
0637:                    //xwsse.printStackTrace();
0638:                    // log here
0639:                    return false;
0640:                }
0641:                if (inferredNodeSet.size() != configuredNodeSet.size()) {
0642:                    //throw XWSSecurityException
0643:                    return false;
0644:                }
0645:
0646:                for (int i = 0; i < configuredNodeSet.size(); i++) {
0647:                    EncryptedData cn = (EncryptedData) configuredNodeSet.get(i);
0648:                    for (int j = 0; j < inferredNodeSet.size(); j++) {
0649:                        EncryptedData ci = (EncryptedData) inferredNodeSet
0650:                                .get(j);
0651:                        boolean found = false;
0652:                        if (cn.isAttachmentData() && ci.isAttachmentData()) {
0653:                            found = cn.equals((AttachmentData) ci);
0654:                        } else if (cn.isElementData() && ci.isElementData()) {
0655:                            found = ((EncryptedElement) cn)
0656:                                    .equals((EncryptedElement) ci);
0657:                        }
0658:                        if (found) {
0659:                            inferredNodeSet.remove(j);
0660:                            break;
0661:                        }
0662:                    }
0663:                }
0664:                if (inferredNodeSet.size() != 0) {
0665:                    //throw XWSSecurityException
0666:                    return false;
0667:                }
0668:                return true;
0669:            }
0670:
0671:            static boolean verifyEncryptionTargets(WSSPolicy inferred,
0672:                    WSSPolicy configured, SecurableSoapMessage message) {
0673:                ArrayList inferredTargets = null;
0674:                ArrayList configuredTargets = null;
0675:                inferredTargets = ((EncryptionPolicy.FeatureBinding) inferred
0676:                        .getFeatureBinding()).getTargetBindings();
0677:                configuredTargets = ((EncryptionPolicy.FeatureBinding) configured
0678:                        .getFeatureBinding()).getTargetBindings();
0679:
0680:                ArrayList inferredNodeSet = new ArrayList();
0681:                ArrayList configuredNodeSet = new ArrayList();
0682:                try {
0683:                    dereferenceTargets(inferredTargets, inferredNodeSet,
0684:                            message, true);
0685:                    dereferenceTargets(configuredTargets, configuredNodeSet,
0686:                            message, false);
0687:                } catch (XWSSecurityException xwsse) {
0688:                    return false;
0689:                }
0690:
0691:                if (inferredNodeSet.size() != configuredNodeSet.size()) {
0692:                    //throw XWSSecurityException
0693:                    return false;
0694:                }
0695:                for (int i = 0; i < configuredNodeSet.size(); i++) {
0696:                    EncryptedData cn = (EncryptedData) configuredNodeSet.get(i);
0697:                    for (int j = 0; j < inferredNodeSet.size(); j++) {
0698:                        EncryptedData ci = (EncryptedData) inferredNodeSet
0699:                                .get(j);
0700:                        boolean found = false;
0701:                        if (cn.isAttachmentData() && ci.isAttachmentData()) {
0702:                            found = cn.equals((AttachmentData) ci);
0703:                        } else if (cn.isElementData() && ci.isElementData()) {
0704:                            found = ((EncryptedElement) cn)
0705:                                    .equals((EncryptedElement) ci);
0706:                        }
0707:                        if (found) {
0708:                            inferredNodeSet.remove(j);
0709:                            break;
0710:                        }
0711:                    }
0712:                }
0713:
0714:                if (inferredNodeSet.size() != 0) {
0715:                    //throw XWSSecurityException
0716:                    return false;
0717:                }
0718:                return true;
0719:            }
0720:
0721:            /*
0722:             * @param targets ArrayList
0723:             * @param nodeSet ArrayList
0724:             *
0725:             * @throws XWSSecurityException
0726:             */
0727:            private static void dereferenceTargets(ArrayList targets,
0728:                    ArrayList nodeSet, SecurableSoapMessage message,
0729:                    boolean inferred) throws XWSSecurityException {
0730:                Iterator i = targets.iterator();
0731:                while (i.hasNext()) {
0732:                    Target t = (Target) i.next();
0733:                    boolean mandatory = t.getEnforce();
0734:                    boolean contentOnly = t.getContentOnly();
0735:                    Object object = null;
0736:                    EncryptedData data = null;
0737:                    try {
0738:                        if (!t.isAttachment()) {
0739:                            Element el = null;
0740:                            if (inferred && t instanceof  EncryptionTarget) {
0741:                                el = ((EncryptionTarget) t).getElementData();
0742:                                data = new EncryptedElement(el, contentOnly);
0743:                                nodeSet.add(data);
0744:                            } else {
0745:                                object = message.getMessageParts(t);
0746:                                if (object instanceof  Element) {
0747:                                    data = new EncryptedElement(
0748:                                            (Element) object, contentOnly);
0749:                                    nodeSet.add(data);
0750:                                } else if (object instanceof  NodeList) {
0751:                                    NodeList nl = (NodeList) object;
0752:                                    for (int j = 0; j < nl.getLength(); j++) {
0753:                                        data = new EncryptedElement(
0754:                                                (Element) nl.item(j),
0755:                                                contentOnly);
0756:                                        nodeSet.add(data);
0757:                                    }
0758:                                } else if (object instanceof  Node) {
0759:                                    data = new EncryptedElement(
0760:                                            (Element) object, contentOnly);
0761:                                    nodeSet.add(data);
0762:                                }
0763:                            }
0764:
0765:                        } else {
0766:                            if (!inferred) {
0767:                                AttachmentPart ap = (AttachmentPart) message
0768:                                        .getMessageParts(t);
0769:                                data = new AttachmentData(ap.getContentId(),
0770:                                        contentOnly);
0771:                            } else {
0772:                                data = new AttachmentData(t.getValue(),
0773:                                        contentOnly);
0774:                            }
0775:                            nodeSet.add(data);
0776:                        }
0777:                    } catch (XWSSecurityException ex) {
0778:                        if (!inferred && mandatory) {
0779:                            log.log(Level.SEVERE,
0780:                                    "WSS0272.failedto.derefer.targets");
0781:                            throw ex;
0782:                        }
0783:                        continue;
0784:                    }
0785:
0786:                    /*System.out.println("Object"+object);
0787:                    if (object instanceof NodeList) {
0788:                        NodeList nl = (NodeList) object;
0789:                        for (int j=0; j< nl.getLength(); j++){
0790:                            System.out.println("NODE "+nl.item(j));
0791:                            nodeSet.add(nl.item(j));
0792:                        }
0793:                    } else {
0794:                        nodeSet.add(object);
0795:                    }
0796:                      }*/
0797:                }
0798:            }
0799:
0800:            /*
0801:             * @param policy MessagePolicy
0802:             * @param configuration Collection
0803:             *
0804:             * @throws XWSSecurityException
0805:             */
0806:            private static void checkPolicyEquivalence(MessagePolicy policy,
0807:                    Collection configuration) throws XWSSecurityException {
0808:
0809:                if (policy != null) {
0810:                    Iterator i = configuration.iterator();
0811:
0812:                    while (i.hasNext()) {
0813:                        MessagePolicy mPolicy = (MessagePolicy) i.next();
0814:
0815:                        if (policy == mPolicy) {
0816:                            return;
0817:                        }
0818:                    }
0819:                    log.log(Level.SEVERE, "WSS0263.invalid.Message.policy");
0820:                    throw new XWSSecurityException(
0821:                            "Message does not conform to configured policy");
0822:                }
0823:            }
0824:
0825:            /*
0826:             * @param fpContext com.sun.xml.wss.FilterProcessingContext
0827:             *
0828:             * @throws com.sun.xml.wss.XWSSecurityException
0829:             */
0830:            private static void processMessagePolicy(
0831:                    FilterProcessingContext fpContext)
0832:                    throws XWSSecurityException {
0833:
0834:                MessagePolicy policy = (MessagePolicy) fpContext
0835:                        .getSecurityPolicy();
0836:
0837:                if (policy.dumpMessages()) {
0838:                    DumpFilter.process(fpContext);
0839:                }
0840:
0841:                if (policy.size() == 0) {
0842:                    fpContext.setMode(FilterProcessingContext.DEFAULT);
0843:                    pProcess(fpContext);
0844:                    return;
0845:                }
0846:
0847:                //TODO: hack till we fix this in PolicyTranslator
0848:                //TO be removed before Plugfest
0849:                try {
0850:                    if ((policy.size() == 1)
0851:                            && (PolicyTypeUtil
0852:                                    .signatureConfirmationPolicy(policy.get(0)))) {
0853:                        fpContext.setMode(FilterProcessingContext.DEFAULT);
0854:                        pProcess(fpContext);
0855:                        return;
0856:                    }
0857:                } catch (Exception e) {
0858:                    log.log(Level.SEVERE, "WSS0273.failedto.process.policy", e);
0859:                    throw new RuntimeException(e);
0860:                }
0861:
0862:                SecurityHeader header = fpContext.getSecurableSoapMessage()
0863:                        .findSecurityHeader();
0864:                if (header == null) {
0865:                    StringBuffer buf = new StringBuffer();
0866:                    for (int it = 0; it < policy.size(); it++) {
0867:                        try {
0868:                            buf.append(policy.get(it).getType());
0869:                            if (PolicyTypeUtil
0870:                                    .isPrimaryPolicy((WSSPolicy) policy.get(it))) {
0871:                                buf.append("(P) ");
0872:                            } else {
0873:                                buf.append("(S) ");
0874:                            }
0875:                        } catch (Exception ex) {
0876:                            //ignore
0877:                        }
0878:                    }
0879:                    log.log(Level.SEVERE, "WSS0253.invalid.Message");
0880:                    throw new XWSSecurityException(
0881:                            "Message does not conform to configured policy [ "
0882:                                    + buf.toString()
0883:                                    + "]:  No Security Header found");
0884:                }
0885:                SOAPElement current = header.getFirstChildElement();
0886:                processMessagePolicy(fpContext, current);
0887:            }
0888:
0889:            private static void processMessagePolicy(
0890:                    FilterProcessingContext fpContext, SOAPElement current)
0891:                    throws XWSSecurityException {
0892:                int idx = 0;
0893:                MessagePolicy policy = (MessagePolicy) fpContext
0894:                        .getSecurityPolicy();
0895:                SecurableSoapMessage secureMsg = fpContext
0896:                        .getSecurableSoapMessage();
0897:                MessagePolicy secPolicy = null;
0898:                ArrayList targets = null;
0899:                StringBuffer buf = null;
0900:
0901:                boolean foundPrimaryPolicy = false;
0902:                while (idx < policy.size()) {
0903:
0904:                    WSSPolicy wssPolicy = null;
0905:                    try {
0906:                        wssPolicy = (WSSPolicy) policy.get(idx);
0907:                    } catch (Exception e) {
0908:                        log
0909:                                .log(Level.SEVERE,
0910:                                        "WSS0270.failedto.get.SecurityPolicy.MessagePolicy");
0911:                        throw new XWSSecurityException(e);
0912:                    }
0913:
0914:                    if (PolicyTypeUtil.isPrimaryPolicy(wssPolicy)) {
0915:                        if (wssPolicy.getType().equals("EncryptionPolicy")) {
0916:                            targets = ((EncryptionPolicy.FeatureBinding) wssPolicy
0917:                                    .getFeatureBinding()).getTargetBindings();
0918:                        } else {
0919:                            targets = ((SignaturePolicy.FeatureBinding) wssPolicy
0920:                                    .getFeatureBinding()).getTargetBindings();
0921:                        }
0922:                        foundPrimaryPolicy = true;
0923:                        Iterator ite = targets.iterator();
0924:                        while (ite.hasNext()) {
0925:                            Target t = (Target) ite.next();
0926:                            if (t.getEnforce()) {
0927:
0928:                                // roll the pointer down the header till a primary block is hit
0929:                                // if end of header is hit (pointer is null) break out of the loop
0930:                                while (current != null
0931:                                        && HarnessUtil
0932:                                                .isSecondaryHeaderElement(current))
0933:                                    current = HarnessUtil
0934:                                            .getNextElement(current);
0935:
0936:                                // if pointer is null (hit end of header), reset pointer to begining of header
0937:                                if (current != null) {
0938:
0939:                                    secureMsg.findSecurityHeader()
0940:                                            .setCurrentHeaderElement(current);
0941:
0942:                                    fpContext.setSecurityPolicy(wssPolicy);
0943:                                    HarnessUtil.processDeep(fpContext);
0944:
0945:                                    boolean keepCurrent = false;
0946:                                    if (MessageConstants.ENCRYPTED_DATA_LNAME
0947:                                            .equals(current.getLocalName())) {
0948:                                        keepCurrent = true;
0949:                                    }
0950:
0951:                                    if (fpContext.isPrimaryPolicyViolation()) {
0952:                                        log.log(Level.SEVERE,
0953:                                                "WSS0265.error.primary.policy");
0954:                                        throw new XWSSecurityException(
0955:                                                fpContext.getPVE());
0956:                                    }
0957:
0958:                                    if (fpContext.isOptionalPolicyViolation()) {
0959:                                        // rollback current security header ptr.
0960:                                        // if secondary security header element
0961:                                        // is found, proceed to next header element
0962:                                        secureMsg.findSecurityHeader()
0963:                                                .setCurrentHeaderElement(
0964:                                                        current);
0965:                                    }
0966:
0967:                                    if (!keepCurrent) {
0968:                                        current = secureMsg
0969:                                                .findSecurityHeader()
0970:                                                .getCurrentHeaderBlockElement();
0971:                                    } else {
0972:                                        current = HarnessUtil
0973:                                                .getNextElement(secureMsg
0974:                                                        .findSecurityHeader()
0975:                                                        .getCurrentHeaderBlockElement());
0976:                                    }
0977:                                    //current = HarnessUtil.getNextElement(current);                            
0978:                                    break;
0979:                                } else {
0980:                                    //log
0981:                                    if (buf == null)
0982:                                        buf = new StringBuffer();
0983:                                    buf.append(wssPolicy.getType() + " ");
0984:                                    //throw new XWSSecurityException("More Receiver requirements specified"+
0985:                                    //        " than present in the message");
0986:                                }
0987:                            } else {
0988:                                // roll the pointer down the header till a primary block is hit
0989:                                // if end of header is hit (pointer is null) break out of the loop
0990:                                while (current != null
0991:                                        && HarnessUtil
0992:                                                .isSecondaryHeaderElement(current))
0993:                                    current = HarnessUtil
0994:                                            .getNextElement(current);
0995:
0996:                                if ((current != null && wssPolicy.getType()
0997:                                        .equals("EncryptionPolicy"))
0998:                                        && current.getLocalName().equals(
0999:                                                "Signature")) {
1000:                                    continue;
1001:                                }
1002:                                if ((current != null && wssPolicy.getType()
1003:                                        .equals("SignaturePolicy"))
1004:                                        && (current
1005:                                                .getLocalName()
1006:                                                .equals(
1007:                                                        MessageConstants.ENCRYPTED_DATA_LNAME)
1008:                                                || current
1009:                                                        .getLocalName()
1010:                                                        .equals(
1011:                                                                MessageConstants.XENC_ENCRYPTED_KEY_LNAME) || current
1012:                                                .getLocalName()
1013:                                                .equals(
1014:                                                        MessageConstants.XENC_REFERENCE_LIST_LNAME))) {
1015:                                    continue;
1016:                                }
1017:
1018:                                // if pointer is null (hit end of header), reset pointer to begining of header
1019:                                if (current != null) {
1020:
1021:                                    secureMsg.findSecurityHeader()
1022:                                            .setCurrentHeaderElement(current);
1023:
1024:                                    fpContext.setSecurityPolicy(wssPolicy);
1025:                                    HarnessUtil.processDeep(fpContext);
1026:
1027:                                    boolean keepCurrent = false;
1028:                                    if (MessageConstants.ENCRYPTED_DATA_LNAME
1029:                                            .equals(current.getLocalName())) {
1030:                                        keepCurrent = true;
1031:                                    }
1032:
1033:                                    if (fpContext.isPrimaryPolicyViolation()) {
1034:                                        log.log(Level.SEVERE,
1035:                                                "WSS0265.error.primary.policy");
1036:                                        throw new XWSSecurityException(
1037:                                                fpContext.getPVE());
1038:                                    }
1039:
1040:                                    if (fpContext.isOptionalPolicyViolation()) {
1041:                                        // rollback current security header ptr.
1042:                                        // if secondary security header element
1043:                                        // is found, proceed to next header element
1044:                                        secureMsg.findSecurityHeader()
1045:                                                .setCurrentHeaderElement(
1046:                                                        current);
1047:                                    }
1048:
1049:                                    if (!keepCurrent) {
1050:                                        current = secureMsg
1051:                                                .findSecurityHeader()
1052:                                                .getCurrentHeaderBlockElement();
1053:                                    } else {
1054:                                        current = HarnessUtil
1055:                                                .getNextElement(secureMsg
1056:                                                        .findSecurityHeader()
1057:                                                        .getCurrentHeaderBlockElement());
1058:                                    }
1059:                                    //current = HarnessUtil.getNextElement(current);                            
1060:                                    break;
1061:                                }
1062:                            }
1063:                        }
1064:                    } else {
1065:                        if (secPolicy == null) {
1066:                            secPolicy = new MessagePolicy();
1067:                        }
1068:                        secPolicy.append(wssPolicy);
1069:                    }
1070:
1071:                    idx++;
1072:                }
1073:
1074:                if (buf != null) {
1075:                    log.log(Level.SEVERE, "WSS0258.invalid.requirements");
1076:                    throw new XWSSecurityException(
1077:                            "More Receiver requirements [ " + buf
1078:                                    + " ] specified"
1079:                                    + " than present in the message");
1080:                }
1081:
1082:                if (!foundPrimaryPolicy) {
1083:                    SecurityHeader header = secureMsg.findSecurityHeader();
1084:                    if (header != null
1085:                            && header.getCurrentHeaderElement() == null) {
1086:                        header.setCurrentHeaderElement(header
1087:                                .getFirstChildElement());
1088:                    }
1089:                    checkForExtraSecurity(fpContext);
1090:                }
1091:
1092:                // now process Secondary policies
1093:                idx = 0;
1094:                SOAPElement securityHeader = secureMsg.findSecurityHeader();
1095:
1096:                NodeList uList = securityHeader.getElementsByTagNameNS(
1097:                        MessageConstants.WSSE_NS,
1098:                        MessageConstants.USERNAME_TOKEN_LNAME);
1099:                if (uList.getLength() > 1) {
1100:                    log.log(Level.SEVERE, "WSS0259.invalid.SEC.username");
1101:                    throw new XWSSecurityException(
1102:                            "More than one wsse:UsernameToken element present in security header");
1103:                }
1104:
1105:                NodeList tList = securityHeader.getElementsByTagNameNS(
1106:                        MessageConstants.WSU_NS,
1107:                        MessageConstants.TIMESTAMP_LNAME);
1108:                if (tList.getLength() > 1) {
1109:                    log.log(Level.SEVERE, "WSS0274.invalid.SEC.Timestamp");
1110:                    throw new XWSSecurityException(
1111:                            "More than one wsu:Timestamp element present in security header");
1112:                }
1113:
1114:                int unpCount = 0;
1115:                int tspCount = 0;
1116:                if (secPolicy != null) {
1117:
1118:                    while (idx < secPolicy.size()) {
1119:                        WSSPolicy wssPolicy = null;
1120:                        try {
1121:                            wssPolicy = (WSSPolicy) secPolicy.get(idx);
1122:                        } catch (Exception e) {
1123:                            log
1124:                                    .log(Level.SEVERE,
1125:                                            "WSS0270.failedto.get.SecurityPolicy.MessagePolicy");
1126:                            throw new XWSSecurityException(e);
1127:                        }
1128:                        if (PolicyTypeUtil.authenticationTokenPolicy(wssPolicy)) {
1129:                            AuthenticationTokenPolicy atp = (AuthenticationTokenPolicy) wssPolicy;
1130:                            WSSPolicy fb = (WSSPolicy) atp.getFeatureBinding();
1131:                            if (PolicyTypeUtil.usernameTokenPolicy(fb)) {
1132:                                if (uList.getLength() == 0) {
1133:                                    log
1134:                                            .log(Level.SEVERE,
1135:                                                    "WSS0275.invalid.policy.NoUsername.SecHeader");
1136:                                    throw new XWSSecurityException(
1137:                                            "Message does not conform to configured policy: "
1138:                                                    + "wsse:UsernameToken element not found in security header");
1139:
1140:                                }
1141:                                unpCount++;
1142:                            } else if (PolicyTypeUtil.samlTokenPolicy(fb)) {
1143:                                //TODO : there can be more than 1 SAML assertion in a message
1144:                            }
1145:                        } else if (PolicyTypeUtil.timestampPolicy(wssPolicy)) {
1146:                            if (tList.getLength() == 0) {
1147:                                log
1148:                                        .log(Level.SEVERE,
1149:                                                "WSS0276.invalid.policy.NoTimestamp.SecHeader");
1150:                                throw new XWSSecurityException(
1151:                                        "Message does not conform to configured policy: "
1152:                                                + "wsu:Timestamp element not found in security header");
1153:                            }
1154:                            tspCount++;
1155:                        }
1156:
1157:                        fpContext.setSecurityPolicy(wssPolicy);
1158:                        HarnessUtil.processDeep(fpContext);
1159:
1160:                        idx++;
1161:                    }
1162:
1163:                }
1164:
1165:                if (uList.getLength() > unpCount) {
1166:                    log.log(Level.SEVERE, "WSS0259.invalid.SEC.username");
1167:                    throw new XWSSecurityException(
1168:                            "Message does not conform to configured policy: "
1169:                                    + "Additional wsse:UsernameToken element found in security header");
1170:                }
1171:
1172:                /* For BC reasons we might support an additional Timestamp in the message */
1173:                if (tList.getLength() > tspCount) {
1174:                    //TODO: localize the string
1175:                    if (log.isLoggable(Level.WARNING)) {
1176:                        log.log(Level.WARNING, "WSS0274.invalid.SEC.Timestamp");
1177:                    }
1178:                    /*
1179:                    throw new XWSSecurityException(
1180:                    "Message does not conform to configured policy: " +
1181:                    "Additional wsu:Timestamp element found in security header");
1182:                     */
1183:                }
1184:
1185:                fpContext.setSecurityPolicy(policy);
1186:                return;
1187:            }
1188:
1189:            private static void checkForExtraSecurity(
1190:                    FilterProcessingContext context)
1191:                    throws XWSSecurityException {
1192:
1193:                SecurityHeader header = context.getSecurableSoapMessage()
1194:                        .findSecurityHeader();
1195:
1196:                if (header == null || header.getCurrentHeaderElement() == null)
1197:                    return;
1198:
1199:                /*
1200:                 for (SOAPElement current = (SOAPElement) header.getCurrentHeaderElement().getNextSibling();
1201:                 current != null;
1202:                 current = (SOAPElement) current.getNextSibling()) {
1203:                 */
1204:
1205:                for (Node nextNode = header.getCurrentHeaderElement()
1206:                        .getNextSibling(); nextNode != null; nextNode = nextNode
1207:                        .getNextSibling()) {
1208:                    if (nextNode instanceof  SOAPElement) {
1209:                        SOAPElement current = (SOAPElement) nextNode;
1210:                        if (!HarnessUtil.isSecondaryHeaderElement(current)) {
1211:                            //System.out.println("----------" +current.getLocalName());
1212:                            log
1213:                                    .log(Level.SEVERE,
1214:                                            "WSS0277.invalid.AddtionalSEC.Message.policy");
1215:                            throw new XWSSecurityException(
1216:                                    "Message does not conform to configured policy (found "
1217:                                            + current.getLocalName()
1218:                                            + ") : "
1219:                                            + "Additional security than required found");
1220:                        }
1221:                    }
1222:                }
1223:
1224:                // TODO: Revisit this
1225:                // checkForExtraSecondarySecurity (context);
1226:            }
1227:
1228:            private static void checkForExtraSecondarySecurity(
1229:                    FilterProcessingContext context)
1230:                    throws XWSSecurityException {
1231:
1232:                SecurityHeader header = context.getSecurableSoapMessage()
1233:                        .findSecurityHeader();
1234:                MessagePolicy policy = (MessagePolicy) context
1235:                        .getSecurityPolicy();
1236:
1237:                boolean _UT = false;
1238:                boolean _TS = false;
1239:
1240:                for (SOAPElement current = (SOAPElement) header
1241:                        .getFirstChildElement(); current != null; current = (SOAPElement) current
1242:                        .getNextSibling()) {
1243:                    try {
1244:                        _UT = current.getLocalName().equals(
1245:                                MessageConstants.USERNAME_TOKEN_LNAME);
1246:                        _TS = current.getLocalName().equals(
1247:                                MessageConstants.TIMESTAMP_LNAME);
1248:                    } catch (Exception e) {
1249:                        log.log(Level.SEVERE, "WSS0278.failedto.get.localName");
1250:                        throw new XWSSecurityRuntimeException(e);
1251:                    }
1252:                }
1253:
1254:                boolean throwFault = false;
1255:                StringBuffer buf = null;
1256:
1257:                if (!_UT)
1258:                    for (int i = 0; i < policy.size(); i++)
1259:                        try {
1260:                            if (PolicyTypeUtil.usernameTokenPolicy(policy
1261:                                    .get(i))) {
1262:                                if (buf == null) {
1263:                                    buf = new StringBuffer();
1264:                                }
1265:                                buf.append(policy.get(i).getType() + " ");
1266:                                throwFault = true;
1267:                            }
1268:                        } catch (Exception e) {
1269:                            log.log(Level.SEVERE,
1270:                                    "WSS0279.failed.check.secSecurity", e);
1271:                            throw new XWSSecurityRuntimeException(e);
1272:                        }
1273:
1274:                if (!_TS)
1275:                    for (int j = 0; j < policy.size(); j++)
1276:                        try {
1277:                            if (PolicyTypeUtil.timestampPolicy(policy.get(j))) {
1278:                                if (buf == null) {
1279:                                    buf = new StringBuffer();
1280:                                }
1281:                                buf.append(policy.get(j).getType() + " ");
1282:                                throwFault = true;
1283:                            }
1284:                        } catch (Exception e) {
1285:                            log.log(Level.SEVERE,
1286:                                    "WSS0279.failed.check.secSecurity", e);
1287:                            throw new XWSSecurityRuntimeException(e);
1288:                        }
1289:
1290:                if (throwFault)
1291:                    log.log(Level.SEVERE,
1292:                            "WSS0277.invalid.AddtionalSEC.Message.policy");
1293:                throw new XWSSecurityException(
1294:                        "Message does not conform to configured policy: "
1295:                                + "Additional security [ " + buf.toString()
1296:                                + "] than required found");
1297:            }
1298:
1299:            /*
1300:             * @param fpContext com.sun.xml.wss.FilterProcessingContext
1301:             * @param isSecondary boolean
1302:             *
1303:             * @return boolean
1304:             *
1305:             * @see pProcess
1306:             *
1307:             * @throws com.sun.xml.wss.XWSSecurityException
1308:             */
1309:            private static boolean pProcessOnce(
1310:                    FilterProcessingContext fpContext, SOAPElement current,
1311:                    boolean isSecondary) throws XWSSecurityException {
1312:
1313:                boolean processed = false;
1314:
1315:                String elementName = current.getLocalName();
1316:
1317:                if (isSecondary) {
1318:                    if (MessageConstants.USERNAME_TOKEN_LNAME
1319:                            .equals(elementName)) {
1320:                        AuthenticationTokenFilter
1321:                                .processUserNameToken(fpContext);
1322:                        processed = true;
1323:
1324:                    } else if (MessageConstants.TIMESTAMP_LNAME
1325:                            .equals(elementName)) {
1326:                        TimestampFilter.process(fpContext);
1327:                        processed = true;
1328:
1329:                    } else if (MessageConstants.SIGNATURE_CONFIRMATION_LNAME
1330:                            .equals(elementName)) {
1331:                        SignatureConfirmationFilter.process(fpContext);
1332:                        processed = true;
1333:                    } else if (MessageConstants.WSSE_BINARY_SECURITY_TOKEN_LNAME
1334:                            .equals(elementName)) {
1335:                        //ignore
1336:
1337:                    } else if (MessageConstants.SAML_ASSERTION_LNAME
1338:                            .equals(elementName)) {
1339:                        AuthenticationTokenFilter.processSamlToken(fpContext);
1340:                    } else if (MessageConstants.WSSE_SECURITY_TOKEN_REFERENCE_LNAME
1341:                            .equals(elementName)) {
1342:                        //ignore
1343:                    } else if (MessageConstants.SECURITY_CONTEXT_TOKEN_LNAME
1344:                            .equals(elementName)) {
1345:                        //TODO:we can put this into TokenCache ?.
1346:                        // Also store this Token into Extraneous Properties for use by RM
1347:                    }
1348:                } else {
1349:                    if (MessageConstants.DS_SIGNATURE_LNAME.equals(elementName)) {
1350:                        SignatureFilter.process(fpContext);
1351:                        processed = true;
1352:
1353:                    } else if (MessageConstants.XENC_ENCRYPTED_KEY_LNAME
1354:                            .equals(elementName)) {
1355:                        Iterator iter = null;
1356:                        try {
1357:                            //TODO: Try to keep a single SOAPFactory instance
1358:                            iter = current
1359:                                    .getChildElements(SOAPFactory
1360:                                            .newInstance()
1361:                                            .createName(
1362:                                                    MessageConstants.XENC_REFERENCE_LIST_LNAME,
1363:                                                    MessageConstants.XENC_PREFIX,
1364:                                                    MessageConstants.XENC_NS));
1365:                        } catch (Exception e) {
1366:                            log.log(Level.SEVERE,
1367:                                    "WSS0360.error.creating.rlhb", e);
1368:                            throw new XWSSecurityException(e);
1369:                        }
1370:                        if (iter.hasNext()) {
1371:                            EncryptionFilter.process(fpContext);
1372:                            processed = true;
1373:                        }
1374:
1375:                    } else if (MessageConstants.XENC_REFERENCE_LIST_LNAME
1376:                            .equals(elementName)) {
1377:                        EncryptionFilter.process(fpContext);
1378:                        processed = true;
1379:
1380:                    } else if (MessageConstants.ENCRYPTED_DATA_LNAME
1381:                            .equals(elementName)) {
1382:                        EncryptionFilter.process(fpContext);
1383:                        processed = true;
1384:                    } else {
1385:                        if (!HarnessUtil.isSecondaryHeaderElement(current)) {
1386:                            log
1387:                                    .log(Level.SEVERE,
1388:                                            "WSS0204.illegal.header.block",
1389:                                            elementName);
1390:                            HarnessUtil
1391:                                    .throwWssSoapFault("Unrecognized header block: "
1392:                                            + elementName);
1393:                        }
1394:                    }
1395:                }
1396:
1397:                return processed;
1398:            }
1399:
1400:            /*
1401:             * Validation of wsse:UsernameToken/wsu:Timestamp protected by
1402:             * signature/encryption should follow post verification of
1403:             * signature/encryption.
1404:             *
1405:             * A two-pass processing model is implemented, the first pass
1406:             * verifies signature/encryption, while the second, the token/
1407:             * timestamp.
1408:             *
1409:             * Note: Can be specification documented
1410:             *
1411:             * @param fpContext com.sun.xml.wss.FilterProcessingContext
1412:             *
1413:             * @throws com.sun.xml.wss.XWSSecurityException
1414:             */
1415:            private static void pProcess(FilterProcessingContext fpContext)
1416:                    throws XWSSecurityException {
1417:
1418:                SecurityHeader header = fpContext.getSecurableSoapMessage()
1419:                        .findSecurityHeader();
1420:
1421:                if (header == null) {
1422:                    SecurityPolicy policy = fpContext.getSecurityPolicy();
1423:                    if (policy != null) {
1424:                        if (PolicyTypeUtil.messagePolicy(policy)) {
1425:                            if (!((MessagePolicy) policy).isEmpty()) {
1426:                                log
1427:                                        .log(Level.SEVERE,
1428:                                                "WSS0253.invalid.Message");
1429:                                throw new XWSSecurityException(
1430:                                        "Message does not conform to configured policy: "
1431:                                                + "No Security Header found in incoming message");
1432:
1433:                            }
1434:                        } else {
1435:                            log.log(Level.SEVERE, "WSS0253.invalid.Message");
1436:                            throw new XWSSecurityException(
1437:                                    "Message does not conform to configured policy: "
1438:                                            + "No Security Header found in incoming message");
1439:                        }
1440:                    }
1441:
1442:                    return;
1443:                }
1444:
1445:                SOAPElement current = header.getCurrentHeaderBlockElement();
1446:                SOAPElement first = current;
1447:                SOAPElement prev = null;
1448:                while (current != null) {
1449:
1450:                    pProcessOnce(fpContext, current, false);
1451:                    if (fpContext.getMode() == FilterProcessingContext.DEFAULT
1452:                            && "EncryptedData".equals(current.getLocalName())
1453:                            && (prev != null)) {
1454:                        header.setCurrentHeaderElement(prev);
1455:
1456:                    } else {
1457:                        prev = current;
1458:                    }
1459:                    current = header.getCurrentHeaderBlockElement();
1460:                }
1461:
1462:                current = first;
1463:                header.setCurrentHeaderElement(current);
1464:
1465:                while (current != null) {
1466:                    pProcessOnce(fpContext, current, true);
1467:                    current = header.getCurrentHeaderBlockElement();
1468:                }
1469:
1470:            }
1471:
1472:            /*
1473:             * @param context Processing Context
1474:             */
1475:            public static void handleFault(ProcessingContext context) {
1476:                /**
1477:                 * TODO
1478:                 */
1479:            }
1480:
1481:            //COPIED FROM DECRYPTION PROCESSOR NOW
1482:            //COMBINE ALL LATER.
1483:            private static interface EncryptedData {
1484:                public boolean isElementData();
1485:
1486:                public boolean isAttachmentData();
1487:            }
1488:
1489:            private static class AttachmentData implements  EncryptedData {
1490:                private String cid = null;
1491:                private boolean contentOnly = false;
1492:
1493:                public AttachmentData(String cid, boolean co) {
1494:                    this .cid = cid;
1495:                    contentOnly = co;
1496:                }
1497:
1498:                public String getCID() {
1499:                    return cid;
1500:                }
1501:
1502:                public boolean isContentOnly() {
1503:                    return contentOnly;
1504:                }
1505:
1506:                public boolean equals(AttachmentData data) {
1507:                    if (cid != null && cid.equals(data.getCID())
1508:                            && (contentOnly == data.isContentOnly())) {
1509:                        return true;
1510:                    }
1511:                    return false;
1512:                }
1513:
1514:                public boolean isElementData() {
1515:                    return false;
1516:                }
1517:
1518:                public boolean isAttachmentData() {
1519:                    return true;
1520:                }
1521:            }
1522:
1523:            private static class EncryptedElement implements  EncryptedData {
1524:                private Element element;
1525:                private boolean contentOnly;
1526:                private EncryptionPolicy policy = null;
1527:
1528:                public EncryptedElement(Element element, boolean contentOnly) {
1529:                    this .element = element;
1530:                    this .contentOnly = contentOnly;
1531:                }
1532:
1533:                public Element getElement() {
1534:                    return element;
1535:                }
1536:
1537:                public boolean getContentOnly() {
1538:                    return contentOnly;
1539:                }
1540:
1541:                public boolean equals(EncryptedElement element) {
1542:                    EncryptedElement encryptedElement = (EncryptedElement) element;
1543:                    return (encryptedElement.getElement() == this .element && encryptedElement
1544:                            .getContentOnly() == this .contentOnly);
1545:                    //&& this.policy.equals(encryptedElement.getPolicy()));
1546:
1547:                }
1548:
1549:                public void setpolicy(EncryptionPolicy policy) {
1550:                    this .policy = policy;
1551:                }
1552:
1553:                public EncryptionPolicy getPolicy() {
1554:                    return policy;
1555:                }
1556:
1557:                public boolean isElementData() {
1558:                    return true;
1559:                }
1560:
1561:                public boolean isAttachmentData() {
1562:                    return false;
1563:                }
1564:            }
1565:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.