No need for message rule.
[shibboleth/cpp-sp.git] / adfs / adfs.cpp
index 133736f..f853bb2 100644 (file)
@@ -1,25 +1,25 @@
-/*\r
- *  Copyright 2001-2005 Internet2\r
- * \r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *     http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-/**\r
- * adfs.cpp\r
- *\r
- * ADFSv1 extension library\r
- */\r
-\r
+/*
+ *  Copyright 2001-2005 Internet2
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * adfs.cpp
+ *
+ * ADFSv1 extension library
+ */
+
 #if defined (_MSC_VER) || defined(__BORLANDC__)
 # include "config_win32.h"
 #else
 #ifdef WIN32
 # define _CRT_NONSTDC_NO_DEPRECATE 1
 # define _CRT_SECURE_NO_DEPRECATE 1
-# define ADFS_EXPORTS __declspec(dllexport)\r
-#else\r
-# define ADFS_EXPORTS\r
+# define ADFS_EXPORTS __declspec(dllexport)
+#else
+# define ADFS_EXPORTS
 #endif
-\r
-#include <shibsp/base.h>\r
-#include <shibsp/exceptions.h>\r
-#include <shibsp/Application.h>\r
-#include <shibsp/ServiceProvider.h>\r
-#include <shibsp/SessionCache.h>\r
-#include <shibsp/SPConfig.h>\r
-#include <shibsp/handler/AssertionConsumerService.h>\r
-#include <shibsp/handler/LogoutHandler.h>\r
+
+#include <shibsp/base.h>
+#include <shibsp/exceptions.h>
+#include <shibsp/Application.h>
+#include <shibsp/ServiceProvider.h>
+#include <shibsp/SessionCache.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/handler/AssertionConsumerService.h>
+#include <shibsp/handler/LogoutHandler.h>
 #include <shibsp/handler/SessionInitiator.h>
+#include <xmltooling/logging.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/URLEncoder.h>
 #include <xmltooling/util/XMLHelper.h>
-#include <log4cpp/Category.hh>
 #include <xercesc/util/XMLUniDefs.hpp>
-\r
-#ifndef SHIBSP_LITE\r
+
+#ifndef SHIBSP_LITE
 # include <shibsp/attribute/Attribute.h>
 # include <shibsp/attribute/filtering/AttributeFilter.h>
 # include <shibsp/attribute/filtering/BasicFilteringContext.h>
 # include <shibsp/attribute/resolver/AttributeExtractor.h>
 # include <shibsp/attribute/resolver/ResolutionContext.h>
-# include <saml/SAMLConfig.h>\r
-# include <saml/saml1/core/Assertions.h>\r
-# include <saml/saml1/profile/AssertionValidator.h>\r
-# include <saml/saml2/core/Assertions.h>\r
-# include <saml/saml2/metadata/Metadata.h>\r
+# include <saml/SAMLConfig.h>
+# include <saml/saml1/core/Assertions.h>
+# include <saml/saml1/profile/AssertionValidator.h>
+# include <saml/saml2/core/Assertions.h>
+# include <saml/saml2/metadata/Metadata.h>
 # include <saml/saml2/metadata/EndpointManager.h>
 # include <xmltooling/impl/AnyElement.h>
