Log requestDelegation with no entity set
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2SessionInitiator.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  * SAML2SessionInitiator.cpp
23  *
24  * SAML 2.0 AuthnRequest support.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "handler/AbstractHandler.h"
32 #include "handler/RemotedHandler.h"
33 #include "handler/SessionInitiator.h"
34 #include "util/SPConstants.h"
35
36 #ifndef SHIBSP_LITE
37 # include "metadata/MetadataProviderCriteria.h"
38 # include <boost/bind.hpp>
39 # include <boost/algorithm/string.hpp>
40 # include <boost/iterator/indirect_iterator.hpp>
41 # include <saml/SAMLConfig.h>
42 # include <saml/saml2/core/Protocols.h>
43 # include <saml/saml2/metadata/EndpointManager.h>
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
46 # include <saml/util/SAMLConstants.h>
47 using namespace opensaml::saml2;
48 using namespace opensaml::saml2p;
49 using namespace opensaml::saml2md;
50 #else
51 # include "lite/SAMLConstants.h"
52 # include <xercesc/util/XMLUniDefs.hpp>
53 #endif
54
55 #include <boost/scoped_ptr.hpp>
56
57 using namespace shibsp;
58 using namespace opensaml;
59 using namespace xmltooling;
60 using namespace boost;
61 using namespace std;
62
63 namespace shibsp {
64
65 #if defined (_MSC_VER)
66     #pragma warning( push )
67     #pragma warning( disable : 4250 )
68 #endif
69
70     class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
71     {
72     public:
73         SAML2SessionInitiator(const DOMElement* e, const char* appId);
74         virtual ~SAML2SessionInitiator() {}
75
76         void init(const char* location);    // encapsulates actions that need to run either in the c'tor or setParent
77
78         void setParent(const PropertySet* parent);
79         void receive(DDF& in, ostream& out);
80         pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
81         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
82
83         const XMLCh* getProtocolFamily() const {
84             return samlconstants::SAML20P_NS;
85         }
86
87     private:
88         pair<bool,long> doRequest(
89             const Application& application,
90             const HTTPRequest* httpRequest,
91             HTTPResponse& httpResponse,
92             const char* entityID,
93             const XMLCh* acsIndex,
94             bool artifactInbound,
95             const char* acsLocation,
96             const XMLCh* acsBinding,
97             bool isPassive,
98             bool forceAuthn,
99             const char* authnContextClassRef,
100             const char* authnContextComparison,
101             const char* NameIDFormat,
102             const char* SPNameQualifier,
103             string& relayState
104             ) const;
105
106         string m_appId;
107         auto_ptr_char m_paosNS,m_ecpNS;
108         auto_ptr_XMLCh m_paosBinding;
109 #ifndef SHIBSP_LITE
110         vector<string> m_bindings;
111         map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
112         scoped_ptr<MessageEncoder> m_ecp;
113         scoped_ptr<AuthnRequest> m_requestTemplate;
114 #else
115         bool m_ecp;
116 #endif
117     };
118
119 #if defined (_MSC_VER)
120     #pragma warning( pop )
121 #endif
122
123     SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
124     {
125         return new SAML2SessionInitiator(p.first, p.second);
126     }
127
128 };
129
130 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
131     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2"), nullptr, &m_remapper), m_appId(appId),
132         m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
133 #ifdef SHIBSP_LITE
134         ,m_ecp(false)
135 #endif
136 {
137 #ifndef SHIBSP_LITE
138     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
139         // Check for a template AuthnRequest to build from.
140         DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
141         if (child)
142             m_requestTemplate.reset(dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child)));
143     }
144 #endif
145
146     // If Location isn't set, defer initialization until the setParent call.
147     pair<bool,const char*> loc = getString("Location");
148     if (loc.first) {
149         init(loc.second);
150     }
151
152     m_supportedOptions.insert("isPassive");
153 }
154
155 void SAML2SessionInitiator::setParent(const PropertySet* parent)
156 {
157     DOMPropertySet::setParent(parent);
158     pair<bool,const char*> loc = getString("Location");
159     init(loc.second);
160 }
161
162 void SAML2SessionInitiator::init(const char* location)
163 {
164     if (location) {
165         string address = m_appId + location + "::run::SAML2SI";
166         setAddress(address.c_str());
167     }
168     else {
169         m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
170     }
171
172     pair<bool,bool> flag = getBool("ECP");
173 #ifdef SHIBSP_LITE
174     m_ecp = flag.first && flag.second;
175 #else
176
177     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
178         // If directed, build an ECP encoder.
179         if (flag.first && flag.second) {
180             try {
181                 m_ecp.reset(
182                     SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
183                         samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(getElement(), nullptr)
184                         )
185                     );
186             }
187             catch (std::exception& ex) {
188                 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
189             }
190         }
191
192         string dupBindings;
193         pair<bool,const char*> outgoing = getString("outgoingBindings");
194         if (outgoing.first) {
195             dupBindings = outgoing.second;
196         }
197         else {
198             // No override, so we'll install a default binding precedence.
199             dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
200                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
201         }
202         split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
203         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
204             try {
205                 boost::shared_ptr<MessageEncoder> encoder(
206                     SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(getElement(),nullptr))
207                     );
208                 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
209                     m_encoders[*b] = encoder;
210                     m_log.debug("supporting outgoing binding (%s)", b->c_str());
211                 }
212                 else {
213                     m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
214                 }
215             }
216             catch (std::exception& ex) {
217                 m_log.error("error building MessageEncoder: %s", ex.what());
218             }
219         }
220     }
221 #endif
222 }
223
224 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
225 {
226     // First check for ECP support, since that doesn't require an IdP to be known.
227     bool ECP = false;
228     if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
229         string PAOS = request.getHeader("PAOS");
230         if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
231             ECP = true;
232     }
233
234     // We have to know the IdP to function unless this is ECP.
235     if ((!ECP && entityID.empty()) || !checkCompatibility(request, isHandler))
236         return make_pair(false, 0L);
237
238     string target;
239     pair<bool,const char*> prop;
240     const Handler* ACS = nullptr;
241     pair<bool,const char*> acClass, acComp, nidFormat, spQual;
242     bool isPassive=false,forceAuthn=false;
243     const Application& app = request.getApplication();
244
245     // ECP means the ACS will be by value no matter what.
246     pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
247
248     if (isHandler) {
249         prop.second = request.getParameter("acsIndex");
250         if (prop.second && *prop.second) {
251             ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
252             if (!ACS)
253                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
254             else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
255                 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
256                 ACS = nullptr;
257             }
258         }
259
260         prop = getString("target", request);
261         if (prop.first)
262             target = prop.second;
263
264         // Always need to recover target URL to compute handler below.
265         recoverRelayState(app, request, request, target, false);
266         app.limitRedirect(request, target.c_str());
267
268         pair<bool,bool> flag = getBool("isPassive", request);
269         isPassive = (flag.first && flag.second);
270
271         if (!isPassive) {
272             flag = getBool("forceAuthn", request);
273             forceAuthn = (flag.first && flag.second);
274         }
275
276         // Populate via parameter, map, or property.
277         acClass = getString("authnContextClassRef", request);
278         acComp = getString("authnContextComparison", request);
279         nidFormat = getString("NameIDFormat", request);
280         spQual = getString("SPNameQualifier", request);
281     }
282     else {
283         // Check for a hardwired target value in the map or handler.
284         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
285         if (prop.first)
286             target = prop.second;
287         else
288             target = request.getRequestURL();
289
290         pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
291         isPassive = flag.first && flag.second;
292         if (!isPassive) {
293             flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
294             forceAuthn = flag.first && flag.second;
295         }
296
297         // Populate via map or property.
298         acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
299         acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
300         nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
301         spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
302     }
303
304     if (ECP)
305         m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
306     else
307         m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
308
309     if (!ACS) {
310         if (ECP) {
311             ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily(), samlconstants::SAML20_BINDING_PAOS);
312             if (!ACS)
313                 throw ConfigurationException("Unable to locate PAOS response endpoint.");
314         }
315         else {
316             // Try fixed index property.
317             pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
318             if (index.first)
319                 ACS = app.getAssertionConsumerServiceByIndex(index.second);
320         }
321     }
322
323     // If we picked by index, validate the ACS for use with this protocol.
324     if (!ECP && (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily()))) {
325         if (ACS)
326             request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 2.0 ACS, using default SAML 2.0 ACS");
327         ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
328         if (!ACS)
329             throw ConfigurationException("Unable to locate a SAML 2.0 ACS endpoint to use for response.");
330     }
331
332     // To invoke the request builder, the key requirement is to figure out how
333     // to express the ACS, by index or value, and if by value, where.
334     // We have to compute the handlerURL no matter what, because we may need to
335     // flip the index to an SSL-version.
336     string ACSloc = request.getHandlerURL(target.c_str());
337
338     SPConfig& conf = SPConfig::getConfig();
339     if (conf.isEnabled(SPConfig::OutOfProcess)) {
340         if (acsByIndex.first && acsByIndex.second) {
341             // Pass by Index.
342             if (isHandler) {
343                 // We may already have RelayState set if we looped back here,
344                 // but we've turned it back into a resource by this point, so if there's
345                 // a target on the URL, reset to that value.
346                 prop.second = request.getParameter("target");
347                 if (prop.second && *prop.second)
348                     target = prop.second;
349             }
350
351             // Determine index to use.
352             pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,nullptr);
353             if (!strncmp(ACSloc.c_str(), "https://", 8)) {
354                 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
355                 if (!ix.first)
356                         ix = ACS->getXMLString("index");
357             }
358             else {
359                 ix = ACS->getXMLString("index");
360             }
361
362             return doRequest(
363                 app, &request, request, entityID.c_str(),
364                 ix.second,
365                 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
366                 nullptr, nullptr,
367                 isPassive, forceAuthn,
368                 acClass.first ? acClass.second : nullptr,
369                 acComp.first ? acComp.second : nullptr,
370                 nidFormat.first ? nidFormat.second : nullptr,
371                 spQual.first ? spQual.second : nullptr,
372                 target
373                 );
374         }
375
376         // Since we're not passing by index, we need to fully compute the return URL and binding.
377         // Compute the ACS URL. We add the ACS location to the base handlerURL.
378         prop = ACS->getString("Location");
379         if (prop.first)
380             ACSloc += prop.second;
381
382         if (isHandler) {
383             // We may already have RelayState set if we looped back here,
384             // but we've turned it back into a resource by this point, so if there's
385             // a target on the URL, reset to that value.
386             prop.second = request.getParameter("target");
387             if (prop.second && *prop.second)
388                 target = prop.second;
389         }
390
391         return doRequest(
392             app, &request, request, entityID.c_str(),
393             nullptr,
394             XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
395             ACSloc.c_str(), ACS->getXMLString("Binding").second,
396             isPassive, forceAuthn,
397             acClass.first ? acClass.second : nullptr,
398             acComp.first ? acComp.second : nullptr,
399             nidFormat.first ? nidFormat.second : nullptr,
400             spQual.first ? spQual.second : nullptr,
401             target
402             );
403     }
404
405     // Remote the call.
406     DDF out,in = DDF(m_address.c_str()).structure();
407     DDFJanitor jin(in), jout(out);
408     in.addmember("application_id").string(app.getId());
409     if (!entityID.empty())
410         in.addmember("entity_id").string(entityID.c_str());
411     if (isPassive)
412         in.addmember("isPassive").integer(1);
413     else if (forceAuthn)
414         in.addmember("forceAuthn").integer(1);
415     if (acClass.first)
416         in.addmember("authnContextClassRef").string(acClass.second);
417     if (acComp.first)
418         in.addmember("authnContextComparison").string(acComp.second);
419     if (nidFormat.first)
420         in.addmember("NameIDFormat").string(nidFormat.second);
421     if (spQual.first)
422         in.addmember("SPNameQualifier").string(spQual.second);
423     if (acsByIndex.first && acsByIndex.second) {
424         // Determine index to use.
425         pair<bool,const char*> ix = pair<bool,const char*>(false,nullptr);
426         if (!strncmp(ACSloc.c_str(), "https://", 8)) {
427                 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
428                 if (!ix.first)
429                         ix = ACS->getString("index");
430         }
431         else {
432                 ix = ACS->getString("index");
433         }
434         in.addmember("acsIndex").string(ix.second);
435         if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
436             in.addmember("artifact").integer(1);
437     }
438     else {
439         // Since we're not passing by index, we need to fully compute the return URL and binding.
440         // Compute the ACS URL. We add the ACS location to the base handlerURL.
441         prop = ACS->getString("Location");
442         if (prop.first)
443             ACSloc += prop.second;
444         in.addmember("acsLocation").string(ACSloc.c_str());
445         prop = ACS->getString("Binding");
446         in.addmember("acsBinding").string(prop.second);
447         if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
448             in.addmember("artifact").integer(1);
449     }
450
451     if (isHandler) {
452         // We may already have RelayState set if we looped back here,
453         // but we've turned it back into a resource by this point, so if there's
454         // a target on the URL, reset to that value.
455         prop.second = request.getParameter("target");
456         if (prop.second && *prop.second)
457             target = prop.second;
458     }
459     if (!target.empty())
460         in.addmember("RelayState").unsafe_string(target.c_str());
461
462     // Remote the processing.
463     out = request.getServiceProvider().getListenerService()->send(in);
464     return unwrap(request, out);
465 }
466
467 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
468 {
469     // See if there's any response to send back.
470     if (!out["redirect"].isnull() || !out["response"].isnull()) {
471         // If so, we're responsible for handling the POST data, probably by dropping a cookie.
472         preservePostData(request.getApplication(), request, request, out["RelayState"].string());
473     }
474     return RemotedHandler::unwrap(request, out);
475 }
476
477 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
478 {
479     // Find application.
480     const char* aid = in["application_id"].string();
481     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
482     if (!app) {
483         // Something's horribly wrong.
484         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
485         throw ConfigurationException("Unable to locate application for new session, deleted?");
486     }
487
488     DDF ret(nullptr);
489     DDFJanitor jout(ret);
490
491     // Wrap the outgoing object with a Response facade.
492     scoped_ptr<HTTPResponse> http(getResponse(ret));
493
494     auto_ptr_XMLCh index(in["acsIndex"].string());
495     auto_ptr_XMLCh bind(in["acsBinding"].string());
496
497     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
498     string postData(in["PostData"].string() ? in["PostData"].string() : "");
499
500     // Since we're remoted, the result should either be a throw, which we pass on,
501     // a false/0 return, which we just return as an empty structure, or a response/redirect,
502     // which we capture in the facade and send back.
503     doRequest(
504         *app, nullptr, *http, in["entity_id"].string(),
505         index.get(),
506         (in["artifact"].integer() != 0),
507         in["acsLocation"].string(), bind.get(),
508         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
509         in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
510         in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
511         relayState
512         );
513     if (!ret.isstruct())
514         ret.structure();
515     ret.addmember("RelayState").unsafe_string(relayState.c_str());
516     out << ret;
517 }
518
519 pair<bool,long> SAML2SessionInitiator::doRequest(
520     const Application& app,
521     const HTTPRequest* httpRequest,
522     HTTPResponse& httpResponse,
523     const char* entityID,
524     const XMLCh* acsIndex,
525     bool artifactInbound,
526     const char* acsLocation,
527     const XMLCh* acsBinding,
528     bool isPassive,
529     bool forceAuthn,
530     const char* authnContextClassRef,
531     const char* authnContextComparison,
532     const char* NameIDFormat,
533     const char* SPNameQualifier,
534     string& relayState
535     ) const
536 {
537 #ifndef SHIBSP_LITE
538     bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
539
540     pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
541     const IDPSSODescriptor* role = nullptr;
542     const EndpointType* ep = nullptr;
543     const MessageEncoder* encoder = nullptr;
544
545     // We won't need this for ECP, but safety dictates we get the lock here.
546     MetadataProvider* m = app.getMetadataProvider();
547     Locker locker(m);
548
549     if (ECP) {
550         encoder = m_ecp.get();
551         if (!encoder) {
552             m_log.error("MessageEncoder for PAOS binding not available");
553             return make_pair(false, 0L);
554         }
555     }
556     else {
557         // Use metadata to locate the IdP's SSO service.
558         MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
559         entity = m->getEntityDescriptor(mc);
560         if (!entity.first) {
561             m_log.warn("unable to locate metadata for provider (%s)", entityID);
562             throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
563         }
564         else if (!entity.second) {
565             m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
566             if (getParent())
567                 return make_pair(false, 0L);
568             throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
569         }
570         else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
571             m_log.warn("artifact binding selected for response, but identity provider lacks support");
572             if (getParent())
573                 return make_pair(false, 0L);
574             throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
575         }
576
577         // Loop over the supportable outgoing bindings.
578         role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
579         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
580             auto_ptr_XMLCh wideb(b->c_str());
581             if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(wideb.get())) {
582                 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
583                 if (enc != m_encoders.end())
584                     encoder = enc->second.get();
585                 break;
586             }
587         }
588         if (!ep || !encoder) {
589             m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
590             if (getParent())
591                 return make_pair(false, 0L);
592             throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
593         }
594     }
595
596     preserveRelayState(app, httpResponse, relayState);
597
598     auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
599     if (m_requestTemplate) {
600         // Freshen TS and ID.
601         req->setID(nullptr);
602         req->setIssueInstant(time(nullptr));
603     }
604
605     if (ep)
606         req->setDestination(ep->getLocation());
607     if (acsIndex && *acsIndex)
608         req->setAssertionConsumerServiceIndex(acsIndex);
609     if (acsLocation) {
610         auto_ptr_XMLCh wideloc(acsLocation);
611         req->setAssertionConsumerServiceURL(wideloc.get());
612     }
613     if (acsBinding && *acsBinding)
614         req->setProtocolBinding(acsBinding);
615     if (isPassive)
616         req->IsPassive(isPassive);
617     else if (forceAuthn)
618         req->ForceAuthn(forceAuthn);
619     if (!req->getIssuer()) {
620         Issuer* issuer = IssuerBuilder::buildIssuer();
621         req->setIssuer(issuer);
622         issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
623     }
624     if (!req->getNameIDPolicy()) {
625         NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
626         req->setNameIDPolicy(namepol);
627         namepol->AllowCreate(true);
628     }
629     if (NameIDFormat && *NameIDFormat) {
630         auto_ptr_XMLCh wideform(NameIDFormat);
631         req->getNameIDPolicy()->setFormat(wideform.get());
632     }
633     if (SPNameQualifier && *SPNameQualifier) {
634         auto_ptr_XMLCh widequal(SPNameQualifier);
635         req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
636     }
637     if (authnContextClassRef || authnContextComparison) {
638         RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
639         if (!reqContext) {
640             reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
641             req->setRequestedAuthnContext(reqContext);
642         }
643         if (authnContextClassRef) {
644             reqContext->getAuthnContextDeclRefs().clear();
645             string dup(authnContextClassRef);
646             vector<string> contexts;
647             split(contexts, dup, is_space(), algorithm::token_compress_on);
648             for (vector<string>::const_iterator ac = contexts.begin(); ac != contexts.end(); ++ac) {
649                 auto_ptr_XMLCh wideac(ac->c_str());
650                 auto_ptr<AuthnContextClassRef> cref(AuthnContextClassRefBuilder::buildAuthnContextClassRef());
651                 cref->setReference(wideac.get());
652                 reqContext->getAuthnContextClassRefs().push_back(cref.get());
653                 cref.release();
654             }
655         }
656
657         if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
658                 req->setRequestedAuthnContext(nullptr);
659         }
660         else if (authnContextComparison) {
661             auto_ptr_XMLCh widecomp(authnContextComparison);
662             reqContext->setComparison(widecomp.get());
663         }
664     }
665
666     pair<bool,bool> requestDelegation = getBool("requestDelegation");
667     if (requestDelegation.first && requestDelegation.second) {
668         if (entity.first) {
669             // Request delegation by including the IdP as an Audience.
670             // Also specify the expected session lifetime as the bound on the assertion lifetime.
671             const PropertySet* sessionProps = app.getPropertySet("Sessions");
672             pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
673             if (!lifetime.first || lifetime.second == 0)
674                 lifetime.second = 28800;
675             if (!req->getConditions())
676                 req->setConditions(ConditionsBuilder::buildConditions());
677             req->getConditions()->setNotOnOrAfter(time(nullptr) + lifetime.second + 300);
678             AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
679             req->getConditions()->getConditions().push_back(audrest);
680             Audience* aud = AudienceBuilder::buildAudience();
681             audrest->getAudiences().push_back(aud);
682             aud->setAudienceURI(entity.first->getEntityID());
683         }
684         else {
685             m_log.warn("requestDelegation set, but IdP unknown at request time");
686         }
687     }
688
689     if (ECP && entityID) {
690         auto_ptr_XMLCh wideid(entityID);
691         Scoping* scoping = req->getScoping();
692         if (!scoping) {
693             scoping = ScopingBuilder::buildScoping();
694             req->setScoping(scoping);
695         }
696         IDPList* idplist = scoping->getIDPList();
697         if (!idplist) {
698             idplist = IDPListBuilder::buildIDPList();
699             scoping->setIDPList(idplist);
700         }
701         VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
702         static bool (*wideequals)(const XMLCh*,const XMLCh*) = &XMLString::equals;
703         if (find_if(entries, boost::bind(wideequals, boost::bind(&IDPEntry::getProviderID, _1), wideid.get())) == nullptr) {
704             IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
705             entry->setProviderID(wideid.get());
706             entries.push_back(entry);
707         }
708     }
709
710     req->setID(SAMLConfig::getConfig().generateIdentifier());
711     req->setIssueInstant(time(nullptr));
712
713     scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
714     if (ar_event) {
715         auto_ptr_char b(ep ? ep->getBinding() : nullptr);
716         ar_event->m_binding = b.get() ? b.get() : samlconstants::SAML20_BINDING_SOAP;
717         auto_ptr_char prot(getProtocolFamily());
718         ar_event->m_protocol = prot.get();
719         ar_event->m_peer = entity.first;
720         ar_event->m_saml2Request = req.get();
721         app.getServiceProvider().getTransactionLog()->write(*ar_event);
722     }
723
724     auto_ptr_char dest(ep ? ep->getLocation() : nullptr);
725
726     if (httpRequest) {
727         // If the request object is available, we're responsible for the POST data.
728         preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
729     }
730
731     long ret = sendMessage(
732         *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
733         );
734     req.release();  // freed by encoder
735     return make_pair(true, ret);
736 #else
737     return make_pair(false, 0L);
738 #endif
739 }