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