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