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