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 * SAML2RedirectDecoder.cpp
20 * SAML 2.0 HTTP Redirect binding message encoder
24 #include "exceptions.h"
25 #include "saml2/binding/SAML2Redirect.h"
26 #include "saml2/binding/SAML2RedirectDecoder.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>
35 #include <xmltooling/util/ReplayCache.h>
36 #include <xmltooling/validation/ValidatorSuite.h>
38 using namespace opensaml::saml2md;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace log4cpp;
49 MessageDecoder* SAML_DLLLOCAL SAML2RedirectDecoderFactory(const DOMElement* const & e)
51 return new SAML2RedirectDecoder(e);
56 SAML2RedirectDecoder::SAML2RedirectDecoder(const DOMElement* e) {}
58 SAML2RedirectDecoder::~SAML2RedirectDecoder() {}
60 XMLObject* SAML2RedirectDecoder::decode(
62 const RoleDescriptor*& issuer,
63 const XMLCh*& securityMech,
64 const HTTPRequest& httpRequest,
65 const MetadataProvider* metadataProvider,
67 const opensaml::TrustEngine* trustEngine
71 xmltooling::NDC ndc("decode");
73 Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Redirect");
75 log.debug("validating input");
76 if (strcmp(httpRequest.getMethod(),"GET"))
78 const char* msg = httpRequest.getParameter("SAMLResponse");
80 msg = httpRequest.getParameter("SAMLRequest");
83 const char* state = httpRequest.getParameter("RelayState");
88 state = httpRequest.getParameter("SAMLEncoding");
89 if (state && strcmp(state,samlconstants::SAML20_BINDING_URL_ENCODING_DEFLATE)) {
90 log.warn("SAMLEncoding (%s) was not recognized", state);
94 // Decode the compressed message into SAML. First we base64-decode it.
96 XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
98 throw BindingException("Unable to decode base64 in Redirect binding message.");
100 // Now we have to inflate it.
102 if (inflate((char*)decoded, x, str)==0) {
103 XMLString::release(&decoded);
104 throw BindingException("Unable to inflate Redirect binding message.");
107 XMLString::release(&decoded);
109 // Parse and bind the document into an XMLObject.
110 DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
111 : XMLToolingConfig::getConfig().getParser()).parse(str);
112 XercesJanitor<DOMDocument> janitor(doc);
113 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
116 StatusResponseType* response = NULL;
117 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
119 response = dynamic_cast<StatusResponseType*>(xmlObject.get());
121 throw BindingException("XML content for SAML 2.0 HTTP-Redirect Decoder must be a SAML 2.0 protocol message.");
124 /* For SAML 2, the issuer can be established either from the message, or in some profiles
125 * it's possible to omit it and defer to assertions in a Response.
126 * The Issuer is later matched against metadata, and then trust checking can be applied.
128 const Issuer* claimedIssuer = request ? request->getIssuer() : response->getIssuer();
129 if (!claimedIssuer) {
130 // Check assertion option. I cannot resist the variable name, for the sake of google.
131 const Response* assbag = dynamic_cast<const Response*>(response);
133 const vector<Assertion*>& assertions=assbag->getAssertions();
134 if (!assertions.empty())
135 claimedIssuer = assertions.front()->getIssuer();
139 const EntityDescriptor* provider=NULL;
142 SchemaValidators.validate(xmlObject.get());
144 // Check destination URL.
145 auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
146 const char* dest2 = httpRequest.getRequestURL();
147 if (!dest.get() || !*(dest.get())) {
148 log.error("signed SAML message missing Destination attribute");
149 throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
151 else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
152 log.error("Redirect targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
153 throw BindingException("SAML message delivered with Redirect to incorrect server URL.");
157 time_t now = time(NULL);
158 if ((request ? request->getIssueInstant()->getEpoch() : response->getIssueInstant()->getEpoch())
159 < now-(2*XMLToolingConfig::getConfig().clock_skew_secs))
160 throw BindingException("Detected expired Redirect binding message.");
163 ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
165 auto_ptr_char id(xmlObject->getXMLID());
166 if (!replayCache->check("SAML2Redirect", id.get(), response->getIssueInstant()->getEpoch() + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
167 log.error("replay detected of message ID (%s)", id.get());
168 throw BindingException("Rejecting replayed message ID ($1).", params(1,id.get()));
172 log.warn("replay cache was not provided, this is a serious security risk!");
175 securityMech = false;
176 log.debug("attempting to establish issuer and integrity of message...");
178 // If we can't identify the issuer, we're done, since we can't lookup or verify anything.
179 if (!claimedIssuer || !claimedIssuer->getName()) {
180 log.warn("unable to establish identity of message issuer");
181 return xmlObject.release();
183 else if (claimedIssuer->getFormat() && !XMLString::equals(claimedIssuer->getFormat(), NameIDType::ENTITY)) {
184 auto_ptr_char iformat(claimedIssuer->getFormat());
185 log.warn("message issuer was in an unsupported format (%s)", iformat.get());
186 return xmlObject.release();
189 log.debug("searching metadata for assertion issuer...");
190 provider=metadataProvider ? metadataProvider->getEntityDescriptor(claimedIssuer->getName()) : NULL;
192 log.debug("matched assertion issuer against metadata, searching for applicable role...");
193 issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
196 if (trustEngine && signature) {
197 if (!trustEngine->validate(*signature, *issuer, metadataProvider->getKeyResolver())) {
198 log.error("unable to verify signature on message with supplied trust engine");
199 throw BindingException("Message signature failed verification.");
202 securityMech = samlconstants::SAML20P_NS;
206 log.warn("unable to authenticate the message, leaving untrusted");
211 log.warn("unable to find compatible SAML 2.0 role (%s) in metadata", role->toString().c_str());
213 if (log.isDebugEnabled()) {
214 auto_ptr_char iname(provider->getEntityID());
215 log.debug("message from (%s), integrity %sverified", iname.get(), securityMech ? "" : "NOT ");
219 auto_ptr_char temp(claimedIssuer->getName());
220 log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
223 catch (XMLToolingException& ex) {
225 if (!claimedIssuer || !claimedIssuer->getName())
227 if (!metadataProvider || !(provider=metadataProvider->getEntityDescriptor(claimedIssuer->getName(), false))) {
229 auto_ptr_char iname(claimedIssuer->getName());
231 ex.addProperty("entityID", iname.get());
236 issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
237 if (issuer) annotateException(&ex,issuer); // throws it
238 annotateException(&ex,provider); // throws it
241 return xmlObject.release();