Rework POST handling to avoid remoting data if handler doesn't run.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
1 /*
2  *  Copyright 2001-2009 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  * AssertionConsumerService.cpp
19  *
20  * Base class for handlers that create sessions by consuming SSO protocol responses.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
29
30 # include <ctime>
31 #ifndef SHIBSP_LITE
32 # include "attribute/Attribute.h"
33 # include "attribute/filtering/AttributeFilter.h"
34 # include "attribute/filtering/BasicFilteringContext.h"
35 # include "attribute/resolver/AttributeExtractor.h"
36 # include "attribute/resolver/AttributeResolver.h"
37 # include "attribute/resolver/ResolutionContext.h"
38 # include "metadata/MetadataProviderCriteria.h"
39 # include "security/SecurityPolicy.h"
40 # include <saml/SAMLConfig.h>
41 # include <saml/saml1/core/Assertions.h>
42 # include <saml/util/CommonDomainCookie.h>
43 using namespace samlconstants;
44 using opensaml::saml2md::MetadataProvider;
45 using opensaml::saml2md::RoleDescriptor;
46 using opensaml::saml2md::EntityDescriptor;
47 using opensaml::saml2md::IDPSSODescriptor;
48 using opensaml::saml2md::SPSSODescriptor;
49 #else
50 # include "lite/CommonDomainCookie.h"
51 #endif
52
53 using namespace shibspconstants;
54 using namespace shibsp;
55 using namespace opensaml;
56 using namespace xmltooling;
57 using namespace std;
58
59 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
60     : AbstractHandler(e, log)
61 #ifndef SHIBSP_LITE
62         ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
63 #endif
64 {
65     if (!e)
66         return;
67     string address(appId);
68     address += getString("Location").second;
69     setAddress(address.c_str());
70 #ifndef SHIBSP_LITE
71     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
72         m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
73             getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
74             );
75         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
76     }
77 #endif
78 }
79
80 AssertionConsumerService::~AssertionConsumerService()
81 {
82 #ifndef SHIBSP_LITE
83     delete m_decoder;
84 #endif
85 }
86
87 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
88 {
89     string relayState;
90     SPConfig& conf = SPConfig::getConfig();
91
92     if (conf.isEnabled(SPConfig::OutOfProcess)) {
93         // When out of process, we run natively and directly process the message.
94         return processMessage(request.getApplication(), request, request);
95     }
96     else {
97         // When not out of process, we remote all the message processing.
98         vector<string> headers(1, "Cookie");
99         DDF out,in = wrap(request, &headers);
100         DDFJanitor jin(in), jout(out);
101         out=request.getServiceProvider().getListenerService()->send(in);
102         return unwrap(request, out);
103     }
104 }
105
106 void AssertionConsumerService::receive(DDF& in, ostream& out)
107 {
108     // Find application.
109     const char* aid=in["application_id"].string();
110     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
111     if (!app) {
112         // Something's horribly wrong.
113         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
114         throw ConfigurationException("Unable to locate application for new session, deleted?");
115     }
116
117     // Unpack the request.
118     auto_ptr<HTTPRequest> req(getRequest(in));
119
120     // Wrap a response shim.
121     DDF ret(NULL);
122     DDFJanitor jout(ret);
123     auto_ptr<HTTPResponse> resp(getResponse(ret));
124
125     // Since we're remoted, the result should either be a throw, a false/0 return,
126     // which we just return as an empty structure, or a response/redirect,
127     // which we capture in the facade and send back.
128     processMessage(*app, *req.get(), *resp.get());
129     out << ret;
130 }
131
132 pair<bool,long> AssertionConsumerService::processMessage(
133     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
134     ) const
135 {
136 #ifndef SHIBSP_LITE
137     // Locate policy key.
138     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
139     if (!policyId.first)
140         policyId = application.getString("policyId");   // unqualified in Application(s) element
141
142     // Access policy properties.
143     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
144     pair<bool,bool> validate = settings->getBool("validate");
145
146     // Lock metadata for use by policy.
147     Locker metadataLocker(application.getMetadataProvider());
148
149     // Create the policy.
150     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second, policyId.second);
151
152     string relayState;
153     try {
154         // Decode the message and process it in a protocol-specific way.
155         auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
156         if (!msg.get())
157             throw BindingException("Failed to decode an SSO protocol response.");
158         DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
159         DDFJanitor postjan(postData);
160         recoverRelayState(application, httpRequest, httpResponse, relayState);
161         implementProtocol(application, httpRequest, httpResponse, policy, settings, *msg.get());
162
163         auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
164
165         // History cookie.
166         if (issuer.get() && *issuer.get())
167             maintainHistory(application, httpRequest, httpResponse, issuer.get());
168
169         // Now redirect to the state value. By now, it should be set to *something* usable.
170         // First check for POST data.
171         if (!postData.islist()) {
172             m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
173             return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
174         }
175         else {
176             m_log.debug("ACS returning via POST to: %s", relayState.c_str());
177             return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
178         }
179     }
180     catch (XMLToolingException& ex) {
181         // Check for isPassive error condition.
182         const char* sc2 = ex.getProperty("statusCode2");
183         if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
184             validate = getBool("ignoreNoPassive", m_configNS.get());  // namespace-qualified if inside handler element
185             if (validate.first && validate.second && !relayState.empty()) {
186                 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
187                 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
188             }
189         }
190         if (!relayState.empty())
191             ex.addProperty("RelayState", relayState.c_str());
192         throw;
193     }
194 #else
195     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
196 #endif
197 }
198
199 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
200 {
201     if (!issuedTo || !*issuedTo)
202         return;
203
204     const PropertySet* props=application.getPropertySet("Sessions");
205     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
206     if (!checkAddress.first)
207         checkAddress.second=true;
208
209     if (checkAddress.second) {
210         m_log.debug("checking client address");
211         if (httpRequest.getRemoteAddr() != issuedTo) {
212             throw FatalProfileException(
213                "Your client's current address ($client_addr) differs from the one used when you authenticated "
214                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
215                 "Please contact your local support staff or help desk for assistance.",
216                 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
217                 );
218         }
219     }
220 }
221
222 #ifndef SHIBSP_LITE
223
224 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
225     const char* loc = getString("Location").second;
226     string hurl(handlerURL);
227     if (*loc != '/')
228         hurl += '/';
229     hurl += loc;
230     auto_ptr_XMLCh widen(hurl.c_str());
231     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
232     ep->setLocation(widen.get());
233     ep->setBinding(getXMLString("Binding").second);
234     if (!strncmp(handlerURL, "https", 5)) {
235         pair<bool,const XMLCh*> index = getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
236         if (index.first)
237                 ep->setIndex(index.second);
238         else
239                 ep->setIndex(getXMLString("index").second);
240     }
241     else {
242         ep->setIndex(getXMLString("index").second);
243     }
244     role.getAssertionConsumerServices().push_back(ep);
245 }
246
247 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
248 {
249 public:
250     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
251     }
252
253     virtual ~DummyContext() {
254         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
255     }
256
257     vector<Attribute*>& getResolvedAttributes() {
258         return m_attributes;
259     }
260     vector<Assertion*>& getResolvedAssertions() {
261         return m_tokens;
262     }
263
264 private:
265     vector<Attribute*> m_attributes;
266     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
267 };
268
269 vector<Assertion*> DummyContext::m_tokens;
270
271 ResolutionContext* AssertionConsumerService::resolveAttributes(
272     const Application& application,
273     const saml2md::RoleDescriptor* issuer,
274     const XMLCh* protocol,
275     const saml1::NameIdentifier* v1nameid,
276     const saml2::NameID* nameid,
277     const XMLCh* authncontext_class,
278     const XMLCh* authncontext_decl,
279     const vector<const Assertion*>* tokens
280     ) const
281 {
282     const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
283
284     // First we do the extraction of any pushed information, including from metadata.
285     vector<Attribute*> resolvedAttributes;
286     AttributeExtractor* extractor = application.getAttributeExtractor();
287     if (extractor) {
288         Locker extlocker(extractor);
289         if (entity) {
290             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
291             if (mprefix.first) {
292                 m_log.debug("extracting metadata-derived attributes...");
293                 try {
294                     extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
295                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
296                         vector<string>& ids = (*a)->getAliases();
297                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
298                             *id = mprefix.second + *id;
299                     }
300                 }
301                 catch (exception& ex) {
302                     m_log.error("caught exception extracting attributes: %s", ex.what());
303                 }
304             }
305         }
306         m_log.debug("extracting pushed attributes...");
307         if (v1nameid) {
308             try {
309                 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
310             }
311             catch (exception& ex) {
312                 m_log.error("caught exception extracting attributes: %s", ex.what());
313             }
314         }
315         else if (nameid) {
316             try {
317                 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
318             }
319             catch (exception& ex) {
320                 m_log.error("caught exception extracting attributes: %s", ex.what());
321             }
322         }
323         if (tokens) {
324             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
325                 try {
326                     extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
327                 }
328                 catch (exception& ex) {
329                     m_log.error("caught exception extracting attributes: %s", ex.what());
330                 }
331             }
332         }
333
334         AttributeFilter* filter = application.getAttributeFilter();
335         if (filter && !resolvedAttributes.empty()) {
336             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
337             Locker filtlocker(filter);
338             try {
339                 filter->filterAttributes(fc, resolvedAttributes);
340             }
341             catch (exception& ex) {
342                 m_log.error("caught exception filtering attributes: %s", ex.what());
343                 m_log.error("dumping extracted attributes due to filtering exception");
344                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
345                 resolvedAttributes.clear();
346             }
347         }
348     }
349
350     try {
351         AttributeResolver* resolver = application.getAttributeResolver();
352         if (resolver) {
353             m_log.debug("resolving attributes...");
354
355             Locker locker(resolver);
356             auto_ptr<ResolutionContext> ctx(
357                 resolver->createResolutionContext(
358                     application,
359                     entity,
360                     protocol,
361                     nameid,
362                     authncontext_class,
363                     authncontext_decl,
364                     tokens,
365                     &resolvedAttributes
366                     )
367                 );
368             resolver->resolveAttributes(*ctx.get());
369             // Copy over any pushed attributes.
370             if (!resolvedAttributes.empty())
371                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
372             return ctx.release();
373         }
374     }
375     catch (exception& ex) {
376         m_log.error("attribute resolution failed: %s", ex.what());
377     }
378
379     if (!resolvedAttributes.empty())
380         return new DummyContext(resolvedAttributes);
381     return NULL;
382 }
383
384 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
385 {
386     policy.setMessageID(assertion.getID());
387     policy.setIssueInstant(assertion.getIssueInstantEpoch());
388
389     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
390         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
391         if (a2) {
392             m_log.debug("extracting issuer from SAML 2.0 assertion");
393             policy.setIssuer(a2->getIssuer());
394         }
395     }
396     else {
397         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
398         if (a1) {
399             m_log.debug("extracting issuer from SAML 1.x assertion");
400             policy.setIssuer(a1->getIssuer());
401         }
402     }
403
404     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
405         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
406             m_log.warn("non-system entity issuer, skipping metadata lookup");
407             return;
408         }
409         m_log.debug("searching metadata for assertion issuer...");
410         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
411         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
412         mc.entityID_unicode = policy.getIssuer()->getName();
413         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
414         mc.protocol = protocol;
415         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
416         if (!entity.first) {
417             auto_ptr_char iname(policy.getIssuer()->getName());
418             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
419         }
420         else if (!entity.second) {
421             m_log.warn("unable to find compatible IdP role in metadata");
422         }
423         else {
424             policy.setIssuerMetadata(entity.second);
425         }
426     }
427 }
428
429 #endif
430
431 void AssertionConsumerService::maintainHistory(
432     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
433     ) const
434 {
435     static const char* defProps="; path=/";
436
437     const PropertySet* sessionProps=application.getPropertySet("Sessions");
438     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
439
440     if (idpHistory.first && idpHistory.second) {
441         pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
442         if (!cookieProps.first)
443             cookieProps.second=defProps;
444
445         // Set an IdP history cookie locally (essentially just a CDC).
446         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
447
448         // Either leave in memory or set an expiration.
449         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
450         if (!days.first || days.second==0) {
451             string c = string(cdc.set(entityID)) + cookieProps.second;
452             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
453         }
454         else {
455             time_t now=time(NULL) + (days.second * 24 * 60 * 60);
456 #ifdef HAVE_GMTIME_R
457             struct tm res;
458             struct tm* ptime=gmtime_r(&now,&res);
459 #else
460             struct tm* ptime=gmtime(&now);
461 #endif
462             char timebuf[64];
463             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
464             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
465             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
466         }
467     }
468 }