Boost changes
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactDecoder.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2ArtifactDecoder.cpp
23  *
24  * SAML 2.0 Artifact binding message decoder.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/SecurityPolicy.h"
30 #include "saml2/binding/SAML2Artifact.h"
31 #include "saml2/binding/SAML2MessageDecoder.h"
32 #include "saml2/core/Protocols.h"
33 #include "saml2/metadata/Metadata.h"
34 #include "saml2/metadata/MetadataProvider.h"
35
36 #include <xmltooling/logging.h>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/io/HTTPRequest.h>
39 #include <xmltooling/util/NDC.h>
40 #include <xmltooling/util/ReplayCache.h>
41
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2;
45 using namespace opensaml;
46 using namespace xmltooling::logging;
47 using namespace xmltooling;
48 using namespace std;
49
50 namespace opensaml {
51     namespace saml2p {
52         class SAML_DLLLOCAL SAML2ArtifactDecoder : public SAML2MessageDecoder
53         {
54         public:
55             SAML2ArtifactDecoder() {}
56             virtual ~SAML2ArtifactDecoder() {}
57
58             xmltooling::XMLObject* decode(
59                 std::string& relayState,
60                 const GenericRequest& genericRequest,
61                 SecurityPolicy& policy
62                 ) const;
63         };
64
65         MessageDecoder* SAML_DLLLOCAL SAML2ArtifactDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
66         {
67             return new SAML2ArtifactDecoder();
68         }
69     };
70 };
71
72 XMLObject* SAML2ArtifactDecoder::decode(
73     string& relayState,
74     const GenericRequest& genericRequest,
75     SecurityPolicy& policy
76     ) const
77 {
78 #ifdef _DEBUG
79     xmltooling::NDC ndc("decode");
80 #endif
81     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Artifact");
82
83     log.debug("validating input");
84     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
85     if (!httpRequest)
86         throw BindingException("Unable to cast request object to HTTPRequest type.");
87     const char* SAMLart = httpRequest->getParameter("SAMLart");
88     if (!SAMLart)
89         throw BindingException("Request missing SAMLart query string or form parameter.");
90     const char* state = httpRequest->getParameter("RelayState");
91     if (state)
92         relayState = state;
93
94     if (!m_artifactResolver || !policy.getMetadataProvider() || !policy.getRole())
95         throw BindingException("Artifact binding requires ArtifactResolver and MetadataProvider implementations be supplied.");
96
97     // Import the artifact.
98     auto_ptr<SAMLArtifact> artifact;
99     try {
100         log.debug("processing encoded artifact (%s)", SAMLart);
101
102         // Check replay.
103         ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
104         if (replayCache) {
105             if (!replayCache->check("SAML2Artifact", SAMLart, time(nullptr) + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
106                 log.error("replay detected of artifact (%s)", SAMLart);
107                 throw BindingException("Rejecting replayed artifact ($1).", params(1,SAMLart));
108             }
109         }
110         else
111             log.warn("replay cache was not provided, this is a serious security risk!");
112
113         artifact.reset(SAMLArtifact::parse(SAMLart));
114     }
115     catch (ArtifactException&) {
116         log.error("error parsing artifact (%s)", SAMLart);
117         throw;
118     }
119
120     // Check the type.
121     SAML2Artifact* artifact2 = dynamic_cast<SAML2Artifact*>(artifact.get());
122     if (!artifact2) {
123         log.error("wrong artifact type");
124         throw BindingException("Artifact binding requires SAML 2.0 artifact.");
125     }
126
127     log.debug("attempting to determine source of artifact...");
128     MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
129     mc.artifact = artifact.get();
130     mc.role = policy.getRole();
131     mc.protocol = samlconstants::SAML20P_NS;
132     pair<const EntityDescriptor*,const RoleDescriptor*> provider=policy.getMetadataProvider()->getEntityDescriptor(mc);
133     if (!provider.first) {
134         log.error(
135             "metadata lookup failed, unable to determine issuer of artifact (0x%s)",
136             SAMLArtifact::toHex(artifact->getBytes()).c_str()
137             );
138         throw BindingException("Metadata lookup failed, unable to determine artifact issuer.");
139     }
140
141     if (log.isDebugEnabled()) {
142         auto_ptr_char issuer(provider.first->getEntityID());
143         log.debug("lookup succeeded, artifact issued by (%s)", issuer.get());
144     }
145
146     if (!provider.second || !dynamic_cast<const SSODescriptorType*>(provider.second)) {
147         log.error("unable to find compatible SAML 2.0 role (%s) in metadata", policy.getRole()->toString().c_str());
148         throw BindingException("Unable to find compatible metadata role for artifact issuer.");
149     }
150     // Set issuer into policy.
151     policy.setIssuer(provider.first->getEntityID());
152     policy.setIssuerMetadata(provider.second);
153
154     log.debug("calling ArtifactResolver...");
155     auto_ptr<ArtifactResponse> response(
156         m_artifactResolver->resolve(*artifact2, dynamic_cast<const SSODescriptorType&>(*provider.second), policy)
157         );
158
159     // The policy should be enforced against the ArtifactResponse by the resolve step.
160     // Reset only the message state.
161     policy.reset(true);
162
163     // Now extract details from the payload and check that message.
164     XMLObject* payload = response->getPayload();
165     if (!payload) {
166         log.error("ArtifactResponse message did not contain a protocol message");
167         throw BindingException("ArtifactResponse message did not contain a protocol message.");
168     }
169     extractMessageDetails(*payload, genericRequest, samlconstants::SAML20P_NS, policy);
170     policy.evaluate(*payload, &genericRequest);
171
172     // Return the payload only.
173     response.release();
174     payload->detach();
175     return payload;
176 }