https://bugs.internet2.edu/jira/browse/SSPCPP-293
[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 char* AssertionConsumerService::getType() const
228 {
229     return "AssertionConsumerService";
230 }
231
232 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
233 {
234     // Initial guess at index to use.
235     pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
236     if (!strncmp(handlerURL, "https", 5))
237         ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
238     if (!ix.first)
239         ix = getUnsignedInt("index");
240     if (!ix.first)
241         ix.second = 1;
242
243     // Find maximum index in use and go one higher.
244     const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
245     if (!services.empty() && ix.second <= services.back()->getIndex().second)
246         ix.second = services.back()->getIndex().second + 1;
247
248     const char* loc = getString("Location").second;
249     string hurl(handlerURL);
250     if (*loc != '/')
251         hurl += '/';
252     hurl += loc;
253     auto_ptr_XMLCh widen(hurl.c_str());
254
255     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
256     ep->setLocation(widen.get());
257     ep->setBinding(getXMLString("Binding").second);
258     ep->setIndex(ix.second);
259     role.getAssertionConsumerServices().push_back(ep);
260 }
261
262 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
263     const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
264     ) const
265 {
266     return new SecurityPolicy(application, role, validate, policyId);
267 }
268
269 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
270 {
271 public:
272     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
273     }
274
275     virtual ~DummyContext() {
276         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
277     }
278
279     vector<Attribute*>& getResolvedAttributes() {
280         return m_attributes;
281     }
282     vector<Assertion*>& getResolvedAssertions() {
283         return m_tokens;
284     }
285
286 private:
287     vector<Attribute*> m_attributes;
288     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
289 };
290
291 vector<Assertion*> DummyContext::m_tokens;
292
293 ResolutionContext* AssertionConsumerService::resolveAttributes(
294     const Application& application,
295     const saml2md::RoleDescriptor* issuer,
296     const XMLCh* protocol,
297     const saml1::NameIdentifier* v1nameid,
298     const saml2::NameID* nameid,
299     const XMLCh* authncontext_class,
300     const XMLCh* authncontext_decl,
301     const vector<const Assertion*>* tokens
302     ) const
303 {
304     // First we do the extraction of any pushed information, including from metadata.
305     vector<Attribute*> resolvedAttributes;
306     AttributeExtractor* extractor = application.getAttributeExtractor();
307     if (extractor) {
308         Locker extlocker(extractor);
309         if (issuer) {
310             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
311             if (mprefix.first) {
312                 m_log.debug("extracting metadata-derived attributes...");
313                 try {
314                     // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
315                     extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
316                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
317                         vector<string>& ids = (*a)->getAliases();
318                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
319                             *id = mprefix.second + *id;
320                     }
321                 }
322                 catch (exception& ex) {
323                     m_log.error("caught exception extracting attributes: %s", ex.what());
324                 }
325             }
326         }
327         m_log.debug("extracting pushed attributes...");
328         if (v1nameid) {
329             try {
330                 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
331             }
332             catch (exception& ex) {
333                 m_log.error("caught exception extracting attributes: %s", ex.what());
334             }
335         }
336         else if (nameid) {
337             try {
338                 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
339             }
340             catch (exception& ex) {
341                 m_log.error("caught exception extracting attributes: %s", ex.what());
342             }
343         }
344         if (tokens) {
345             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
346                 try {
347                     extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
348                 }
349                 catch (exception& ex) {
350                     m_log.error("caught exception extracting attributes: %s", ex.what());
351                 }
352             }
353         }
354
355         AttributeFilter* filter = application.getAttributeFilter();
356         if (filter && !resolvedAttributes.empty()) {
357             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
358             Locker filtlocker(filter);
359             try {
360                 filter->filterAttributes(fc, resolvedAttributes);
361             }
362             catch (exception& ex) {
363                 m_log.error("caught exception filtering attributes: %s", ex.what());
364                 m_log.error("dumping extracted attributes due to filtering exception");
365                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
366                 resolvedAttributes.clear();
367             }
368         }
369     }
370     else {
371         m_log.warn("no AttributeExtractor plugin installed, check log during startup");
372     }
373
374     try {
375         AttributeResolver* resolver = application.getAttributeResolver();
376         if (resolver) {
377             m_log.debug("resolving attributes...");
378
379             Locker locker(resolver);
380             auto_ptr<ResolutionContext> ctx(
381                 resolver->createResolutionContext(
382                     application,
383                     issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
384                     protocol,
385                     nameid,
386                     authncontext_class,
387                     authncontext_decl,
388                     tokens,
389                     &resolvedAttributes
390                     )
391                 );
392             resolver->resolveAttributes(*ctx.get());
393             // Copy over any pushed attributes.
394             if (!resolvedAttributes.empty())
395                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
396             return ctx.release();
397         }
398     }
399     catch (exception& ex) {
400         m_log.error("attribute resolution failed: %s", ex.what());
401     }
402
403     if (!resolvedAttributes.empty())
404         return new DummyContext(resolvedAttributes);
405     return nullptr;
406 }
407
408 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
409 {
410     policy.setMessageID(assertion.getID());
411     policy.setIssueInstant(assertion.getIssueInstantEpoch());
412
413     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
414         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
415         if (a2) {
416             m_log.debug("extracting issuer from SAML 2.0 assertion");
417             policy.setIssuer(a2->getIssuer());
418         }
419     }
420     else {
421         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
422         if (a1) {
423             m_log.debug("extracting issuer from SAML 1.x assertion");
424             policy.setIssuer(a1->getIssuer());
425         }
426     }
427
428     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
429         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
430             m_log.warn("non-system entity issuer, skipping metadata lookup");
431             return;
432         }
433         m_log.debug("searching metadata for assertion issuer...");
434         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
435         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
436         mc.entityID_unicode = policy.getIssuer()->getName();
437         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
438         mc.protocol = protocol;
439         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
440         if (!entity.first) {
441             auto_ptr_char iname(policy.getIssuer()->getName());
442             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
443         }
444         else if (!entity.second) {
445             m_log.warn("unable to find compatible IdP role in metadata");
446         }
447         else {
448             policy.setIssuerMetadata(entity.second);
449         }
450     }
451 }
452
453 #endif
454
455 void AssertionConsumerService::maintainHistory(
456     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
457     ) const
458 {
459     static const char* defProps="; path=/";
460
461     const PropertySet* sessionProps=application.getPropertySet("Sessions");
462     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
463
464     if (idpHistory.first && idpHistory.second) {
465         pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
466         if (!cookieProps.first)
467             cookieProps.second=defProps;
468
469         // Set an IdP history cookie locally (essentially just a CDC).
470         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
471
472         // Either leave in memory or set an expiration.
473         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
474         if (!days.first || days.second==0) {
475             string c = string(cdc.set(entityID)) + cookieProps.second;
476             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
477         }
478         else {
479             time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
480 #ifdef HAVE_GMTIME_R
481             struct tm res;
482             struct tm* ptime=gmtime_r(&now,&res);
483 #else
484             struct tm* ptime=gmtime(&now);
485 #endif
486             char timebuf[64];
487             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
488             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
489             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
490         }
491     }
492 }