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