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