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