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