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 "saml2/binding/SAML2POSTDecoder.h"
26 #include "saml2/core/Protocols.h"
27 #include "saml2/metadata/Metadata.h"
28 #include "saml2/metadata/MetadataProvider.h"
29 #include "security/X509TrustEngine.h"
31 #include <log4cpp/Category.hh>
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/ReplayCache.h>
35 #include <xmltooling/validation/ValidatorSuite.h>
37 using namespace opensaml::saml2md;
38 using namespace opensaml::saml2p;
39 using namespace opensaml::saml2;
40 using namespace opensaml;
41 using namespace xmlsignature;
42 using namespace xmltooling;
43 using namespace log4cpp;
48 MessageDecoder* SAML_DLLLOCAL SAML2POSTDecoderFactory(const DOMElement* const & e)
50 return new SAML2POSTDecoder(e);
55 SAML2POSTDecoder::SAML2POSTDecoder(const DOMElement* e) {}
57 SAML2POSTDecoder::~SAML2POSTDecoder() {}
59 XMLObject* SAML2POSTDecoder::decode(
61 const RoleDescriptor*& issuer,
63 const HTTPRequest& httpRequest,
64 const MetadataProvider* metadataProvider,
66 const opensaml::TrustEngine* trustEngine
70 xmltooling::NDC ndc("decode");
72 Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2POST");
74 log.debug("validating input");
75 if (strcmp(httpRequest.getMethod(),"POST"))
77 const char* msg = httpRequest.getParameter("SAMLResponse");
79 msg = httpRequest.getParameter("SAMLRequest");
82 const char* state = httpRequest.getParameter("RelayState");
88 // Decode the base64 into SAML.
90 XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
92 throw BindingException("Unable to decode base64 in POST binding message.");
93 log.debug("decoded SAML message:\n%s", decoded);
94 istringstream is(reinterpret_cast<char*>(decoded));
95 XMLString::release(&decoded);
97 // Parse and bind the document into an XMLObject.
98 DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
99 : XMLToolingConfig::getConfig().getParser()).parse(is);
100 XercesJanitor<DOMDocument> janitor(doc);
101 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
104 StatusResponseType* response = NULL;
105 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
107 response = dynamic_cast<StatusResponseType*>(xmlObject.get());
109 throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
112 /* For SAML 2, the issuer can be established either from the message, or in some profiles
113 * it's possible to omit it and defer to assertions in a Response.
114 * The Issuer is later matched against metadata, and then trust checking can be applied.
116 const Issuer* claimedIssuer = request ? request->getIssuer() : response->getIssuer();
117 if (!claimedIssuer) {
118 // Check assertion option. I cannot resist the variable name, for the sake of google.
119 const Response* assbag = dynamic_cast<const Response*>(response);
121 const vector<Assertion*>& assertions=assbag->getAssertions();
122 if (!assertions.empty())
123 claimedIssuer = assertions.front()->getIssuer();
127 const EntityDescriptor* provider=NULL;
130 SchemaValidators.validate(xmlObject.get());
132 Signature* signature = request ? request->getSignature() : response->getSignature();
134 // Check destination URL.
135 auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
136 const char* dest2 = httpRequest.getRequestURL();
137 if (signature && !dest.get() || !*(dest.get())) {
138 log.error("signed SAML message missing Destination attribute");
139 throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
141 else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
142 log.error("POST targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
143 throw BindingException("SAML message delivered with POST to incorrect server URL.");
147 time_t now = time(NULL);
148 if ((request ? request->getIssueInstant()->getEpoch() : response->getIssueInstant()->getEpoch())
149 < now-(2*XMLToolingConfig::getConfig().clock_skew_secs))
150 throw BindingException("Detected expired POST binding message.");
153 ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
155 auto_ptr_char id(xmlObject->getXMLID());
156 if (!replayCache->check("SAML2POST", id.get(), response->getIssueInstant()->getEpoch() + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
157 log.error("replay detected of response ID (%s)", id.get());
158 throw BindingException("Rejecting replayed response ID ($1).", params(1,id.get()));
162 log.warn("replay cache was not provided, this is a serious security risk!");
165 issuerTrusted = false;
166 log.debug("attempting to establish issuer and integrity of message...");
168 // If we can't identify the issuer, we're done, since we can't lookup or verify anything.
169 if (!claimedIssuer || !claimedIssuer->getName()) {
170 log.warn("unable to establish identity of message issuer");
171 return xmlObject.release();
173 else if (claimedIssuer->getFormat() && !XMLString::equals(claimedIssuer->getFormat(), NameIDType::ENTITY)) {
174 auto_ptr_char iformat(claimedIssuer->getFormat());
175 log.warn("message issuer was in an unsupported format (%s)", iformat.get());
176 return xmlObject.release();
179 log.debug("searching metadata for assertion issuer...");
180 provider=metadataProvider ? metadataProvider->getEntityDescriptor(claimedIssuer->getName()) : NULL;
182 log.debug("matched assertion issuer against metadata, searching for applicable role...");
183 issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
185 if (trustEngine && signature) {
186 issuerTrusted = trustEngine->validate(*signature, *issuer, metadataProvider->getKeyResolver());
187 if (!issuerTrusted) {
188 log.error("unable to verify signature on message with supplied trust engine");
189 throw BindingException("Message signature failed verification.");
193 log.warn("unable to verify integrity of the message, leaving untrusted");
197 log.warn("unable to find compatible SAML 2.0 role (%s) in metadata", role->toString().c_str());
199 if (log.isDebugEnabled()) {
200 auto_ptr_char iname(provider->getEntityID());
201 log.debug("message from (%s), integrity %sverified", iname.get(), issuerTrusted ? "" : "NOT ");
205 auto_ptr_char temp(claimedIssuer->getName());
206 log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
209 catch (XMLToolingException& ex) {
211 if (!claimedIssuer || !claimedIssuer->getName())
213 if (!metadataProvider || !(provider=metadataProvider->getEntityDescriptor(claimedIssuer->getName(), false))) {
215 auto_ptr_char iname(claimedIssuer->getName());
217 ex.addProperty("entityID", iname.get());
222 issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
223 if (issuer) annotateException(&ex,issuer); // throws it
224 annotateException(&ex,provider); // throws it
227 return xmlObject.release();