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