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