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