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