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