2 * Copyright 2001-2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SAML2SessionInitiator.cpp
20 * SAML 2.0 AuthnRequest support.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/SAMLConfig.h>
36 # include <saml/saml2/core/Protocols.h>
37 # include <saml/saml2/metadata/EndpointManager.h>
38 # include <saml/saml2/metadata/Metadata.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 using namespace opensaml::saml2;
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
44 #include <xercesc/util/XMLUniDefs.hpp>
47 using namespace shibsp;
48 using namespace opensaml;
49 using namespace xmltooling;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
59 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
62 SAML2SessionInitiator(const DOMElement* e, const char* appId);
63 virtual ~SAML2SessionInitiator() {
65 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66 XMLString::release(&m_outgoing);
67 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
68 delete m_requestTemplate;
74 void setParent(const PropertySet* parent);
75 void receive(DDF& in, ostream& out);
76 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
77 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
80 pair<bool,long> doRequest(
81 const Application& application,
82 const HTTPRequest* httpRequest,
83 HTTPResponse& httpResponse,
85 const XMLCh* acsIndex,
87 const char* acsLocation,
88 const XMLCh* acsBinding,
91 const char* authnContextClassRef,
92 const char* authnContextComparison,
97 auto_ptr_char m_paosNS,m_ecpNS;
98 auto_ptr_XMLCh m_paosBinding;
101 vector<const XMLCh*> m_bindings;
102 map<const XMLCh*,MessageEncoder*> m_encoders;
103 MessageEncoder* m_ecp;
104 AuthnRequest* m_requestTemplate;
110 #if defined (_MSC_VER)
111 #pragma warning( pop )
114 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
116 return new SAML2SessionInitiator(p.first, p.second);
121 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
122 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
123 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
125 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
126 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
128 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
132 m_requestTemplate=NULL;
134 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
135 // Check for a template AuthnRequest to build from.
136 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
138 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
140 // If directed, build an ECP encoder.
141 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
143 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
144 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
147 catch (exception& ex) {
148 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
152 // Handle outgoing binding setup.
153 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
154 if (outgoing.first) {
155 m_outgoing = XMLString::replicate(outgoing.second);
156 XMLString::trim(m_outgoing);
159 // No override, so we'll install a default binding precedence.
160 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
161 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
162 m_outgoing = XMLString::transcode(prec.c_str());
166 XMLCh* start = m_outgoing;
167 while (start && *start) {
168 pos = XMLString::indexOf(start,chSpace);
170 *(start + pos)=chNull;
171 m_bindings.push_back(start);
173 auto_ptr_char b(start);
174 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
175 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
177 m_encoders[start] = encoder;
178 m_log.debug("supporting outgoing binding (%s)", b.get());
180 catch (exception& ex) {
181 m_log.error("error building MessageEncoder: %s", ex.what());
184 start = start + pos + 1;
191 // If Location isn't set, defer address registration until the setParent call.
192 pair<bool,const char*> loc = getString("Location");
194 string address = m_appId + loc.second + "::run::SAML2SI";
195 setAddress(address.c_str());
199 void SAML2SessionInitiator::setParent(const PropertySet* parent)
201 DOMPropertySet::setParent(parent);
202 pair<bool,const char*> loc = getString("Location");
204 string address = m_appId + loc.second + "::run::SAML2SI";
205 setAddress(address.c_str());
208 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
212 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
214 // First check for ECP support, since that doesn't require an IdP to be known.
216 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
217 string PAOS = request.getHeader("PAOS");
218 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
222 // We have to know the IdP to function unless this is ECP.
223 if (!ECP && (entityID.empty()))
224 return make_pair(false,0L);
228 const Handler* ACS=NULL;
230 pair<bool,const char*> acClass;
231 pair<bool,const char*> acComp;
232 bool isPassive=false,forceAuthn=false;
233 const Application& app=request.getApplication();
235 // ECP means the ACS will be by value no matter what.
236 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
239 option=request.getParameter("acsIndex");
241 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
243 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
244 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
245 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
250 option = request.getParameter("target");
254 // Always need to recover target URL to compute handler below.
255 recoverRelayState(request.getApplication(), request, request, target, false);
257 pair<bool,bool> flag;
258 option = request.getParameter("isPassive");
260 isPassive = (*option=='1' || *option=='t');
263 flag = getBool("isPassive");
264 isPassive = (flag.first && flag.second);
267 option = request.getParameter("forceAuthn");
269 forceAuthn = (*option=='1' || *option=='t');
272 flag = getBool("forceAuthn");
273 forceAuthn = (flag.first && flag.second);
277 if (acClass.second = request.getParameter("authnContextClassRef"))
278 acClass.first = true;
280 acClass = getString("authnContextClassRef");
282 if (acComp.second = request.getParameter("authnContextComparison"))
285 acComp = getString("authnContextComparison");
288 // We're running as a "virtual handler" from within the filter.
289 // The target resource is the current one and everything else is defaulted.
290 target=request.getRequestURL();
291 const PropertySet* settings = request.getRequestSettings().first;
293 pair<bool,bool> flag = settings->getBool("isPassive");
295 flag = getBool("isPassive");
296 isPassive = flag.first && flag.second;
298 flag = settings->getBool("forceAuthn");
300 flag = getBool("forceAuthn");
301 forceAuthn = flag.first && flag.second;
304 acClass = settings->getString("authnContextClassRef");
306 acClass = getString("authnContextClassRef");
307 acComp = settings->getString("authnContextComparison");
309 acComp = getString("authnContextComparison");
313 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
315 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
319 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
320 if (handlers.empty())
321 throw ConfigurationException("Unable to locate PAOS response endpoint.");
322 ACS = handlers.front();
325 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
327 ACS = app.getAssertionConsumerServiceByIndex(index.second);
329 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
332 ACS = app.getDefaultAssertionConsumerService();
336 // To invoke the request builder, the key requirement is to figure out how
337 // to express the ACS, by index or value, and if by value, where.
338 // We have to compute the handlerURL no matter what, because we may need to
339 // flip the index to an SSL-version.
340 string ACSloc=request.getHandlerURL(target.c_str());
342 SPConfig& conf = SPConfig::getConfig();
343 if (conf.isEnabled(SPConfig::OutOfProcess)) {
344 if (!acsByIndex.first || acsByIndex.second) {
347 // We may already have RelayState set if we looped back here,
348 // but just in case target is a resource, we reset it back.
350 option = request.getParameter("target");
355 // Determine index to use.
356 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
358 if (!strncmp(ACSloc.c_str(), "https", 5)) {
359 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
361 ix = ACS->getXMLString("index");
364 ix = ACS->getXMLString("index");
369 app, &request, request, entityID.c_str(),
371 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
373 isPassive, forceAuthn,
374 acClass.first ? acClass.second : NULL,
375 acComp.first ? acComp.second : NULL,
380 // Since we're not passing by index, we need to fully compute the return URL and binding.
381 // Compute the ACS URL. We add the ACS location to the base handlerURL.
382 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
383 if (loc.first) ACSloc+=loc.second;
386 // We may already have RelayState set if we looped back here,
387 // but just in case target is a resource, we reset it back.
389 option = request.getParameter("target");
395 app, &request, request, entityID.c_str(),
397 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
398 ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
399 isPassive, forceAuthn,
400 acClass.first ? acClass.second : NULL,
401 acComp.first ? acComp.second : NULL,
407 DDF out,in = DDF(m_address.c_str()).structure();
408 DDFJanitor jin(in), jout(out);
409 in.addmember("application_id").string(app.getId());
410 if (!entityID.empty())
411 in.addmember("entity_id").string(entityID.c_str());
413 in.addmember("isPassive").integer(1);
415 in.addmember("forceAuthn").integer(1);
417 in.addmember("authnContextClassRef").string(acClass.second);
419 in.addmember("authnContextComparison").string(acComp.second);
420 if (!acsByIndex.first || acsByIndex.second) {
422 // Determine index to use.
423 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
424 if (!strncmp(ACSloc.c_str(), "https", 5)) {
425 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
427 ix = ACS->getString("index");
430 ix = ACS->getString("index");
432 in.addmember("acsIndex").string(ix.second);
433 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
434 in.addmember("artifact").integer(1);
438 // Since we're not passing by index, we need to fully compute the return URL and binding.
439 // Compute the ACS URL. We add the ACS location to the base handlerURL.
440 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
441 if (loc.first) ACSloc+=loc.second;
442 in.addmember("acsLocation").string(ACSloc.c_str());
444 loc = ACS->getString("Binding");
445 in.addmember("acsBinding").string(loc.second);
446 if (XMLString::equals(loc.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
447 in.addmember("artifact").integer(1);
452 // We may already have RelayState set if we looped back here,
453 // but just in case target is a resource, we reset it back.
455 option = request.getParameter("target");
460 in.addmember("RelayState").string(target.c_str());
462 // Remote the processing.
463 out = request.getServiceProvider().getListenerService()->send(in);
464 return unwrap(request, out);
467 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
469 // See if there's any response to send back.
470 if (!out["redirect"].isnull() || !out["response"].isnull()) {
471 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
472 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
474 return RemotedHandler::unwrap(request, out);
477 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
480 const char* aid=in["application_id"].string();
481 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
483 // Something's horribly wrong.
484 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
485 throw ConfigurationException("Unable to locate application for new session, deleted?");
489 DDFJanitor jout(ret);
491 // Wrap the outgoing object with a Response facade.
492 auto_ptr<HTTPResponse> http(getResponse(ret));
494 auto_ptr_XMLCh index(in["acsIndex"].string());
495 auto_ptr_XMLCh bind(in["acsBinding"].string());
497 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
498 string postData(in["PostData"].string() ? in["PostData"].string() : "");
500 // Since we're remoted, the result should either be a throw, which we pass on,
501 // a false/0 return, which we just return as an empty structure, or a response/redirect,
502 // which we capture in the facade and send back.
504 *app, NULL, *http.get(), in["entity_id"].string(),
506 (in["artifact"].integer() != 0),
507 in["acsLocation"].string(), bind.get(),
508 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
509 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
514 ret.addmember("RelayState").string(relayState.c_str());
520 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
523 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
524 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
530 pair<bool,long> SAML2SessionInitiator::doRequest(
531 const Application& app,
532 const HTTPRequest* httpRequest,
533 HTTPResponse& httpResponse,
534 const char* entityID,
535 const XMLCh* acsIndex,
536 bool artifactInbound,
537 const char* acsLocation,
538 const XMLCh* acsBinding,
541 const char* authnContextClassRef,
542 const char* authnContextComparison,
547 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
549 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
550 const IDPSSODescriptor* role = NULL;
551 const EndpointType* ep = NULL;
552 const MessageEncoder* encoder = NULL;
554 // We won't need this for ECP, but safety dictates we get the lock here.
555 MetadataProvider* m=app.getMetadataProvider();
561 m_log.error("MessageEncoder for PAOS binding not available");
562 return make_pair(false,0L);
566 // Use metadata to locate the IdP's SSO service.
567 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
568 entity=m->getEntityDescriptor(mc);
570 m_log.warn("unable to locate metadata for provider (%s)", entityID);
571 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
573 else if (!entity.second) {
574 m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
576 return make_pair(false,0L);
577 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
579 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
580 m_log.warn("artifact binding selected for response, but identity provider lacks support");
582 return make_pair(false,0L);
583 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
586 // Loop over the supportable outgoing bindings.
587 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
588 vector<const XMLCh*>::const_iterator b;
589 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
590 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
591 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
592 if (enc!=m_encoders.end())
593 encoder = enc->second;
597 if (!ep || !encoder) {
598 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
600 return make_pair(false,0L);
601 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
605 preserveRelayState(app, httpResponse, relayState);
607 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
608 if (m_requestTemplate) {
609 // Freshen TS and ID.
611 req->setIssueInstant(time(NULL));
615 req->setDestination(ep->getLocation());
616 if (acsIndex && *acsIndex)
617 req->setAssertionConsumerServiceIndex(acsIndex);
619 auto_ptr_XMLCh wideloc(acsLocation);
620 req->setAssertionConsumerServiceURL(wideloc.get());
622 if (acsBinding && *acsBinding)
623 req->setProtocolBinding(acsBinding);
625 req->IsPassive(isPassive);
627 req->ForceAuthn(forceAuthn);
628 if (!req->getIssuer()) {
629 Issuer* issuer = IssuerBuilder::buildIssuer();
630 req->setIssuer(issuer);
631 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
633 if (!req->getNameIDPolicy()) {
634 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
635 req->setNameIDPolicy(namepol);
636 namepol->AllowCreate(true);
638 if (authnContextClassRef || authnContextComparison) {
639 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
641 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
642 req->setRequestedAuthnContext(reqContext);
644 if (authnContextClassRef) {
645 reqContext->getAuthnContextDeclRefs().clear();
646 auto_ptr_XMLCh wideclass(authnContextClassRef);
647 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
648 cref->setReference(wideclass.get());
649 reqContext->getAuthnContextClassRefs().push_back(cref);
652 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
653 req->setRequestedAuthnContext(NULL);
655 else if (authnContextComparison) {
656 auto_ptr_XMLCh widecomp(authnContextComparison);
657 reqContext->setComparison(widecomp.get());
661 if (ECP && entityID) {
662 auto_ptr_XMLCh wideid(entityID);
663 Scoping* scoping = req->getScoping();
665 scoping = ScopingBuilder::buildScoping();
666 req->setScoping(scoping);
668 IDPList* idplist = scoping->getIDPList();
670 idplist = IDPListBuilder::buildIDPList();
671 scoping->setIDPList(idplist);
673 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
674 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
675 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
676 entry->setProviderID(wideid.get());
677 entries.push_back(entry);
681 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
684 // If the request object is available, we're responsible for the POST data.
685 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
688 long ret = sendMessage(
689 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
691 req.release(); // freed by encoder
692 return make_pair(true,ret);
694 return make_pair(false,0L);