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