https://issues.shibboleth.net/jira/browse/SSPCPP-375
[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     // First we do the extraction of any pushed information, including from metadata.
318     vector<Attribute*> resolvedAttributes;
319     AttributeExtractor* extractor = application.getAttributeExtractor();
320     if (extractor) {
321         Locker extlocker(extractor);
322         if (issuer) {
323             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
324             if (mprefix.first) {
325                 m_log.debug("extracting metadata-derived attributes...");
326                 try {
327                     // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
328                     extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
329                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
330                         vector<string>& ids = (*a)->getAliases();
331                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
332                             *id = mprefix.second + *id;
333                     }
334                 }
335                 catch (exception& ex) {
336                     m_log.error("caught exception extracting attributes: %s", ex.what());
337                 }
338             }
339         }
340         m_log.debug("extracting pushed attributes...");
341         if (v1nameid) {
342             try {
343                 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
344             }
345             catch (exception& ex) {
346                 m_log.error("caught exception extracting attributes: %s", ex.what());
347             }
348         }
349         else if (nameid) {
350             try {
351                 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
352             }
353             catch (exception& ex) {
354                 m_log.error("caught exception extracting attributes: %s", ex.what());
355             }
356         }
357         if (tokens) {
358             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
359                 try {
360                     extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
361                 }
362                 catch (exception& ex) {
363                     m_log.error("caught exception extracting attributes: %s", ex.what());
364                 }
365             }
366         }
367
368         AttributeFilter* filter = application.getAttributeFilter();
369         if (filter && !resolvedAttributes.empty()) {
370             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
371             Locker filtlocker(filter);
372             try {
373                 filter->filterAttributes(fc, resolvedAttributes);
374             }
375             catch (exception& ex) {
376                 m_log.error("caught exception filtering attributes: %s", ex.what());
377                 m_log.error("dumping extracted attributes due to filtering exception");
378                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
379                 resolvedAttributes.clear();
380             }
381         }
382     }
383     else {
384         m_log.warn("no AttributeExtractor plugin installed, check log during startup");
385     }
386
387     try {
388         AttributeResolver* resolver = application.getAttributeResolver();
389         if (resolver) {
390             m_log.debug("resolving attributes...");
391
392             Locker locker(resolver);
393             auto_ptr<ResolutionContext> ctx(
394                 resolver->createResolutionContext(
395                     application,
396                     issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
397                     protocol,
398                     nameid,
399                     authncontext_class,
400                     authncontext_decl,
401                     tokens,
402                     &resolvedAttributes
403                     )
404                 );
405             resolver->resolveAttributes(*ctx.get());
406             // Copy over any pushed attributes.
407             if (!resolvedAttributes.empty())
408                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
409             return ctx.release();
410         }
411     }
412     catch (exception& ex) {
413         m_log.error("attribute resolution failed: %s", ex.what());
414     }
415
416     if (!resolvedAttributes.empty())
417         return new DummyContext(resolvedAttributes);
418     return nullptr;
419 }
420
421 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
422 {
423     policy.setMessageID(assertion.getID());
424     policy.setIssueInstant(assertion.getIssueInstantEpoch());
425
426     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
427         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
428         if (a2) {
429             m_log.debug("extracting issuer from SAML 2.0 assertion");
430             policy.setIssuer(a2->getIssuer());
431         }
432     }
433     else {
434         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
435         if (a1) {
436             m_log.debug("extracting issuer from SAML 1.x assertion");
437             policy.setIssuer(a1->getIssuer());
438         }
439     }
440
441     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
442         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
443             m_log.warn("non-system entity issuer, skipping metadata lookup");
444             return;
445         }
446         m_log.debug("searching metadata for assertion issuer...");
447         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
448         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
449         mc.entityID_unicode = policy.getIssuer()->getName();
450         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
451         mc.protocol = protocol;
452         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
453         if (!entity.first) {
454             auto_ptr_char iname(policy.getIssuer()->getName());
455             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
456         }
457         else if (!entity.second) {
458             m_log.warn("unable to find compatible IdP role in metadata");
459         }
460         else {
461             policy.setIssuerMetadata(entity.second);
462         }
463     }
464 }
465
466 #endif
467
468 void AssertionConsumerService::maintainHistory(
469     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
470     ) const
471 {
472     static const char* defProps="; path=/";
473
474     const PropertySet* sessionProps=application.getPropertySet("Sessions");
475     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
476
477     if (idpHistory.first && idpHistory.second) {
478         pair<bool,const char*> cookieProps=sessionProps->getString("idpHistoryProps");
479         if (!cookieProps.first)
480             cookieProps=sessionProps->getString("cookieProps");
481         if (!cookieProps.first)
482             cookieProps.second=defProps;
483
484         // Set an IdP history cookie locally (essentially just a CDC).
485         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
486
487         // Either leave in memory or set an expiration.
488         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
489         if (!days.first || days.second==0) {
490             string c = string(cdc.set(entityID)) + cookieProps.second;
491             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
492         }
493         else {
494             time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
495 #ifdef HAVE_GMTIME_R
496             struct tm res;
497             struct tm* ptime=gmtime_r(&now,&res);
498 #else
499             struct tm* ptime=gmtime(&now);
500 #endif
501             char timebuf[64];
502             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
503             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
504             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
505         }
506     }
507 }