2 * Copyright 2001-2006 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SAML2POSTDecoder.cpp
20 * SAML 2.0 HTTP POST binding message encoder
24 #include "exceptions.h"
25 #include "saml/binding/ReplayCache.h"
26 #include "saml2/binding/SAML2POSTDecoder.h"
27 #include "saml2/core/Protocols.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataProvider.h"
30 #include "security/X509TrustEngine.h"
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/util/NDC.h>
36 using namespace opensaml::saml2md;
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2;
39 using namespace opensaml;
40 using namespace xmlsignature;
41 using namespace xmltooling;
42 using namespace log4cpp;
47 MessageDecoder* SAML_DLLLOCAL SAML2POSTDecoderFactory(const DOMElement* const & e)
49 return new SAML2POSTDecoder(e);
54 SAML2POSTDecoder::SAML2POSTDecoder(const DOMElement* e) {}
56 SAML2POSTDecoder::~SAML2POSTDecoder() {}
58 XMLObject* SAML2POSTDecoder::decode(
60 const RoleDescriptor*& issuer,
62 const HTTPRequest& httpRequest,
63 const MetadataProvider* metadataProvider,
65 const X509TrustEngine* trustEngine
69 xmltooling::NDC ndc("decode");
71 Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2POST");
73 log.debug("validating input");
74 if (strcmp(httpRequest.getMethod(),"POST"))
76 const char* msg = httpRequest.getParameter("SAMLResponse");
78 msg = httpRequest.getParameter("SAMLRequest");
81 const char* state = httpRequest.getParameter("RelayState");
87 // Decode the base64 into SAML.
89 XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
91 throw BindingException("Unable to decode base64 in POST binding message.");
92 log.debug("decoded SAML message:\n%s", decoded);
93 istringstream is(reinterpret_cast<char*>(decoded));
94 XMLString::release(&decoded);
96 // Parse and bind the document into an XMLObject.
97 DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
98 : XMLToolingConfig::getConfig().getParser()).parse(is);
99 XercesJanitor<DOMDocument> janitor(doc);
100 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
103 StatusResponseType* response = NULL;
104 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
106 response = dynamic_cast<StatusResponseType*>(xmlObject.get());
108 throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
111 /* For SAML 2, the issuer can be established either from the message, or in some profiles
112 * it's possible to omit it and defer to assertions in a Response.
113 * The Issuer is later matched against metadata, and then trust checking can be applied.
115 const Issuer* claimedIssuer = request ? request->getIssuer() : response->getIssuer();
116 if (!claimedIssuer) {
117 // Check assertion option. I cannot resist the variable name, for the sake of google.
118 const Response* assbag = dynamic_cast<const Response*>(response);
120 const vector<Assertion*>& assertions=assbag->getAssertions();
121 if (!assertions.empty())
122 claimedIssuer = assertions.front()->getIssuer();
126 const EntityDescriptor* provider=NULL;
129 SchemaValidators.validate(xmlObject.get());
131 Signature* signature = request ? request->getSignature() : response->getSignature();
133 // Check destination URL.
134 auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
135 const char* dest2 = httpRequest.getRequestURL();
136 if (signature && !dest.get() || !*(dest.get())) {
137 log.error("signed SAML message missing Destination attribute");
138 throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
140 else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
141 log.error("POST targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
142 throw BindingException("SAML message delivered with POST to incorrect server URL.");
146 time_t now = time(NULL);
147 if ((request ? request->getIssueInstant()->getEpoch() : response->getIssueInstant()->getEpoch())
148 < now-(2*XMLToolingConfig::getConfig().clock_skew_secs))
149 throw BindingException("Detected expired POST binding message.");
152 ReplayCache* replayCache = SAMLConfig::getConfig().getReplayCache();
154 auto_ptr_char id(xmlObject->getXMLID());
155 if (!replayCache->check("SAML2POST", id.get(), response->getIssueInstant()->getEpoch() + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
156 log.error("replay detected of response ID (%s)", id.get());
157 throw BindingException("Rejecting replayed response ID ($1).", params(1,id.get()));
161 log.warn("replay cache was not provided, this is a serious security risk!");
164 issuerTrusted = false;
165 log.debug("attempting to establish issuer and integrity of message...");
167 // If we can't identify the issuer, we're done, since we can't lookup or verify anything.
168 if (!claimedIssuer || !claimedIssuer->getName()) {
169 log.warn("unable to establish identity of message issuer");
170 return xmlObject.release();
172 else if (claimedIssuer->getFormat() && !XMLString::equals(claimedIssuer->getFormat(), NameIDType::ENTITY)) {
173 auto_ptr_char iformat(claimedIssuer->getFormat());
174 log.warn("message issuer was in an unsupported format (%s)", iformat.get());
175 return xmlObject.release();
178 log.debug("searching metadata for assertion issuer...");
179 provider=metadataProvider ? metadataProvider->getEntityDescriptor(claimedIssuer->getName()) : NULL;
181 log.debug("matched assertion issuer against metadata, searching for applicable role...");
182 issuer=provider->getRoleDescriptor(*role, SAMLConstants::SAML20P_NS);
184 if (trustEngine && signature) {
185 issuerTrusted = static_cast<const TrustEngine*>(trustEngine)->validate(
186 *signature, *issuer, metadataProvider->getKeyResolver()
188 if (!issuerTrusted) {
189 log.error("unable to verify signature on message with supplied trust engine");
190 throw BindingException("Message signature failed verification.");
194 log.warn("unable to verify integrity of the message, leaving untrusted");
198 log.warn("unable to find compatible SAML 2.0 role (%s) in metadata", role->toString().c_str());
200 if (log.isDebugEnabled()) {
201 auto_ptr_char iname(provider->getEntityID());
202 log.debug("message from (%s), integrity %sverified", iname.get(), issuerTrusted ? "" : "NOT ");
206 auto_ptr_char temp(claimedIssuer->getName());
207 log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
210 catch (XMLToolingException& ex) {
212 if (!claimedIssuer || !claimedIssuer->getName())
214 if (!metadataProvider || !(provider=metadataProvider->getEntityDescriptor(claimedIssuer->getName(), false))) {
216 auto_ptr_char iname(claimedIssuer->getName());
218 ex.addProperty("entityID", iname.get());
223 issuer=provider->getRoleDescriptor(*role, SAMLConstants::SAML20P_NS);
224 if (issuer) annotateException(&ex,issuer); // throws it
225 annotateException(&ex,provider); // throws it
228 return xmlObject.release();