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