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