c42abd9a2ec708c2098280ce2e1013c156e60612
[shibboleth/sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * AssertionConsumerService.cpp
23  *
24  * Base class for handlers that create sessions by consuming SSO protocol responses.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AssertionConsumerService.h"
33 #include "util/CGIParser.h"
34 #include "util/SPConstants.h"
35
36 # include <ctime>
37 #ifndef SHIBSP_LITE
38 # include "attribute/Attribute.h"
39 # include "attribute/filtering/AttributeFilter.h"
40 # include "attribute/filtering/BasicFilteringContext.h"
41 # include "attribute/resolver/AttributeExtractor.h"
42 # include "attribute/resolver/AttributeResolver.h"
43 # include "attribute/resolver/ResolutionContext.h"
44 # include "metadata/MetadataProviderCriteria.h"
45 # include "security/SecurityPolicy.h"
46 # include "security/SecurityPolicyProvider.h"
47 # include <boost/iterator/indirect_iterator.hpp>
48 # include <saml/exceptions.h>
49 # include <saml/SAMLConfig.h>
50 # include <saml/saml1/core/Assertions.h>
51 # include <saml/saml1/core/Protocols.h>
52 # include <saml/saml2/core/Protocols.h>
53 # include <saml/saml2/metadata/Metadata.h>
54 # include <saml/util/CommonDomainCookie.h>
55 using namespace samlconstants;
56 using opensaml::saml2md::MetadataProvider;
57 using opensaml::saml2md::RoleDescriptor;
58 using opensaml::saml2md::EntityDescriptor;
59 using opensaml::saml2md::IDPSSODescriptor;
60 using opensaml::saml2md::SPSSODescriptor;
61 #else
62 # include "lite/CommonDomainCookie.h"
63 #endif
64
65 #include <xmltooling/XMLToolingConfig.h>
66 #include <xmltooling/util/URLEncoder.h>
67
68 using namespace shibspconstants;
69 using namespace shibsp;
70 using namespace opensaml;
71 using namespace xmltooling;
72 using namespace boost;
73 using namespace std;
74
75 AssertionConsumerService::AssertionConsumerService(
76     const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
77     ) : AbstractHandler(e, log, filter, remapper)
78 {
79     if (!e)
80         return;
81     string address(appId);
82     address += getString("Location").second;
83     setAddress(address.c_str());
84 #ifndef SHIBSP_LITE
85     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
86         m_decoder.reset(
87             SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
88                 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
89                 )
90             );
91         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
92     }
93 #endif
94 }
95
96 AssertionConsumerService::~AssertionConsumerService()
97 {
98 }
99
100 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
101 {
102     // Check for a message back to the ACS from a post-session hook.
103     if (request.getQueryString() && strstr(request.getQueryString(), "hook=1")) {
104         // Parse the query string only to preserve any POST data.
105         CGIParser cgi(request, true);
106         pair<CGIParser::walker,CGIParser::walker> param = cgi.getParameters("hook");
107         if (param.first != param.second && param.first->second && !strcmp(param.first->second, "1")) {
108             string target;
109             param = cgi.getParameters("target");
110             if (param.first != param.second && param.first->second)
111                 target = param.first->second;
112             return finalizeResponse(request.getApplication(), request, request, target);
113         }
114     }
115
116     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
117         // When out of process, we run natively and directly process the message.
118         return processMessage(request.getApplication(), request, request);
119     }
120     else {
121         // When not out of process, we remote all the message processing.
122         vector<string> headers(1, "Cookie");
123         headers.push_back("User-Agent");
124         headers.push_back("Accept-Language");
125         DDF out,in = wrap(request, &headers);
126         DDFJanitor jin(in), jout(out);
127         out = request.getServiceProvider().getListenerService()->send(in);
128         return unwrap(request, out);
129     }
130 }
131
132 void AssertionConsumerService::receive(DDF& in, ostream& out)
133 {
134     // Find application.
135     const char* aid = in["application_id"].string();
136     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
137     if (!app) {
138         // Something's horribly wrong.
139         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
140         throw ConfigurationException("Unable to locate application for new session, deleted?");
141     }
142
143     // Unpack the request.
144     scoped_ptr<HTTPRequest> req(getRequest(in));
145
146     // Wrap a response shim.
147     DDF ret(nullptr);
148     DDFJanitor jout(ret);
149     scoped_ptr<HTTPResponse> resp(getResponse(ret));
150
151     // Since we're remoted, the result should either be a throw, a false/0 return,
152     // which we just return as an empty structure, or a response/redirect,
153     // which we capture in the facade and send back.
154     processMessage(*app, *req, *resp);
155     out << ret;
156 }
157
158 pair<bool,long> AssertionConsumerService::processMessage(
159     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
160     ) const
161 {
162 #ifndef SHIBSP_LITE
163     // Locate policy key.
164     pair<bool,const char*> prop = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
165     if (!prop.first)
166         prop = application.getString("policyId");   // unqualified in Application(s) element
167
168     // Lock metadata for use by policy.
169     Locker metadataLocker(application.getMetadataProvider());
170
171     // Create the policy.
172     scoped_ptr<opensaml::SecurityPolicy> policy(
173         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(
174             application, &IDPSSODescriptor::ELEMENT_QNAME, prop.second
175             )
176         );
177
178     string relayState;
179     scoped_ptr<XMLObject> msg;
180     try {
181         // Decode the message and process it in a protocol-specific way.
182         msg.reset(m_decoder->decode(relayState, httpRequest, *(policy.get())));
183         if (!msg)
184             throw BindingException("Failed to decode an SSO protocol response.");
185         implementProtocol(application, httpRequest, httpResponse, *policy, nullptr, *msg);
186
187         // History cookie.
188         auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
189         if (issuer.get() && *issuer.get())
190             maintainHistory(application, httpRequest, httpResponse, issuer.get());
191
192         const EntityDescriptor* entity =
193             dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata() ? policy->getIssuerMetadata()->getParent() : nullptr);
194         prop = application.getRelyingParty(entity)->getString("sessionHook");
195         if (prop.first) {
196             string hook(prop.second);
197             httpRequest.absolutize(hook);
198
199             // Compute the return URL. We use a self-referential link plus a hook indicator to break the cycle
200             // and the relay state.
201             const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
202             string returnURL = httpRequest.getRequestURL();
203             returnURL = returnURL.substr(0, returnURL.find('?')) + "?hook=1";
204             if (!relayState.empty())
205                 returnURL += "&target=" + encoder->encode(relayState.c_str());
206             if (hook.find('?') == string::npos)
207                 hook += '?';
208             else
209                 hook += '&';
210             hook += "return=" + encoder->encode(returnURL.c_str());
211
212             // Add the translated target resource in case it's of interest.
213             if (!relayState.empty()) {
214                 try {
215                     recoverRelayState(application, httpRequest, httpResponse, relayState, false);
216                     hook += "&target=" + encoder->encode(relayState.c_str());
217                 }
218                 catch (std::exception& ex) {
219                     m_log.warn("error recovering relay state: %s", ex.what());
220                 }
221             }
222
223             return make_pair(true, httpResponse.sendRedirect(hook.c_str()));
224         }
225
226         return finalizeResponse(application, httpRequest, httpResponse, relayState);
227     }
228     catch (XMLToolingException& ex) {
229         // Check for isPassive error condition.
230         const char* sc2 = ex.getProperty("statusCode2");
231         if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
232             pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get());  // namespace-qualified if inside handler element
233             if (ignore.first && ignore.second && !relayState.empty()) {
234                 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
235                 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
236             }
237         }
238         if (!relayState.empty()) {
239             try {
240                 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
241             }
242             catch (std::exception& rsex) {
243                 m_log.warn("error recovering relay state: %s", rsex.what());
244             }
245             ex.addProperty("RelayState", relayState.c_str());
246         }
247
248         // Log the error.
249         try {
250             scoped_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
251             LoginEvent* error_event = dynamic_cast<LoginEvent*>(event.get());
252             if (error_event) {
253                 error_event->m_exception = &ex;
254                 error_event->m_request = &httpRequest;
255                 error_event->m_app = &application;
256                 if (policy->getIssuerMetadata())
257                     error_event->m_peer = dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata()->getParent());
258                 auto_ptr_char prot(getProtocolFamily());
259                 error_event->m_protocol = prot.get();
260                 error_event->m_binding = getString("Binding").second;
261                 error_event->m_saml2Response = dynamic_cast<const saml2p::StatusResponseType*>(msg.get());
262                 if (!error_event->m_saml2Response)
263                     error_event->m_saml1Response = dynamic_cast<const saml1p::Response*>(msg.get());
264                 application.getServiceProvider().getTransactionLog()->write(*error_event);
265             }
266             else {
267                 m_log.warn("unable to audit event, log event object was of an incorrect type");
268             }
269         }
270         catch (std::exception& ex2) {
271             m_log.warn("exception auditing event: %s", ex2.what());
272         }
273
274         // If no sign of annotation, try to annotate it now.
275         if (!ex.getProperty("statusCode")) {
276             annotateException(&ex, policy->getIssuerMetadata(), nullptr, false);    // wait to throw it
277         }
278
279         throw;
280     }
281 #else
282     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
283 #endif
284 }
285
286 pair<bool,long> AssertionConsumerService::finalizeResponse(
287     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, string& relayState
288     ) const
289 {
290     DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
291     DDFJanitor postjan(postData);
292     recoverRelayState(application, httpRequest, httpResponse, relayState);
293     application.limitRedirect(httpRequest, relayState.c_str());
294
295     // Now redirect to the state value. By now, it should be set to *something* usable.
296     // First check for POST data.
297     if (!postData.islist()) {
298         m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
299         return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
300     }
301     else {
302         m_log.debug("ACS returning via POST to: %s", relayState.c_str());
303         return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
304     }
305 }
306
307 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
308 {
309     if (!issuedTo || !*issuedTo)
310         return;
311
312     const PropertySet* props = application.getPropertySet("Sessions");
313     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
314     if (!checkAddress.first)
315         checkAddress.second = true;
316
317     if (checkAddress.second) {
318         m_log.debug("checking client address");
319         if (httpRequest.getRemoteAddr() != issuedTo) {
320             throw FatalProfileException(
321                "Your client's current address ($client_addr) differs from the one used when you authenticated "
322                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
323                 "Please contact your local support staff or help desk for assistance.",
324                 namedparams(1, "client_addr", httpRequest.getRemoteAddr().c_str())
325                 );
326         }
327     }
328 }
329
330 #ifndef SHIBSP_LITE
331
332 const XMLCh* AssertionConsumerService::getProtocolFamily() const
333 {
334     return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
335 }
336
337 const char* AssertionConsumerService::getType() const
338 {
339     return "AssertionConsumerService";
340 }
341
342 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
343 {
344     // Initial guess at index to use.
345     pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
346     if (!strncmp(handlerURL, "https", 5))
347         ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
348     if (!ix.first)
349         ix = getUnsignedInt("index");
350     if (!ix.first)
351         ix.second = 1;
352
353     // Find maximum index in use and go one higher.
354     const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
355     if (!services.empty() && ix.second <= services.back()->getIndex().second)
356         ix.second = services.back()->getIndex().second + 1;
357
358     const char* loc = getString("Location").second;
359     string hurl(handlerURL);
360     if (*loc != '/')
361         hurl += '/';
362     hurl += loc;
363     auto_ptr_XMLCh widen(hurl.c_str());
364
365     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
366     ep->setLocation(widen.get());
367     ep->setBinding(getXMLString("Binding").second);
368     ep->setIndex(ix.second);
369     role.getAssertionConsumerServices().push_back(ep);
370 }
371
372 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
373     const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
374     ) const
375 {
376     return new SecurityPolicy(application, role, validate, policyId);
377 }
378
379 namespace {
380     class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
381     {
382     public:
383         DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
384         }
385
386         virtual ~DummyContext() {
387             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
388         }
389
390         vector<Attribute*>& getResolvedAttributes() {
391             return m_attributes;
392         }
393         vector<Assertion*>& getResolvedAssertions() {
394             return m_tokens;
395         }
396
397     private:
398         vector<Attribute*> m_attributes;
399         static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
400     };
401 };
402
403 vector<Assertion*> DummyContext::m_tokens;
404
405 ResolutionContext* AssertionConsumerService::resolveAttributes(
406     const Application& application,
407     const saml2md::RoleDescriptor* issuer,
408     const XMLCh* protocol,
409     const saml1::NameIdentifier* v1nameid,
410     const saml2::NameID* nameid,
411     const XMLCh* authncontext_class,
412     const XMLCh* authncontext_decl,
413     const vector<const Assertion*>* tokens
414     ) const
415 {
416     return resolveAttributes(
417         application,
418         nullptr,
419         issuer,
420         protocol,
421         nullptr,
422         v1nameid,
423         nullptr,
424         nameid,
425         nullptr,
426         authncontext_class,
427         authncontext_decl,
428         tokens
429         );
430 }
431
432 ResolutionContext* AssertionConsumerService::resolveAttributes(
433     const Application& application,
434     const GenericRequest* request,
435     const RoleDescriptor* issuer,
436     const XMLCh* protocol,
437     const xmltooling::XMLObject* protmsg,
438     const saml1::NameIdentifier* v1nameid,
439     const saml1::AuthenticationStatement* v1statement,
440     const saml2::NameID* nameid,
441     const saml2::AuthnStatement* statement,
442     const XMLCh* authncontext_class,
443     const XMLCh* authncontext_decl,
444     const vector<const Assertion*>* tokens
445     ) const
446 {
447     // First we do the extraction of any pushed information, including from metadata.
448     vector<Attribute*> resolvedAttributes;
449     AttributeExtractor* extractor = application.getAttributeExtractor();
450     if (extractor) {
451         Locker extlocker(extractor);
452         if (issuer) {
453             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
454             if (mprefix.first) {
455                 m_log.debug("extracting metadata-derived attributes...");
456                 try {
457                     // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
458                     extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
459                     for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
460                             a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
461                         vector<string>& ids = a->getAliases();
462                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
463                             *id = mprefix.second + *id;
464                     }
465                 }
466                 catch (std::exception& ex) {
467                     m_log.error("caught exception extracting attributes: %s", ex.what());
468                 }
469             }
470         }
471
472         m_log.debug("extracting pushed attributes...");
473
474         if (protmsg) {
475             try {
476                 extractor->extractAttributes(application, request, issuer, *protmsg, resolvedAttributes);
477             }
478             catch (std::exception& ex) {
479                 m_log.error("caught exception extracting attributes: %s", ex.what());
480             }
481         }
482
483         if (v1nameid || nameid) {
484             try {
485                 if (v1nameid)
486                     extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
487                 else
488                     extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
489             }
490             catch (std::exception& ex) {
491                 m_log.error("caught exception extracting attributes: %s", ex.what());
492             }
493         }
494
495         if (v1statement || statement) {
496             try {
497                 if (v1statement)
498                     extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
499                 else
500                     extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
501             }
502             catch (std::exception& ex) {
503                 m_log.error("caught exception extracting attributes: %s", ex.what());
504             }
505         }
506
507         if (tokens) {
508             for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
509                     t != make_indirect_iterator(tokens->end()); ++t) {
510                 try {
511                     extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
512                 }
513                 catch (std::exception& ex) {
514                     m_log.error("caught exception extracting attributes: %s", ex.what());
515                 }
516             }
517         }
518
519         AttributeFilter* filter = application.getAttributeFilter();
520         if (filter && !resolvedAttributes.empty()) {
521             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class, authncontext_decl);
522             Locker filtlocker(filter);
523             try {
524                 filter->filterAttributes(fc, resolvedAttributes);
525             }
526             catch (std::exception& ex) {
527                 m_log.error("caught exception filtering attributes: %s", ex.what());
528                 m_log.error("dumping extracted attributes due to filtering exception");
529                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
530                 resolvedAttributes.clear();
531             }
532         }
533     }
534     else {
535         m_log.warn("no AttributeExtractor plugin installed, check log during startup");
536     }
537
538     try {
539         AttributeResolver* resolver = application.getAttributeResolver();
540         if (resolver) {
541             m_log.debug("resolving attributes...");
542
543             Locker locker(resolver);
544             auto_ptr<ResolutionContext> ctx(
545                 resolver->createResolutionContext(
546                     application,
547                     request,
548                     issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
549                     protocol,
550                     nameid,
551                     authncontext_class,
552                     authncontext_decl,
553                     tokens,
554                     &resolvedAttributes
555                     )
556                 );
557             resolver->resolveAttributes(*ctx);
558             // Copy over any pushed attributes.
559             while (!resolvedAttributes.empty()) {
560                 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
561                 resolvedAttributes.pop_back();
562             }
563             return ctx.release();
564         }
565     }
566     catch (std::exception& ex) {
567         m_log.error("attribute resolution failed: %s", ex.what());
568     }
569
570     if (!resolvedAttributes.empty()) {
571         try {
572             return new DummyContext(resolvedAttributes);
573         }
574         catch (bad_alloc&) {
575             for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
576         }
577     }
578     return nullptr;
579 }
580
581 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
582 {
583     policy.setMessageID(assertion.getID());
584     policy.setIssueInstant(assertion.getIssueInstantEpoch());
585
586     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
587         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
588         if (a2) {
589             m_log.debug("extracting issuer from SAML 2.0 assertion");
590             policy.setIssuer(a2->getIssuer());
591         }
592     }
593     else {
594         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
595         if (a1) {
596             m_log.debug("extracting issuer from SAML 1.x assertion");
597             policy.setIssuer(a1->getIssuer());
598         }
599     }
600
601     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
602         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
603             m_log.warn("non-system entity issuer, skipping metadata lookup");
604             return;
605         }
606         m_log.debug("searching metadata for assertion issuer...");
607         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
608         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
609         mc.entityID_unicode = policy.getIssuer()->getName();
610         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
611         mc.protocol = protocol;
612         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
613         if (!entity.first) {
614             auto_ptr_char iname(policy.getIssuer()->getName());
615             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
616         }
617         else if (!entity.second) {
618             m_log.warn("unable to find compatible IdP role in metadata");
619         }
620         else {
621             policy.setIssuerMetadata(entity.second);
622         }
623     }
624 }
625
626 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const HTTPRequest& request) const
627 {
628     if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
629         return nullptr;
630     try {
631         auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
632         LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
633         if (login_event) {
634             login_event->m_request = &request;
635             login_event->m_app = &application;
636             login_event->m_binding = getString("Binding").second;
637             event.release();
638             return login_event;
639         }
640         else {
641             m_log.warn("unable to audit event, log event object was of an incorrect type");
642         }
643     }
644     catch (std::exception& ex) {
645         m_log.warn("exception auditing event: %s", ex.what());
646     }
647     return nullptr;
648 }
649
650 #endif
651
652 void AssertionConsumerService::maintainHistory(
653     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
654     ) const
655 {
656     static const char* defProps="; path=/";
657
658     const PropertySet* sessionProps=application.getPropertySet("Sessions");
659     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
660
661     if (idpHistory.first && idpHistory.second) {
662         pair<bool,const char*> cookieProps=sessionProps->getString("idpHistoryProps");
663         if (!cookieProps.first)
664             cookieProps=sessionProps->getString("cookieProps");
665         if (!cookieProps.first)
666             cookieProps.second=defProps;
667
668         // Set an IdP history cookie locally (essentially just a CDC).
669         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
670
671         // Either leave in memory or set an expiration.
672         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
673         if (!days.first || days.second==0) {
674             string c = string(cdc.set(entityID)) + cookieProps.second;
675             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
676         }
677         else {
678             time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
679 #ifdef HAVE_GMTIME_R
680             struct tm res;
681             struct tm* ptime=gmtime_r(&now,&res);
682 #else
683             struct tm* ptime=gmtime(&now);
684 #endif
685             char timebuf[64];
686             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
687             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
688             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
689         }
690     }
691 }