-# include <xmltooling/validation/ValidatorSuite.h>\r
-using namespace opensaml::saml2md;\r
-#endif\r
-using namespace shibsp;\r
-using namespace opensaml;\r
-using namespace xmltooling;\r
-using namespace xercesc;\r
-using namespace log4cpp;\r
-using namespace std;\r
-\r
-#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"\r
-#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"\r
-\r
-namespace {\r
-\r
+# include <xmltooling/validation/ValidatorSuite.h>
+using namespace opensaml::saml2md;
+#endif
+using namespace shibsp;
+using namespace opensaml;
+using namespace xmltooling::logging;
+using namespace xmltooling;
+using namespace xercesc;
+using namespace std;
+
+#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
+#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
+
+namespace {
+
+#ifndef SHIBSP_LITE
+    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
+    {
+        auto_ptr_XMLCh m_ns;
+    public:
+        ADFSDecoder() : m_ns(WSTRUST_NS) {}
+        virtual ~ADFSDecoder() {}
+        
+        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
+    };
+
+    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
+    {
+        return new ADFSDecoder();
+    }
+#endif
+
 #if defined (_MSC_VER)
     #pragma warning( push )
     #pragma warning( disable : 4250 )
@@ -129,7 +146,7 @@ namespace {
         ADFSConsumer(const DOMElement* e, const char* appId)
             : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
 #ifndef SHIBSP_LITE
-                ,m_binding(WSFED_NS)
+                ,m_protocol(WSFED_NS)
 #endif
             {}
         virtual ~ADFSConsumer() {}
@@ -143,7 +160,7 @@ namespace {
             const PropertySet* settings,
             const XMLObject& xmlObject
             ) const;
-        auto_ptr_XMLCh m_binding;
+        auto_ptr_XMLCh m_protocol;
 #endif
     };
 
@@ -209,23 +226,6 @@ namespace {
     #pragma warning( pop )
 #endif
 
-#ifndef SHIBSP_LITE
-    class ADFSDecoder : public MessageDecoder\r
-    {\r
-        auto_ptr_XMLCh m_ns;
-    public:\r
-        ADFSDecoder() : m_ns(WSTRUST_NS) {}\r
-        virtual ~ADFSDecoder() {}\r
-        \r
-        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;\r
-    };\r
-\r
-    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)\r
-    {\r
-        return new ADFSDecoder();\r
-    }\r
-#endif\r
-\r
     SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
     {
         return new ADFSSessionInitiator(p.first, p.second);
@@ -235,18 +235,18 @@ namespace {
     {
         return new ADFSLogout(p.first, p.second);
     }
-\r
+
     Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
     {
         return new ADFSLogoutInitiator(p.first, p.second);
-    }\r
-\r
-    const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);\r
-    const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);\r
-};\r
-\r
-extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)\r
-{\r
+    }
+
+    const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);
+    const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);
+};
+
+extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
+{
     SPConfig& conf=SPConfig::getConfig();
     conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
     conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
@@ -255,25 +255,25 @@ extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
 #ifndef SHIBSP_LITE
     SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
     XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
-    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityTokenResponse"), new AnyElementBuilder());
-#endif\r
-    return 0;\r
-}\r
-\r
-extern "C" void ADFS_EXPORTS xmltooling_extension_term()\r
-{\r
-    /* should get unregistered during normal shutdown...\r
-    SPConfig& conf=SPConfig::getConfig();\r
-    conf.SessionInitiatorManager.deregisterFactory("ADFS");\r
-    conf.LogoutInitiatorManager.deregisterFactory("ADFS");\r
-    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");\r
-    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);\r
+    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
+#endif
+    return 0;
+}
+
+extern "C" void ADFS_EXPORTS xmltooling_extension_term()
+{
+    /* should get unregistered during normal shutdown...
+    SPConfig& conf=SPConfig::getConfig();
+    conf.SessionInitiatorManager.deregisterFactory("ADFS");
+    conf.LogoutInitiatorManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
 #ifndef SHIBSP_LITE
     SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
-#endif\r
-    */\r
-}\r
-\r
+#endif
+    */
+}
+
 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
 {
     // We have to know the IdP to function.
@@ -422,17 +422,17 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
 
     preserveRelayState(app, httpResponse, relayState);
 
-    // UTC timestamp\r
-#ifndef HAVE_GMTIME_R\r
-    time_t epoch=time(NULL);\r
-    struct tm* ptime=gmtime(&epoch);\r
-#else\r
-    struct tm res;\r
-    struct tm* ptime=gmtime_r(&epoch,&res);\r
-#endif\r
-    char timebuf[32];\r
-    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
-\r
+    // UTC timestamp
+    time_t epoch=time(NULL);
+#ifndef HAVE_GMTIME_R
+    struct tm* ptime=gmtime(&epoch);
+#else
+    struct tm res;
+    struct tm* ptime=gmtime_r(&epoch,&res);
+#endif
+    char timebuf[32];
+    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
+
     auto_ptr_char dest(ep->getLocation());
     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
 
@@ -446,53 +446,53 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
     return make_pair(false,0);
 #endif
 }
-\r
+
 #ifndef SHIBSP_LITE
 
-XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const\r
-{\r
-#ifdef _DEBUG\r
-    xmltooling::NDC ndc("decode");\r
-#endif\r
-    Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");\r
-\r
-    log.debug("validating input");\r
-    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);\r
-    if (!httpRequest)\r
-        throw BindingException("Unable to cast request object to HTTPRequest type.");\r
-    if (strcmp(httpRequest->getMethod(),"POST"))\r
-        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));\r
-    const char* param = httpRequest->getParameter("wa");\r
-    if (!param || strcmp(param, "wsignin1.0"))\r
-        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");\r
-    param = httpRequest->getParameter("wctx");\r
-    if (param)\r
-        relayState = param;\r
-\r
-    param = httpRequest->getParameter("wresult");\r
-    if (!param)\r
-        throw BindingException("Request missing wresult parameter.");\r
-\r
-    log.debug("decoded ADFS response:\n%s", param);\r
-\r
-    // Parse and bind the document into an XMLObject.\r
-    istringstream is(param);\r
-    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()\r
-        : XMLToolingConfig::getConfig().getParser()).parse(is); \r
-    XercesJanitor<DOMDocument> janitor(doc);\r
-    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
-    janitor.release();\r
-\r
-    if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))\r
-        throw BindingException("Decoded message was not of the appropriate type.");\r
-\r
-    if (!policy.getValidating())\r
-        SchemaValidators.validate(xmlObject.get());\r
-\r
-    // Run through the policy.\r
-    policy.evaluate(*xmlObject.get(), &genericRequest);\r
-    \r
-    return xmlObject.release();\r
+XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
+{
+#ifdef _DEBUG
+    xmltooling::NDC ndc("decode");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
+
+    log.debug("validating input");
+    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
+    if (!httpRequest)
+        throw BindingException("Unable to cast request object to HTTPRequest type.");
+    if (strcmp(httpRequest->getMethod(),"POST"))
+        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
+    const char* param = httpRequest->getParameter("wa");
+    if (!param || strcmp(param, "wsignin1.0"))
+        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
+    param = httpRequest->getParameter("wctx");
+    if (param)
+        relayState = param;
+
+    param = httpRequest->getParameter("wresult");
+    if (!param)
+        throw BindingException("Request missing wresult parameter.");
+
+    log.debug("decoded ADFS response:\n%s", param);
+
+    // Parse and bind the document into an XMLObject.
+    istringstream is(param);
+    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
+        : XMLToolingConfig::getConfig().getParser()).parse(is); 
+    XercesJanitor<DOMDocument> janitor(doc);
+    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
+    janitor.release();
+
+    if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
+        throw BindingException("Decoded message was not of the appropriate type.");
+
+    if (!policy.getValidating())
+        SchemaValidators.validate(xmlObject.get());
+
+    // Skip policy step here, there's no security in the wrapper.
+    // policy.evaluate(*xmlObject.get(), &genericRequest);
+    
+    return xmlObject.release();
 }
 
 string ADFSConsumer::implementProtocol(
@@ -520,7 +520,7 @@ string ADFSConsumer::implementProtocol(
 
     // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
     // and signature verification, assuming the relevant rules are configured.
-    policy.evaluate(*token);
+    policy.evaluate(*token, NULL, m_protocol.get());
     
     // If no security is in place now, we kick it.
     if (!policy.isSecure())
@@ -561,7 +561,7 @@ string ADFSConsumer::implementProtocol(
 
     // We've successfully "accepted" the SSO token.
     // To complete processing, we need to extract and resolve attributes and then create the session.
-    multimap<string,Attribute*> resolvedAttributes;
+    vector<Attribute*> resolvedAttributes;
     AttributeExtractor* extractor = application.getAttributeExtractor();
     if (extractor) {
         m_log.debug("extracting pushed attributes...");
@@ -591,7 +591,7 @@ string ADFSConsumer::implementProtocol(
             catch (exception& ex) {
                 m_log.error("caught exception filtering attributes: %s", ex.what());
                 m_log.error("dumping extracted attributes due to filtering exception");
-                for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,shibsp::Attribute>());
+                for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
                 resolvedAttributes.clear();
             }
         }
@@ -611,7 +611,7 @@ string ADFSConsumer::implementProtocol(
         resolveAttributes(
             application,
             issuerMetadata,
-            m_binding.get(),
+            m_protocol.get(),
             nameid.get(),
             ssoStatement->getAuthenticationMethod(),
             NULL,
@@ -625,7 +625,7 @@ string ADFSConsumer::implementProtocol(
         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
 
         // Copy over new attributes, and transfer ownership.
-        resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
+        resolvedAttributes.insert(resolvedAttributes.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
         ctx->getResolvedAttributes().clear();
     }
 
@@ -635,7 +635,7 @@ string ADFSConsumer::implementProtocol(
             application,
             httpRequest.getRemoteAddr().c_str(),
             issuerMetadata,
-            m_binding.get(),
+            m_protocol.get(),
             nameid.get(),
             ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
             NULL,
@@ -644,11 +644,11 @@ string ADFSConsumer::implementProtocol(
             &tokens,
             &resolvedAttributes
             );
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
+        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
         return key;
     }
     catch (exception&) {
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
+        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
         throw;
     }
 }