7fedc014a3a7f6e8b519346c5ebaae7c86e84a71
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTDecoder.cpp
1 /*
2  *  Copyright 2001-2006 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  * SAML2POSTDecoder.cpp
19  * 
20  * SAML 2.0 HTTP POST binding message encoder
21  */
22
23 #include "internal.h"
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"
31
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/util/NDC.h>
35
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;
43 using namespace std;
44
45 namespace opensaml {
46     namespace saml2p {              
47         MessageDecoder* SAML_DLLLOCAL SAML2POSTDecoderFactory(const DOMElement* const & e)
48         {
49             return new SAML2POSTDecoder(e);
50         }
51     };
52 };
53
54 SAML2POSTDecoder::SAML2POSTDecoder(const DOMElement* e) {}
55
56 SAML2POSTDecoder::~SAML2POSTDecoder() {}
57
58 XMLObject* SAML2POSTDecoder::decode(
59     string& relayState,
60     const RoleDescriptor*& issuer,
61     bool& issuerTrusted,
62     const HTTPRequest& httpRequest,
63     const MetadataProvider* metadataProvider,
64     const QName* role,
65     const opensaml::TrustEngine* trustEngine
66     ) const
67 {
68 #ifdef _DEBUG
69     xmltooling::NDC ndc("decode");
70 #endif
71     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2POST");
72
73     log.debug("validating input");
74     if (strcmp(httpRequest.getMethod(),"POST"))
75         return NULL;
76     const char* msg = httpRequest.getParameter("SAMLResponse");
77     if (!msg)
78         msg = httpRequest.getParameter("SAMLRequest");
79     if (!msg)
80         return NULL;
81     const char* state = httpRequest.getParameter("RelayState");
82     if (state)
83         relayState = state;
84     else
85         relayState.erase();
86
87     // Decode the base64 into SAML.
88     unsigned int x;
89     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
90     if (!decoded)
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);
95     
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));
101     janitor.release();
102
103     StatusResponseType* response = NULL;
104     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
105     if (!request) {
106         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
107         if (!response)
108             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
109     }
110     
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.
114      */
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);
119         if (assbag) {
120             const vector<Assertion*>& assertions=assbag->getAssertions();
121             if (!assertions.empty())
122                 claimedIssuer = assertions.front()->getIssuer();
123         }
124     }
125
126     const EntityDescriptor* provider=NULL;
127     try {
128         if (!m_validate)
129             SchemaValidators.validate(xmlObject.get());
130         
131         Signature* signature = request ? request->getSignature() : response->getSignature();
132         
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.");
139         }
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.");
143         }
144         
145         // Check freshness.
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.");
150         
151         // Check replay.
152         ReplayCache* replayCache = SAMLConfig::getConfig().getReplayCache();
153         if (replayCache) {
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()));
158             }
159         }
160         else
161             log.warn("replay cache was not provided, this is a serious security risk!");
162         
163         issuer = NULL;
164         issuerTrusted = false;
165         log.debug("attempting to establish issuer and integrity of message...");
166         
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();
171         }
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();
176         }
177         
178         log.debug("searching metadata for assertion issuer...");
179         provider=metadataProvider ? metadataProvider->getEntityDescriptor(claimedIssuer->getName()) : NULL;
180         if (provider) {
181             log.debug("matched assertion issuer against metadata, searching for applicable role...");
182             issuer=provider->getRoleDescriptor(*role, SAMLConstants::SAML20P_NS);
183             if (issuer) {
184                 if (trustEngine && signature) {
185                     issuerTrusted = trustEngine->validate(*signature, *issuer, metadataProvider->getKeyResolver());
186                     if (!issuerTrusted) {
187                         log.error("unable to verify signature on message with supplied trust engine");
188                         throw BindingException("Message signature failed verification.");
189                     }
190                 }
191                 else {
192                     log.warn("unable to verify integrity of the message, leaving untrusted");
193                 }
194             }
195             else {
196                 log.warn("unable to find compatible SAML 2.0 role (%s) in metadata", role->toString().c_str());
197             }
198             if (log.isDebugEnabled()) {
199                 auto_ptr_char iname(provider->getEntityID());
200                 log.debug("message from (%s), integrity %sverified", iname.get(), issuerTrusted ? "" : "NOT ");
201             }
202         }
203         else {
204             auto_ptr_char temp(claimedIssuer->getName());
205             log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
206         }
207     }
208     catch (XMLToolingException& ex) {
209         if (!provider) {
210             if (!claimedIssuer || !claimedIssuer->getName())
211                 throw;
212             if (!metadataProvider || !(provider=metadataProvider->getEntityDescriptor(claimedIssuer->getName(), false))) {
213                 // Just record it.
214                 auto_ptr_char iname(claimedIssuer->getName());
215                 if (iname.get())
216                     ex.addProperty("entityID", iname.get());
217                 throw;
218             }
219         }
220         if (!issuer)
221             issuer=provider->getRoleDescriptor(*role, SAMLConstants::SAML20P_NS);
222         if (issuer) annotateException(&ex,issuer); // throws it
223         annotateException(&ex,provider);  // throws it
224     }
225
226     return xmlObject.release();
227 }