Add relay state to exception only if non-empty
[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());  // may be namespace-qualified if inside handler element
165     if (!prop.first)
166         prop = getString("policyId");   // try unqualified
167     if (!prop.first)
168         prop = application.getString("policyId");   // unqualified in Application(s) element
169
170     // Lock metadata for use by policy.
171     Locker metadataLocker(application.getMetadataProvider());
172
173     // Create the policy.
174     scoped_ptr<opensaml::SecurityPolicy> policy(
175         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(
176             application, &IDPSSODescriptor::ELEMENT_QNAME, prop.second
177             )
178         );
179
180     string relayState;
181     scoped_ptr<XMLObject> msg;
182     try {
183         // Decode the message and process it in a protocol-specific way.
184         msg.reset(m_decoder->decode(relayState, httpRequest, *(policy.get())));
185         if (!msg)
186             throw BindingException("Failed to decode an SSO protocol response.");
187         implementProtocol(application, httpRequest, httpResponse, *policy, nullptr, *msg);
188
189         // History cookie.
190         auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
191         if (issuer.get() && *issuer.get())
192             maintainHistory(application, httpRequest, httpResponse, issuer.get());
193
194         const EntityDescriptor* entity =
195             dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata() ? policy->getIssuerMetadata()->getParent() : nullptr);
196         prop = application.getRelyingParty(entity)->getString("sessionHook");
197         if (prop.first) {
198             string hook(prop.second);
199             httpRequest.absolutize(hook);
200
201             // Compute the return URL. We use a self-referential link plus a hook indicator to break the cycle
202             // and the relay state.
203             const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
204             string returnURL = httpRequest.getRequestURL();
205             returnURL = returnURL.substr(0, returnURL.find('?')) + "?hook=1";
206             if (!relayState.empty())
207                 returnURL += "&target=" + encoder->encode(relayState.c_str());
208             if (hook.find('?') == string::npos)
209                 hook += '?';
210             else
211                 hook += '&';
212             hook += "return=" + encoder->encode(returnURL.c_str());
213
214             // Add the translated target resource in case it's of interest.
215             if (!relayState.empty()) {
216                 try {
217                     recoverRelayState(application, httpRequest, httpResponse, relayState, false);
218                     hook += "&target=" + encoder->encode(relayState.c_str());
219                 }
220                 catch (std::exception& ex) {
221                     m_log.warn("error recovering relay state: %s", ex.what());
222                 }
223             }
224
225             return make_pair(true, httpResponse.sendRedirect(hook.c_str()));
226         }
227
228         return finalizeResponse(application, httpRequest, httpResponse, relayState);
229     }
230     catch (XMLToolingException& ex) {
231         // Recover relay state.
232         if (!relayState.empty()) {
233             try {
234                 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
235             }
236             catch (std::exception& rsex) {
237                 m_log.warn("error recovering relay state: %s", rsex.what());
238                 relayState.erase();
239                 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
240             }
241         }
242
243         // Check for isPassive error condition.
244         const char* sc2 = ex.getProperty("statusCode2");
245         if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
246             pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get());  // may be namespace-qualified inside handler element
247             if (!ignore.first)
248                 ignore = getBool("ignoreNoPassive");    // try unqualified
249             if (ignore.first && ignore.second && !relayState.empty()) {
250                 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
251                 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
252             }
253         }
254         
255         if (!relayState.empty()) {
256             ex.addProperty("RelayState", relayState.c_str());
257         }
258
259         // Log the error.
260         try {
261             scoped_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
262             LoginEvent* error_event = dynamic_cast<LoginEvent*>(event.get());
263             if (error_event) {
264                 error_event->m_exception = &ex;
265                 error_event->m_request = &httpRequest;
266                 error_event->m_app = &application;
267                 if (policy->getIssuerMetadata())
268                     error_event->m_peer = dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata()->getParent());
269                 auto_ptr_char prot(getProtocolFamily());
270                 error_event->m_protocol = prot.get();
271                 error_event->m_binding = getString("Binding").second;
272                 error_event->m_saml2Response = dynamic_cast<const saml2p::StatusResponseType*>(msg.get());
273                 if (!error_event->m_saml2Response)
274                     error_event->m_saml1Response = dynamic_cast<const saml1p::Response*>(msg.get());
275                 application.getServiceProvider().getTransactionLog()->write(*error_event);
276             }
277             else {
278                 m_log.warn("unable to audit event, log event object was of an incorrect type");
279             }
280         }
281         catch (std::exception& ex2) {
282             m_log.warn("exception auditing event: %s", ex2.what());
283         }
284
285         // If no sign of annotation, try to annotate it now.
286         if (!ex.getProperty("statusCode")) {
287             annotateException(&ex, policy->getIssuerMetadata(), nullptr, false);    // wait to throw it
288         }
289
290         throw;
291     }
292 #else
293     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
294 #endif
295 }
296
297 pair<bool,long> AssertionConsumerService::finalizeResponse(
298     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, string& relayState
299     ) const
300 {
301     DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
302     DDFJanitor postjan(postData);
303     recoverRelayState(application, httpRequest, httpResponse, relayState);
304     application.limitRedirect(httpRequest, relayState.c_str());
305
306     // Now redirect to the state value. By now, it should be set to *something* usable.
307     // First check for POST data.
308     if (!postData.islist()) {
309         m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
310         return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
311     }
312     else {
313         m_log.debug("ACS returning via POST to: %s", relayState.c_str());
314         return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
315     }
316 }
317
318 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
319 {
320     if (!issuedTo || !*issuedTo)
321         return;
322
323     const PropertySet* props = application.getPropertySet("Sessions");
324     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
325     if (!checkAddress.first)
326         checkAddress.second = true;
327
328     if (checkAddress.second) {
329         m_log.debug("checking client address");
330         if (httpRequest.getRemoteAddr() != issuedTo) {
331             throw FatalProfileException(
332                "Your client's current address ($client_addr) differs from the one used when you authenticated "
333                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
334                 "Please contact your local support staff or help desk for assistance.",
335                 namedparams(1, "client_addr", httpRequest.getRemoteAddr().c_str())
336                 );
337         }
338     }
339 }
340
341 #ifndef SHIBSP_LITE
342
343 const XMLCh* AssertionConsumerService::getProtocolFamily() const
344 {
345     return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
346 }
347
348 const char* AssertionConsumerService::getType() const
349 {
350     return "AssertionConsumerService";
351 }
352
353 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
354 {
355     // Initial guess at index to use.
356     pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
357     if (!strncmp(handlerURL, "https", 5))
358         ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
359     if (!ix.first)
360         ix = getUnsignedInt("index");
361     if (!ix.first)
362         ix.second = 1;
363
364     // Find maximum index in use and go one higher.
365     const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
366     if (!services.empty() && ix.second <= services.back()->getIndex().second)
367         ix.second = services.back()->getIndex().second + 1;
368
369     const char* loc = getString("Location").second;
370     string hurl(handlerURL);
371     if (*loc != '/')
372         hurl += '/';
373     hurl += loc;
374     auto_ptr_XMLCh widen(hurl.c_str());
375
376     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
377     ep->setLocation(widen.get());
378     ep->setBinding(getXMLString("Binding").second);
379     ep->setIndex(ix.second);
380     role.getAssertionConsumerServices().push_back(ep);
381 }
382
383 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
384     const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
385     ) const
386 {
387     return new SecurityPolicy(application, role, validate, policyId);
388 }
389
390 namespace {
391     class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
392     {
393     public:
394         DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
395         }
396
397         virtual ~DummyContext() {
398             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
399         }
400
401         vector<Attribute*>& getResolvedAttributes() {
402             return m_attributes;
403         }
404         vector<Assertion*>& getResolvedAssertions() {
405             return m_tokens;
406         }
407
408     private:
409         vector<Attribute*> m_attributes;
410         static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
411     };
412 };
413
414 vector<Assertion*> DummyContext::m_tokens;
415
416 ResolutionContext* AssertionConsumerService::resolveAttributes(
417     const Application& application,
418     const saml2md::RoleDescriptor* issuer,
419     const XMLCh* protocol,
420     const saml1::NameIdentifier* v1nameid,
421     const saml2::NameID* nameid,
422     const XMLCh* authncontext_class,
423     const XMLCh* authncontext_decl,
424     const vector<const Assertion*>* tokens
425     ) const
426 {
427     return resolveAttributes(
428         application,
429         nullptr,
430         issuer,
431         protocol,
432         nullptr,
433         v1nameid,
434         nullptr,
435         nameid,
436         nullptr,
437         authncontext_class,
438         authncontext_decl,
439         tokens
440         );
441 }
442
443 ResolutionContext* AssertionConsumerService::resolveAttributes(
444     const Application& application,
445     const GenericRequest* request,
446     const RoleDescriptor* issuer,
447     const XMLCh* protocol,
448     const xmltooling::XMLObject* protmsg,
449     const saml1::NameIdentifier* v1nameid,
450     const saml1::AuthenticationStatement* v1statement,
451     const saml2::NameID* nameid,
452     const saml2::AuthnStatement* statement,
453     const XMLCh* authncontext_class,
454     const XMLCh* authncontext_decl,
455     const vector<const Assertion*>* tokens
456     ) const
457 {
458     // First we do the extraction of any pushed information, including from metadata.
459     vector<Attribute*> resolvedAttributes;
460     AttributeExtractor* extractor = application.getAttributeExtractor();
461     if (extractor) {
462         Locker extlocker(extractor);
463         if (issuer) {
464             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
465             if (mprefix.first) {
466                 m_log.debug("extracting metadata-derived attributes...");
467                 try {
468                     // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
469                     extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
470                     for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
471                             a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
472                         vector<string>& ids = a->getAliases();
473                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
474                             *id = mprefix.second + *id;
475                     }
476                 }
477                 catch (std::exception& ex) {
478                     m_log.error("caught exception extracting attributes: %s", ex.what());
479                 }
480             }
481         }
482
483         m_log.debug("extracting pushed attributes...");
484
485         if (protmsg) {
486             try {
487                 extractor->extractAttributes(application, request, issuer, *protmsg, resolvedAttributes);
488             }
489             catch (std::exception& ex) {
490                 m_log.error("caught exception extracting attributes: %s", ex.what());
491             }
492         }
493
494         if (v1nameid || nameid) {
495             try {
496                 if (v1nameid)
497                     extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
498                 else
499                     extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
500             }
501             catch (std::exception& ex) {
502                 m_log.error("caught exception extracting attributes: %s", ex.what());
503             }
504         }
505
506         if (v1statement || statement) {
507             try {
508                 if (v1statement)
509                     extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
510                 else
511                     extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
512             }
513             catch (std::exception& ex) {
514                 m_log.error("caught exception extracting attributes: %s", ex.what());
515             }
516         }
517
518         if (tokens) {
519             for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
520                     t != make_indirect_iterator(tokens->end()); ++t) {
521                 try {
522                     extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
523                 }
524                 catch (std::exception& ex) {
525                     m_log.error("caught exception extracting attributes: %s", ex.what());
526                 }
527             }
528         }
529
530         AttributeFilter* filter = application.getAttributeFilter();
531         if (filter && !resolvedAttributes.empty()) {
532             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class, authncontext_decl);
533             Locker filtlocker(filter);
534             try {
535                 filter->filterAttributes(fc, resolvedAttributes);
536             }
537             catch (std::exception& ex) {
538                 m_log.error("caught exception filtering attributes: %s", ex.what());
539                 m_log.error("dumping extracted attributes due to filtering exception");
540                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
541                 resolvedAttributes.clear();
542             }
543         }
544     }
545     else {
546         m_log.warn("no AttributeExtractor plugin installed, check log during startup");
547     }
548
549     try {
550         AttributeResolver* resolver = application.getAttributeResolver();
551         if (resolver) {
552             m_log.debug("resolving attributes...");
553
554             Locker locker(resolver);
555             auto_ptr<ResolutionContext> ctx(
556                 resolver->createResolutionContext(
557                     application,
558                     request,
559                     issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
560                     protocol,
561                     nameid,
562                     authncontext_class,
563                     authncontext_decl,
564                     tokens,
565                     &resolvedAttributes
566                     )
567                 );
568             resolver->resolveAttributes(*ctx);
569             // Copy over any pushed attributes.
570             while (!resolvedAttributes.empty()) {
571                 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
572                 resolvedAttributes.pop_back();
573             }
574             return ctx.release();
575         }
576     }
577     catch (std::exception& ex) {
578         m_log.error("attribute resolution failed: %s", ex.what());
579     }
580
581     if (!resolvedAttributes.empty()) {
582         try {
583             return new DummyContext(resolvedAttributes);
584         }
585         catch (bad_alloc&) {
586             for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
587         }
588     }
589     return nullptr;
590 }
591
592 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
593 {
594     policy.setMessageID(assertion.getID());
595     policy.setIssueInstant(assertion.getIssueInstantEpoch());
596
597     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
598         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
599         if (a2) {
600             m_log.debug("extracting issuer from SAML 2.0 assertion");
601             policy.setIssuer(a2->getIssuer());
602         }
603     }
604     else {
605         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
606         if (a1) {
607             m_log.debug("extracting issuer from SAML 1.x assertion");
608             policy.setIssuer(a1->getIssuer());
609         }
610     }
611
612     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
613         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
614             m_log.warn("non-system entity issuer, skipping metadata lookup");
615             return;
616         }
617         m_log.debug("searching metadata for assertion issuer...");
618         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
619         MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
620         mc.entityID_unicode = policy.getIssuer()->getName();
621         mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
622         mc.protocol = protocol;
623         entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
624         if (!entity.first) {
625             auto_ptr_char iname(policy.getIssuer()->getName());
626             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
627         }
628         else if (!entity.second) {
629             m_log.warn("unable to find compatible IdP role in metadata");
630         }
631         else {
632             policy.setIssuerMetadata(entity.second);
633         }
634     }
635 }
636
637 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const HTTPRequest& request) const
638 {
639     if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
640         return nullptr;
641     try {
642         auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
643         LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
644         if (login_event) {
645             login_event->m_request = &request;
646             login_event->m_app = &application;
647             login_event->m_binding = getString("Binding").second;
648             event.release();
649             return login_event;
650         }
651         else {
652             m_log.warn("unable to audit event, log event object was of an incorrect type");
653         }
654     }
655     catch (std::exception& ex) {
656         m_log.warn("exception auditing event: %s", ex.what());
657     }
658     return nullptr;
659 }
660
661 #endif
662
663 void AssertionConsumerService::maintainHistory(
664     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
665     ) const
666 {
667     static const char* defProps="; path=/";
668     static const char* sslProps="; path=/; secure";
669
670     const PropertySet* sessionProps = application.getPropertySet("Sessions");
671     pair<bool,bool> idpHistory = sessionProps->getBool("idpHistory");
672
673     if (idpHistory.first && idpHistory.second) {
674         pair<bool,const char*> cookieProps = sessionProps->getString("idpHistoryProps");
675         if (!cookieProps.first)
676             cookieProps = sessionProps->getString("cookieProps");
677         if (!cookieProps.first || !strcmp(cookieProps.second, "http"))
678             cookieProps.second = defProps;
679         else if (!strcmp(cookieProps.second, "https"))
680             cookieProps.second = sslProps;
681
682         // Set an IdP history cookie locally (essentially just a CDC).
683         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
684
685         // Either leave in memory or set an expiration.
686         pair<bool,unsigned int> days = sessionProps->getUnsignedInt("idpHistoryDays");
687         if (!days.first || days.second == 0) {
688             string c = string(cdc.set(entityID)) + cookieProps.second;
689             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
690         }
691         else {
692             time_t now = time(nullptr) + (days.second * 24 * 60 * 60);
693 #ifdef HAVE_GMTIME_R
694             struct tm res;
695             struct tm* ptime = gmtime_r(&now,&res);
696 #else
697             struct tm* ptime = gmtime(&now);
698 #endif
699             char timebuf[64];
700             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT", ptime);
701             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
702             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
703         }
704     }
705 }