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