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 #define BOOST_BIND_GLOBAL_PLACEHOLDERS
39 # include <boost/bind.hpp>
40 # include <boost/algorithm/string.hpp>
41 # include <boost/iterator/indirect_iterator.hpp>
42 # include <saml/exceptions.h>
43 # include <saml/SAMLConfig.h>
44 # include <saml/saml2/core/Protocols.h>
45 # include <saml/saml2/metadata/EndpointManager.h>
46 # include <saml/saml2/metadata/Metadata.h>
47 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
48 # include <saml/util/SAMLConstants.h>
49 # include <xmltooling/XMLToolingConfig.h>
50 # include <xmltooling/util/ParserPool.h>
51 # include <xercesc/util/Base64.hpp>
52 using namespace opensaml::saml2;
53 using namespace opensaml::saml2p;
54 using namespace opensaml::saml2md;
55 #else
56 # include "lite/SAMLConstants.h"
57 # include <xercesc/util/XMLUniDefs.hpp>
58 #endif
59
60 #include <boost/scoped_ptr.hpp>
61
62 using namespace shibsp;
63 using namespace opensaml;
64 using namespace xmltooling;
65 using namespace boost;
66 using namespace std;
67
68 namespace shibsp {
69
70 #if defined (_MSC_VER)
71 #pragma warning( push )
72 #pragma warning( disable : 4250 )
73 #endif
74
75 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
76 {
77 public:
78 SAML2SessionInitiator(const DOMElement* e, const char* appId, bool deprecationSupport);
~SAML2SessionInitiator()79 virtual ~SAML2SessionInitiator() {}
80
81 void init(const char* location); // encapsulates actions that need to run either in the c'tor or setParent
82
83 void setParent(const PropertySet* parent);
84 void receive(DDF& in, ostream& out);
85 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
86 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
87
getProtocolFamily() const88 const XMLCh* getProtocolFamily() const {
89 return samlconstants::SAML20P_NS;
90 }
91
92 #ifndef SHIBSP_LITE
generateMetadata(saml2md::SPSSODescriptor & role,const char * handlerURL) const93 void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
94 doGenerateMetadata(role, handlerURL);
95 }
96 #endif
97
98 private:
99 pair<bool,long> doRequest(
100 const Application& application,
101 const HTTPRequest* httpRequest,
102 HTTPResponse& httpResponse,
103 const char* entityID,
104 const XMLCh* acsIndex,
105 const char* attributeIndex,
106 bool artifactInbound,
107 const char* acsLocation,
108 const XMLCh* acsBinding,
109 bool isPassive,
110 bool forceAuthn,
111 const char* authnContextClassRef,
112 const char* authnContextComparison,
113 const char* NameIDFormat,
114 const char* SPNameQualifier,
115 const char* requestTemplate,
116 const char* outgoingBinding,
117 string& relayState
118 ) const;
119
120 string m_appId;
121 bool m_deprecationSupport;
122 auto_ptr_char m_paosNS,m_ecpNS;
123 auto_ptr_XMLCh m_paosBinding;
124 #ifndef SHIBSP_LITE
125 vector<string> m_bindings;
126 map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
127 scoped_ptr<MessageEncoder> m_ecp;
128 scoped_ptr<AuthnRequest> m_requestTemplate;
129 #else
130 bool m_ecp;
131 #endif
132 };
133
134 #if defined (_MSC_VER)
135 #pragma warning( pop )
136 #endif
137
138 class SHIBSP_DLLLOCAL SessionInitiatorNodeFilter : public DOMNodeFilter
139 {
140 public:
acceptNode(const DOMNode * node) const141 FilterAction acceptNode(const DOMNode* node) const {
142 return FILTER_REJECT;
143 }
144 };
145
146 static SHIBSP_DLLLOCAL SessionInitiatorNodeFilter g_SINFilter;
147
SAML2SessionInitiatorFactory(const pair<const DOMElement *,const char * > & p,bool deprecationSupport)148 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p, bool deprecationSupport)
149 {
150 return new SAML2SessionInitiator(p.first, p.second, deprecationSupport);
151 }
152
153 };
154
SAML2SessionInitiator(const DOMElement * e,const char * appId,bool deprecationSupport)155 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId, bool deprecationSupport)
156 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.SAML2"), &g_SINFilter, this),
157 m_appId(appId), m_deprecationSupport(deprecationSupport),
158 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
159 #ifdef SHIBSP_LITE
160 ,m_ecp(false)
161 #endif
162 {
163 #ifndef SHIBSP_LITE
164 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
165 // Check for a template AuthnRequest to build from.
166 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
167 if (child)
168 m_requestTemplate.reset(dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child)));
169 }
170 #endif
171
172 // If Location isn't set, defer initialization until the setParent call.
173 pair<bool,const char*> loc = getString("Location");
174 if (loc.first) {
175 init(loc.second);
176 }
177
178 m_supportedOptions.insert("isPassive");
179 }
180
setParent(const PropertySet * parent)181 void SAML2SessionInitiator::setParent(const PropertySet* parent)
182 {
183 DOMPropertySet::setParent(parent);
184 pair<bool,const char*> loc = getString("Location");
185 init(loc.second);
186 }
187
init(const char * location)188 void SAML2SessionInitiator::init(const char* location)
189 {
190 if (location) {
191 string address = m_appId + location + "::run::SAML2SI";
192 setAddress(address.c_str());
193 }
194 else {
195 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
196 }
197
198 pair<bool,bool> flag = getBool("ECP");
199 #ifdef SHIBSP_LITE
200 m_ecp = flag.first && flag.second;
201 #else
202
203 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
204 // If directed, build an ECP encoder.
205 if (flag.first && flag.second) {
206 try {
207 m_ecp.reset(SAMLConfig::getConfig().MessageEncoderManager.newPlugin(samlconstants::SAML20_BINDING_PAOS, getElement(), m_deprecationSupport));
208 }
209 catch (std::exception& ex) {
210 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
211 }
212 }
213
214 string dupBindings;
215 pair<bool,const char*> outgoing = getString("outgoingBindings");
216 if (outgoing.first) {
217 dupBindings = outgoing.second;
218 trim(dupBindings);
219 }
220 else {
221 // No override, so we'll install a default binding precedence.
222 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
223 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
224 }
225 split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
226 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
227 try {
228 boost::shared_ptr<MessageEncoder> encoder(SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, getElement(), m_deprecationSupport));
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
run(SPRequest & request,string & entityID,bool isHandler) const245 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, attributeIndex;
263 const char* requestTemplate = nullptr;
264 const char* outgoingBinding = nullptr;
265 bool isPassive=false,forceAuthn=false;
266 const Application& app = request.getApplication();
267
268 // ECP means the ACS will be by value no matter what.
269 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
270
271 if (isHandler) {
272 prop.second = request.getParameter("acsIndex");
273 if (prop.second && *prop.second) {
274 SPConfig::getConfig().deprecation().warn("Use of acsIndex when specifying response endpoint");
275 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
276 if (!ACS)
277 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
278 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
279 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
280 ACS = nullptr;
281 }
282 }
283
284 prop = getString("target", request);
285 if (prop.first)
286 target = prop.second;
287
288 // Always need to recover target URL to compute handler below.
289 recoverRelayState(app, request, request, target, false);
290 app.limitRedirect(request, target.c_str());
291
292 // Default is to allow externally supplied settings.
293 pair<bool,bool> externalInput = getBool("externalInput");
294 unsigned int settingMask = HANDLER_PROPERTY_MAP | HANDLER_PROPERTY_FIXED;
295 if (!externalInput.first || externalInput.second) {
296 settingMask |= HANDLER_PROPERTY_REQUEST;
297 requestTemplate = request.getParameter("template");
298 }
299
300 outgoingBinding = request.getParameter("outgoingBinding");
301
302 pair<bool,bool> flag = getBool("isPassive", request, settingMask);
303 isPassive = (flag.first && flag.second);
304
305 if (!isPassive) {
306 flag = getBool("forceAuthn", request, settingMask);
307 forceAuthn = (flag.first && flag.second);
308 }
309
310 // Populate via parameter, map, or property.
311 attributeIndex = getString("attributeIndex", request, settingMask);
312 acClass = getString("authnContextClassRef", request, settingMask);
313 acComp = getString("authnContextComparison", request, settingMask);
314 nidFormat = getString("NameIDFormat", request, settingMask);
315 spQual = getString("SPNameQualifier", request, settingMask);
316
317 }
318 else {
319 // Check for a hardwired target value in the map or handler.
320 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
321 if (prop.first)
322 target = prop.second;
323 else
324 target = request.getRequestURL();
325
326 pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
327 isPassive = flag.first && flag.second;
328 if (!isPassive) {
329 flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
330 forceAuthn = flag.first && flag.second;
331 }
332
333 // Populate via map or property.
334 attributeIndex = getString("attributeIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
335 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
336 acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
337 nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
338 spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
339 }
340
341 if (ECP)
342 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
343 else
344 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
345
346 if (!ACS) {
347 if (ECP) {
348 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily(), samlconstants::SAML20_BINDING_PAOS);
349 if (!ACS)
350 throw ConfigurationException("Unable to locate PAOS response endpoint.");
351 }
352 else {
353 // Try fixed index property.
354 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
355 if (index.first) {
356 SPConfig::getConfig().deprecation().warn("Use of acsIndex when specifying response endpoint");
357 ACS = app.getAssertionConsumerServiceByIndex(index.second);
358 }
359 }
360 }
361
362 // If we picked by index, validate the ACS for use with this protocol.
363 if (!ECP && (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily()))) {
364 if (ACS)
365 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 2.0 ACS, using default SAML 2.0 ACS");
366 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
367 if (!ACS)
368 throw ConfigurationException("Unable to locate a SAML 2.0 ACS endpoint to use for response.");
369 }
370
371 // To invoke the request builder, the key requirement is to figure out how
372 // to express the ACS, by index or value, and if by value, where.
373 // We have to compute the handlerURL no matter what, because we may need to
374 // flip the index to an SSL-version.
375 string ACSloc = request.getHandlerURL(target.c_str());
376
377 SPConfig& conf = SPConfig::getConfig();
378 if (conf.isEnabled(SPConfig::OutOfProcess)) {
379 if (acsByIndex.first && acsByIndex.second) {
380 // Pass by Index.
381 if (isHandler) {
382 // We may already have RelayState set if we looped back here,
383 // but we've turned it back into a resource by this point, so if there's
384 // a target on the URL, reset to that value.
385 prop.second = request.getParameter("target");
386 if (prop.second && *prop.second)
387 target = prop.second;
388 }
389
390 // Determine index to use.
391 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,nullptr);
392 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
393 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIBSPCONFIG_NS);
394 if (!ix.first)
395 ix = ACS->getXMLString("index");
396 }
397 else {
398 ix = ACS->getXMLString("index");
399 }
400
401 return doRequest(
402 app, &request, request, entityID.c_str(),
403 ix.second,
404 attributeIndex.first ? attributeIndex.second : nullptr,
405 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
406 nullptr, nullptr,
407 isPassive, forceAuthn,
408 acClass.first ? acClass.second : nullptr,
409 acComp.first ? acComp.second : nullptr,
410 nidFormat.first ? nidFormat.second : nullptr,
411 spQual.first ? spQual.second : nullptr,
412 requestTemplate,
413 outgoingBinding,
414 target
415 );
416 }
417
418 // Since we're not passing by index, we need to fully compute the return URL and binding.
419 // Compute the ACS URL. We add the ACS location to the base handlerURL.
420 prop = ACS->getString("Location");
421 if (prop.first)
422 ACSloc += prop.second;
423
424 if (isHandler) {
425 // We may already have RelayState set if we looped back here,
426 // but we've turned it back into a resource by this point, so if there's
427 // a target on the URL, reset to that value.
428 prop.second = request.getParameter("target");
429 if (prop.second && *prop.second)
430 target = prop.second;
431 }
432
433 return doRequest(
434 app, &request, request, entityID.c_str(),
435 nullptr,
436 attributeIndex.first ? attributeIndex.second : nullptr,
437 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
438 ACSloc.c_str(), ACS->getXMLString("Binding").second,
439 isPassive, forceAuthn,
440 acClass.first ? acClass.second : nullptr,
441 acComp.first ? acComp.second : nullptr,
442 nidFormat.first ? nidFormat.second : nullptr,
443 spQual.first ? spQual.second : nullptr,
444 requestTemplate,
445 outgoingBinding,
446 target
447 );
448 }
449
450 // Remote the call.
451 DDF out,in = DDF(m_address.c_str()).structure();
452 DDFJanitor jin(in), jout(out);
453 in.addmember("application_id").string(app.getId());
454 if (!entityID.empty())
455 in.addmember("entity_id").string(entityID.c_str());
456 if (isPassive)
457 in.addmember("isPassive").integer(1);
458 else if (forceAuthn)
459 in.addmember("forceAuthn").integer(1);
460 if (attributeIndex.first)
461 in.addmember("attributeIndex").string(attributeIndex.second);
462 if (acClass.first)
463 in.addmember("authnContextClassRef").string(acClass.second);
464 if (acComp.first)
465 in.addmember("authnContextComparison").string(acComp.second);
466 if (nidFormat.first)
467 in.addmember("NameIDFormat").string(nidFormat.second);
468 if (spQual.first)
469 in.addmember("SPNameQualifier").string(spQual.second);
470 if (requestTemplate)
471 in.addmember("template").string(requestTemplate);
472 if (outgoingBinding)
473 in.addmember("outgoingBinding").string(outgoingBinding);
474 if (acsByIndex.first && acsByIndex.second) {
475 // Determine index to use.
476 pair<bool,const char*> ix = pair<bool,const char*>(false,nullptr);
477 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
478 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIBSPCONFIG_NS);
479 if (!ix.first)
480 ix = ACS->getString("index");
481 }
482 else {
483 ix = ACS->getString("index");
484 }
485 in.addmember("acsIndex").string(ix.second);
486 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
487 in.addmember("artifact").integer(1);
488 }
489 else {
490 // Since we're not passing by index, we need to fully compute the return URL and binding.
491 // Compute the ACS URL. We add the ACS location to the base handlerURL.
492 prop = ACS->getString("Location");
493 if (prop.first)
494 ACSloc += prop.second;
495 in.addmember("acsLocation").string(ACSloc.c_str());
496 prop = ACS->getString("Binding");
497 in.addmember("acsBinding").string(prop.second);
498 if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
499 in.addmember("artifact").integer(1);
500 }
501
502 if (isHandler) {
503 // We may already have RelayState set if we looped back here,
504 // but we've turned it back into a resource by this point, so if there's
505 // a target on the URL, reset to that value.
506 prop.second = request.getParameter("target");
507 if (prop.second && *prop.second)
508 target = prop.second;
509 }
510 if (!target.empty())
511 in.addmember("RelayState").unsafe_string(target.c_str());
512
513 // Remote the processing.
514 out = send(request, in);
515 return unwrap(request, out);
516 }
517
unwrap(SPRequest & request,DDF & out) const518 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
519 {
520 // See if there's any response to send back.
521 if (!out["redirect"].isnull() || !out["response"].isnull()) {
522 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
523 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
524 }
525 return RemotedHandler::unwrap(request, out);
526 }
527
receive(DDF & in,ostream & out)528 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
529 {
530 // Find application.
531 const char* aid = in["application_id"].string();
532 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
533 if (!app) {
534 // Something's horribly wrong.
535 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
536 throw ConfigurationException("Unable to locate application for new session, deleted?");
537 }
538
539 DDF ret(nullptr);
540 DDFJanitor jout(ret);
541
542 // Wrap the outgoing object with a Response facade.
543 scoped_ptr<HTTPResponse> http(getResponse(*app, ret));
544
545 auto_ptr_XMLCh index(in["acsIndex"].string());
546 auto_ptr_XMLCh bind(in["acsBinding"].string());
547
548 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
549 string postData(in["PostData"].string() ? in["PostData"].string() : "");
550
551 // Since we're remoted, the result should either be a throw, which we pass on,
552 // a false/0 return, which we just return as an empty structure, or a response/redirect,
553 // which we capture in the facade and send back.
554 doRequest(
555 *app, nullptr, *http, in["entity_id"].string(),
556 index.get(),
557 in["attributeIndex"].string(),
558 (in["artifact"].integer() != 0),
559 in["acsLocation"].string(), bind.get(),
560 in["isPassive"].integer() == 1,
561 in["forceAuthn"].integer() == 1,
562 in["authnContextClassRef"].string(),
563 in["authnContextComparison"].string(),
564 in["NameIDFormat"].string(),
565 in["SPNameQualifier"].string(),
566 in["template"].string(),
567 in["outgoingBinding"].string(),
568 relayState
569 );
570 if (!ret.isstruct())
571 ret.structure();
572 ret.addmember("RelayState").unsafe_string(relayState.c_str());
573 out << ret;
574 }
575
doRequest(const Application & app,const HTTPRequest * httpRequest,HTTPResponse & httpResponse,const char * entityID,const XMLCh * acsIndex,const char * attributeIndex,bool artifactInbound,const char * acsLocation,const XMLCh * acsBinding,bool isPassive,bool forceAuthn,const char * authnContextClassRef,const char * authnContextComparison,const char * NameIDFormat,const char * SPNameQualifier,const char * requestTemplate,const char * outgoingBinding,string & relayState) const576 pair<bool,long> SAML2SessionInitiator::doRequest(
577 const Application& app,
578 const HTTPRequest* httpRequest,
579 HTTPResponse& httpResponse,
580 const char* entityID,
581 const XMLCh* acsIndex,
582 const char* attributeIndex,
583 bool artifactInbound,
584 const char* acsLocation,
585 const XMLCh* acsBinding,
586 bool isPassive,
587 bool forceAuthn,
588 const char* authnContextClassRef,
589 const char* authnContextComparison,
590 const char* NameIDFormat,
591 const char* SPNameQualifier,
592 const char* requestTemplate,
593 const char* outgoingBinding,
594 string& relayState
595 ) const
596 {
597 #ifndef SHIBSP_LITE
598 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
599
600 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
601 const IDPSSODescriptor* role = nullptr;
602 const EndpointType* ep = nullptr;
603 const MessageEncoder* encoder = nullptr;
604
605 // We won't need this for ECP, but safety dictates we get the lock here.
606 MetadataProvider* m = app.getMetadataProvider();
607 Locker locker(m);
608
609 if (ECP) {
610 encoder = m_ecp.get();
611 if (!encoder) {
612 m_log.error("MessageEncoder for PAOS binding not available");
613 return make_pair(false, 0L);
614 }
615 }
616 else {
617 // Use metadata to locate the IdP's SSO service.
618 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
619 entity = m->getEntityDescriptor(mc);
620 if (!entity.first) {
621 m_log.warn("unable to locate metadata for provider (%s)", entityID);
622 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
623 }
624 else if (!entity.second) {
625 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
626 if (getParent())
627 return make_pair(false, 0L);
628 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
629 }
630 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
631 m_log.warn("artifact binding selected for response, but identity provider lacks support");
632 if (getParent())
633 return make_pair(false, 0L);
634 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
635 }
636
637 // Loop over the supportable outgoing bindings.
638 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
639 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
640 if (outgoingBinding && *b != outgoingBinding)
641 continue;
642 auto_ptr_XMLCh wideb(b->c_str());
643 ep = EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(wideb.get());
644 if (ep) {
645 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
646 if (enc != m_encoders.end()) {
647 encoder = enc->second.get();
648 }
649 break;
650 }
651 }
652 if (!ep || !encoder) {
653 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
654 if (getParent())
655 return make_pair(false, 0L);
656 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
657 }
658 }
659
660 preserveRelayState(app, httpResponse, relayState);
661
662 const PropertySet* relyingParty = app.getRelyingParty(entity.first);
663
664 auto_ptr<AuthnRequest> req;
665
666 if (requestTemplate) {
667 XMLSize_t x;
668 XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(requestTemplate), &x);
669 if (decoded) {
670 istringstream is(reinterpret_cast<char*>(decoded));
671 XMLString::release((char**)&decoded);
672 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(is);
673 XercesJanitor<DOMDocument> docjanitor(doc);
674 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
675 docjanitor.release();
676 if (!dynamic_cast<AuthnRequest*>(xmlObject.get())) {
677 throw FatalProfileException("Template parameter was not a SAML AuthnRequest");
678 }
679 req.reset(dynamic_cast<AuthnRequest*>(xmlObject.release()));
680 }
681 else {
682 throw FatalProfileException("Unable to base64-eecode AuthnRequest template");
683 }
684 }
685 else {
686 req.reset(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
687 }
688
689 if (requestTemplate || m_requestTemplate) {
690 // Freshen TS and ID.
691 req->setID(nullptr);
692 req->setIssueInstant(time(nullptr));
693 }
694
695 if (ep)
696 req->setDestination(ep->getLocation());
697 if (acsIndex && *acsIndex)
698 req->setAssertionConsumerServiceIndex(acsIndex);
699 if (acsLocation) {
700 auto_ptr_XMLCh wideloc(acsLocation);
701 req->setAssertionConsumerServiceURL(wideloc.get());
702 }
703 if (acsBinding && *acsBinding)
704 req->setProtocolBinding(acsBinding);
705 if (isPassive)
706 req->IsPassive(isPassive);
707 else if (forceAuthn)
708 req->ForceAuthn(forceAuthn);
709 if (!req->getIssuer()) {
710 Issuer* issuer = IssuerBuilder::buildIssuer();
711 req->setIssuer(issuer);
712 issuer->setName(relyingParty->getXMLString("entityID").second);
713 }
714 if (!req->getNameIDPolicy()) {
715 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
716 req->setNameIDPolicy(namepol);
717 namepol->AllowCreate(true);
718 }
719
720 // Format may be specified, or inferred from RelyingParty.
721 if (NameIDFormat && *NameIDFormat) {
722 auto_ptr_XMLCh wideform(NameIDFormat);
723 req->getNameIDPolicy()->setFormat(wideform.get());
724 }
725 else {
726 pair<bool,const XMLCh*> rpFormat = relyingParty->getXMLString("NameIDFormat");
727 if (rpFormat.first)
728 req->getNameIDPolicy()->setFormat(rpFormat.second);
729 }
730
731 // SPNameQualifier may be specified, or inferred from RelyingParty.
732 if (SPNameQualifier && *SPNameQualifier) {
733 auto_ptr_XMLCh widequal(SPNameQualifier);
734 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
735 }
736 else {
737 pair<bool,const XMLCh*> rpQual = relyingParty->getXMLString("SPNameQualifier");
738 if (rpQual.first)
739 req->getNameIDPolicy()->setSPNameQualifier(rpQual.second);
740 }
741
742 // AttributeConsumingService may be specified, or inferred from RelyingParty.
743 if (attributeIndex && *attributeIndex) {
744 auto_ptr_XMLCh wideacs(attributeIndex);
745 req->setAttributeConsumingServiceIndex(wideacs.get());
746 }
747 else {
748 pair<bool,const XMLCh*> attrIndex = relyingParty->getXMLString("attributeIndex");
749 if (attrIndex.first)
750 req->setAttributeConsumingServiceIndex(attrIndex.second);
751 }
752
753 // If no specified AC class, infer from RelyingParty.
754 if (!authnContextClassRef || !*authnContextClassRef) {
755 pair<bool,const char*> rpContextClassRef = relyingParty->getString("authnContextClassRef");
756 if (rpContextClassRef.first)
757 authnContextClassRef = rpContextClassRef.second;
758 }
759
760 if (authnContextClassRef || authnContextComparison) {
761 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
762 if (!reqContext) {
763 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
764 req->setRequestedAuthnContext(reqContext);
765 }
766 if (authnContextClassRef) {
767 reqContext->getAuthnContextDeclRefs().clear();
768 string dup(authnContextClassRef);
769 trim(dup);
770 vector<string> contexts;
771 split(contexts, dup, is_space(), algorithm::token_compress_on);
772 for (vector<string>::const_iterator ac = contexts.begin(); ac != contexts.end(); ++ac) {
773 auto_ptr_XMLCh wideac(ac->c_str());
774 auto_ptr<AuthnContextClassRef> cref(AuthnContextClassRefBuilder::buildAuthnContextClassRef());
775 cref->setReference(wideac.get());
776 reqContext->getAuthnContextClassRefs().push_back(cref.get());
777 cref.release();
778 }
779 }
780
781 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
782 req->setRequestedAuthnContext(nullptr);
783 }
784 else if (authnContextComparison) {
785 auto_ptr_XMLCh widecomp(authnContextComparison);
786 reqContext->setComparison(widecomp.get());
787 } else {
788 pair<bool,const XMLCh*> rpComp = relyingParty->getXMLString("authnContextComparison");
789 if (rpComp.first)
790 reqContext->setComparison(rpComp.second);
791 }
792 }
793
794 pair<bool,bool> requestDelegation = getBool("requestDelegation");
795 if (!requestDelegation.first)
796 requestDelegation = relyingParty->getBool("requestDelegation");
797
798 if (requestDelegation.first && requestDelegation.second) {
799 if (entity.first) {
800 // Request delegation by including the IdP as an Audience.
801 // Also specify the expected session lifetime as the bound on the assertion lifetime.
802 const PropertySet* sessionProps = app.getPropertySet("Sessions");
803 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
804 if (!lifetime.first || lifetime.second == 0)
805 lifetime.second = 28800;
806 if (!req->getConditions())
807 req->setConditions(ConditionsBuilder::buildConditions());
808 req->getConditions()->setNotOnOrAfter(time(nullptr) + lifetime.second + 300);
809 AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
810 req->getConditions()->getConditions().push_back(audrest);
811 Audience* aud = AudienceBuilder::buildAudience();
812 audrest->getAudiences().push_back(aud);
813 aud->setAudienceURI(entity.first->getEntityID());
814 }
815 else {
816 m_log.warn("requestDelegation set, but IdP unknown at request time");
817 }
818 }
819
820 if (ECP && entityID) {
821 auto_ptr_XMLCh wideid(entityID);
822 Scoping* scoping = req->getScoping();
823 if (!scoping) {
824 scoping = ScopingBuilder::buildScoping();
825 req->setScoping(scoping);
826 }
827 IDPList* idplist = scoping->getIDPList();
828 if (!idplist) {
829 idplist = IDPListBuilder::buildIDPList();
830 scoping->setIDPList(idplist);
831 }
832 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
833 static bool (*wideequals)(const XMLCh*,const XMLCh*) = &XMLString::equals;
834 if (find_if(entries, boost::bind(wideequals, boost::bind(&IDPEntry::getProviderID, _1), wideid.get())) == nullptr) {
835 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
836 entry->setProviderID(wideid.get());
837 entries.push_back(entry);
838 }
839 }
840
841 XMLCh* genid = SAMLConfig::getConfig().generateIdentifier();
842 req->setID(genid);
843 XMLString::release(&genid);
844 req->setIssueInstant(time(nullptr));
845
846 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
847 if (ar_event) {
848 auto_ptr_char b(ep ? ep->getBinding() : nullptr);
849 ar_event->m_binding = b.get() ? b.get() : samlconstants::SAML20_BINDING_SOAP;
850 auto_ptr_char prot(getProtocolFamily());
851 ar_event->m_protocol = prot.get();
852 ar_event->m_peer = entity.first;
853 ar_event->m_saml2Request = req.get();
854 app.getServiceProvider().getTransactionLog()->write(*ar_event);
855 }
856
857 auto_ptr_char dest(ep ? ep->getLocation() : nullptr);
858
859 if (httpRequest) {
860 // If the request object is available, we're responsible for the POST data.
861 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
862 }
863
864 long ret = sendMessage(
865 *encoder,
866 req.get(),
867 relayState.c_str(),
868 dest.get(),
869 role,
870 app,
871 httpResponse,
872 (role && role->WantAuthnRequestsSigned()) ? "true" : "false"
873 );
874 req.release(); // freed by encoder
875 return make_pair(true, ret);
876 #else
877 return make_pair(false, 0L);
878 #endif
879 }
880