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