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