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