Convert from NULL macro to nullptr, remove unused zlib code.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactDecoder.cpp
1 /*
2  *  Copyright 2001-2010 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 "binding/SecurityPolicy.h"
26 #include "saml2/binding/SAML2Artifact.h"
27 #include "saml2/binding/SAML2MessageDecoder.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/MetadataProvider.h"
31
32 #include <xmltooling/logging.h>
33 #include <xmltooling/XMLToolingConfig.h>
34 #include <xmltooling/io/HTTPRequest.h>
35 #include <xmltooling/util/NDC.h>
36 #include <xmltooling/util/ReplayCache.h>
37
38 using namespace opensaml::saml2md;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2;
41 using namespace opensaml;
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace opensaml {
47     namespace saml2p {
48         class SAML_DLLLOCAL SAML2ArtifactDecoder : public SAML2MessageDecoder
49         {
50         public:
51             SAML2ArtifactDecoder() {}
52             virtual ~SAML2ArtifactDecoder() {}
53
54             xmltooling::XMLObject* decode(
55                 std::string& relayState,
56                 const GenericRequest& genericRequest,
57                 SecurityPolicy& policy
58                 ) const;
59         };
60
61         MessageDecoder* SAML_DLLLOCAL SAML2ArtifactDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
62         {
63             return new SAML2ArtifactDecoder();
64         }
65     };
66 };
67
68 XMLObject* SAML2ArtifactDecoder::decode(
69     string& relayState,
70     const GenericRequest& genericRequest,
71     SecurityPolicy& policy
72     ) const
73 {
74 #ifdef _DEBUG
75     xmltooling::NDC ndc("decode");
76 #endif
77     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Artifact");
78
79     log.debug("validating input");
80     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
81     if (!httpRequest)
82         throw BindingException("Unable to cast request object to HTTPRequest type.");
83     const char* SAMLart = httpRequest->getParameter("SAMLart");
84     if (!SAMLart)
85         throw BindingException("Request missing SAMLart query string or form parameter.");
86     const char* state = httpRequest->getParameter("RelayState");
87     if (state)
88         relayState = state;
89
90     if (!m_artifactResolver || !policy.getMetadataProvider() || !policy.getRole())
91         throw BindingException("Artifact binding requires ArtifactResolver and MetadataProvider implementations be supplied.");
92
93     // Import the artifact.
94     SAMLArtifact* artifact=nullptr;
95     try {
96         log.debug("processing encoded artifact (%s)", SAMLart);
97
98         // Check replay.
99         ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
100         if (replayCache) {
101             if (!replayCache->check("SAML2Artifact", SAMLart, time(nullptr) + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
102                 log.error("replay detected of artifact (%s)", SAMLart);
103                 throw BindingException("Rejecting replayed artifact ($1).", params(1,SAMLart));
104             }
105         }
106         else
107             log.warn("replay cache was not provided, this is a serious security risk!");
108
109         artifact = SAMLArtifact::parse(SAMLart);
110     }
111     catch (ArtifactException&) {
112         log.error("error parsing artifact (%s)", SAMLart);
113         throw;
114     }
115
116     // Check the type.
117     auto_ptr<SAML2Artifact> artifact2(dynamic_cast<SAML2Artifact*>(artifact));
118     if (!artifact2.get()) {
119         delete artifact;
120         log.error("wrong artifact type");
121         throw BindingException("Artifact binding requires SAML 2.0 artifact.");
122     }
123
124     log.debug("attempting to determine source of artifact...");
125     MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
126     mc.artifact = artifact;
127     mc.role = policy.getRole();
128     mc.protocol = samlconstants::SAML20P_NS;
129     pair<const EntityDescriptor*,const RoleDescriptor*> provider=policy.getMetadataProvider()->getEntityDescriptor(mc);
130     if (!provider.first) {
131         log.error(
132             "metadata lookup failed, unable to determine issuer of artifact (0x%s)",
133             SAMLArtifact::toHex(artifact->getBytes()).c_str()
134             );
135         throw BindingException("Metadata lookup failed, unable to determine artifact issuer.");
136     }
137
138     if (log.isDebugEnabled()) {
139         auto_ptr_char issuer(provider.first->getEntityID());
140         log.debug("lookup succeeded, artifact issued by (%s)", issuer.get());
141     }
142
143     if (!provider.second || !dynamic_cast<const SSODescriptorType*>(provider.second)) {
144         log.error("unable to find compatible SAML 2.0 role (%s) in metadata", policy.getRole()->toString().c_str());
145         throw BindingException("Unable to find compatible metadata role for artifact issuer.");
146     }
147     // Set issuer into policy.
148     policy.setIssuer(provider.first->getEntityID());
149     policy.setIssuerMetadata(provider.second);
150
151     log.debug("calling ArtifactResolver...");
152     auto_ptr<ArtifactResponse> response(
153         m_artifactResolver->resolve(*(artifact2.get()), dynamic_cast<const SSODescriptorType&>(*provider.second), policy)
154         );
155
156     // The policy should be enforced against the ArtifactResponse by the resolve step.
157     // Reset only the message state.
158     policy.reset(true);
159
160     // Now extract details from the payload and check that message.
161     XMLObject* payload = response->getPayload();
162     if (!payload) {
163         log.error("ArtifactResponse message did not contain a protocol message");
164         throw BindingException("ArtifactResponse message did not contain a protocol message.");
165     }
166     extractMessageDetails(*payload, genericRequest, samlconstants::SAML20P_NS, policy);
167     policy.evaluate(*payload, &genericRequest);
168
169     // Return the payload only.
170     response.release();
171     payload->detach();
172     return payload;
173 }