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