https://issues.shibboleth.net/jira/browse/SSPCPP-421
[shibboleth/cpp-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 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
380 {
381 public:
382     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
383     }
384
385     virtual ~DummyContext() {
386         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
387     }
388
389     vector<Attribute*>& getResolvedAttributes() {
390         return m_attributes;
391     }
392     vector<Assertion*>& getResolvedAssertions() {
393         return m_tokens;
394     }
395
396 private:
397     vector<Attribute*> m_attributes;
398     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
399 };
400
401 vector<Assertion*> DummyContext::m_tokens;
402
403 ResolutionContext* AssertionConsumerService::resolveAttributes(
404     const Application& application,
405     const saml2md::RoleDescriptor* issuer,
406     const XMLCh* protocol,
407     const saml1::NameIdentifier* v1nameid,
408     const saml2::NameID* nameid,
409     const XMLCh* authncontext_class,
410     const XMLCh* authncontext_decl,
411     const vector<const Assertion*>* tokens
412     ) const
413 {
414     return resolveAttributes(
415         application,
416         nullptr,
417         issuer,
418         protocol,
419         nullptr,
420         v1nameid,
421         nullptr,
422         nameid,
423         nullptr,
424         authncontext_class,
425         authncontext_decl,
426         tokens
427         );
428 }
429
430 ResolutionContext* AssertionConsumerService::resolveAttributes(
431     const Application& application,
432     const GenericRequest* request,
433     const saml2md::RoleDescriptor* issuer,
434     const XMLCh* protocol,
435     const xmltooling::XMLObject* protmsg,
436     const saml1::NameIdentifier* v1nameid,
437     const saml1::AuthenticationStatement* v1statement,
438     const saml2::NameID* nameid,
439     const saml2::AuthnStatement* statement,
440     const XMLCh* authncontext_class,
441     const XMLCh* authncontext_decl,
442     const vector<const Assertion*>* tokens
443     ) const
444 {
445     // First we do the extraction of any pushed information, including from metadata.
446     vector<Attribute*> resolvedAttributes;
447     AttributeExtractor* extractor = application.getAttributeExtractor();
448     if (extractor) {
449         Locker extlocker(extractor);
450         if (issuer) {
451             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
452             if (mprefix.first) {
453                 m_log.debug("extracting metadata-derived attributes...");
454                 try {
455                     // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
456                     extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
457                     for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
458                             a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
459                         vector<string>& ids = a->getAliases();
460                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
461                             *id = mprefix.second + *id;
462                     }
463                 }
464                 catch (std::exception& ex) {
465                     m_log.error("caught exception extracting attributes: %s", ex.what());
466                 }
467             }
468         }
469
470         m_log.debug("extracting pushed attributes...");
471
472         if (protmsg) {
473             try {
474                 extractor->extractAttributes(application, request, issuer, *protmsg, resolvedAttributes);
475             }
476             catch (std::exception& ex) {
477                 m_log.error("caught exception extracting attributes: %s", ex.what());
478             }
479         }
480
481         if (v1nameid || nameid) {
482             try {
483                 if (v1nameid)
484                     extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
485                 else
486                     extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
487             }
488             catch (std::exception& ex) {
489                 m_log.error("caught exception extracting attributes: %s", ex.what());
490             }
491         }
492
493         if (v1statement || statement) {
494             try {
495                 if (v1statement)
496                     extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
497                 else
498                     extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
499             }
500             catch (std::exception& ex) {
501                 m_log.error("caught exception extracting attributes: %s", ex.what());
502             }
503         }
504
505         if (tokens) {
506             for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
507                     t != make_indirect_iterator(tokens->end()); ++t) {
508                 try {
509                     extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
510                 }
511                 catch (std::exception& ex) {
512                     m_log.error("caught exception extracting attributes: %s", ex.what());
513                 }
514             }
515         }
516
517         AttributeFilter* filter = application.getAttributeFilter();
518         if (filter && !resolvedAttributes.empty()) {
519             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
520             Locker filtlocker(filter);
521             try {
522                 filter->filterAttributes(fc, resolvedAttributes);
523             }
524             catch (std::exception& ex) {
525                 m_log.error("caught exception filtering attributes: %s", ex.what());
526                 m_log.error("dumping extracted attributes due to filtering exception");
527                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
528                 resolvedAttributes.clear();
529             }
530         }
531     }
532     else {
533         m_log.warn("no AttributeExtractor plugin installed, check log during startup");
534     }
535
536     try {
537         AttributeResolver* resolver = application.getAttributeResolver();
538         if (resolver) {
539             m_log.debug("resolving attributes...");
540
541             Locker locker(resolver);
542             auto_ptr<ResolutionContext> ctx(
543                 resolver->createResolutionContext(
544                     application,
545                     issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
546                     protocol,
547                     nameid,
548                     authncontext_class,
549                     authncontext_decl,
550                     tokens,
551                     &resolvedAttributes
552                     )
553                 );
554             resolver->resolveAttributes(*ctx);
555             // Copy over any pushed attributes.
556             while (!resolvedAttributes.empty()) {
557                 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
558                 resolvedAttributes.pop_back();
559             }
560             return ctx.release();
561         }
562     }
563     catch (std::exception& ex) {
564         m_log.error("attribute resolution failed: %s", ex.what());
565     }
566
567     if (!resolvedAttributes.empty()) {
568         try {
569             return new DummyContext(resolvedAttributes);
570         }
571         catch (bad_alloc&) {
572             for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
573         }
574     }
575     return nullptr;
576 }
577
578 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
579 {
580     policy.setMessageID(assertion.getID());
581     policy.setIssueInstant(assertion.getIssueInstantEpoch());
582
583     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
584         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
585         if (a2) {
586             m_log.debug("extracting issuer from SAML 2.0 assertion");
587             policy.setIssuer(a2->getIssuer());
588         }
589     }
590     else {
591         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
592         if (a1) {
593             m_log.debug("extracting issuer from SAML 1.x assertion");
594             policy.setIssuer(a1->getIssuer());
595         }
596     }
597
598     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
599         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
600             m_log.warn("non-system entity issuer, skipping metadata lookup");
601             return;
602         }
603         m_log.debug("searching metadata for assertion issuer...");
604         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
605         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
606         mc.entityID_unicode = policy.getIssuer()->getName();
607         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
608         mc.protocol = protocol;
609         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
610         if (!entity.first) {
611             auto_ptr_char iname(policy.getIssuer()->getName());
612             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
613         }
614         else if (!entity.second) {
615             m_log.warn("unable to find compatible IdP role in metadata");
616         }
617         else {
618             policy.setIssuerMetadata(entity.second);
619         }
620     }
621 }
622
623 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const xmltooling::HTTPRequest& request) const
624 {
625     if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
626         return nullptr;
627     try {
628         auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
629         LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
630         if (login_event) {
631             login_event->m_request = &request;
632             login_event->m_app = &application;
633             login_event->m_binding = getString("Binding").second;
634             event.release();
635             return login_event;
636         }
637         else {
638             m_log.warn("unable to audit event, log event object was of an incorrect type");
639         }
640     }
641     catch (std::exception& ex) {
642         m_log.warn("exception auditing event: %s", ex.what());
643     }
644     return nullptr;
645 }
646
647 #endif
648
649 void AssertionConsumerService::maintainHistory(
650     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
651     ) const
652 {
653     static const char* defProps="; path=/";
654
655     const PropertySet* sessionProps=application.getPropertySet("Sessions");
656     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
657
658     if (idpHistory.first && idpHistory.second) {
659         pair<bool,const char*> cookieProps=sessionProps->getString("idpHistoryProps");
660         if (!cookieProps.first)
661             cookieProps=sessionProps->getString("cookieProps");
662         if (!cookieProps.first)
663             cookieProps.second=defProps;
664
665         // Set an IdP history cookie locally (essentially just a CDC).
666         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
667
668         // Either leave in memory or set an expiration.
669         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
670         if (!days.first || days.second==0) {
671             string c = string(cdc.set(entityID)) + cookieProps.second;
672             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
673         }
674         else {
675             time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
676 #ifdef HAVE_GMTIME_R
677             struct tm res;
678             struct tm* ptime=gmtime_r(&now,&res);
679 #else
680             struct tm* ptime=gmtime(&now);
681 #endif
682             char timebuf[64];
683             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
684             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
685             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
686         }
687     }
688 }