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