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> run(SPRequest& request, string& entityID, bool isHandler=true) const;
79 pair<bool,long> doRequest(
80 const Application& application,
81 HTTPResponse& httpResponse,
83 const XMLCh* acsIndex,
85 const char* acsLocation,
86 const XMLCh* acsBinding,
89 const char* authnContextClassRef,
90 const char* authnContextComparison,
95 auto_ptr_char m_paosNS,m_ecpNS;
96 auto_ptr_XMLCh m_paosBinding;
99 vector<const XMLCh*> m_bindings;
100 map<const XMLCh*,MessageEncoder*> m_encoders;
101 MessageEncoder* m_ecp;
102 AuthnRequest* m_requestTemplate;
108 #if defined (_MSC_VER)
109 #pragma warning( pop )
112 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
114 return new SAML2SessionInitiator(p.first, p.second);
119 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
120 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
121 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
123 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
124 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
126 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
130 m_requestTemplate=NULL;
132 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
133 // Check for a template AuthnRequest to build from.
134 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
136 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
138 // If directed, build an ECP encoder.
139 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
141 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
142 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
145 catch (exception& ex) {
146 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
150 // Handle outgoing binding setup.
151 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
152 if (outgoing.first) {
153 m_outgoing = XMLString::replicate(outgoing.second);
154 XMLString::trim(m_outgoing);
157 // No override, so we'll install a default binding precedence.
158 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
159 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
160 m_outgoing = XMLString::transcode(prec.c_str());
164 XMLCh* start = m_outgoing;
165 while (start && *start) {
166 pos = XMLString::indexOf(start,chSpace);
168 *(start + pos)=chNull;
169 m_bindings.push_back(start);
171 auto_ptr_char b(start);
172 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
173 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
175 m_encoders[start] = encoder;
176 m_log.debug("supporting outgoing binding (%s)", b.get());
178 catch (exception& ex) {
179 m_log.error("error building MessageEncoder: %s", ex.what());
182 start = start + pos + 1;
189 // If Location isn't set, defer address registration until the setParent call.
190 pair<bool,const char*> loc = getString("Location");
192 string address = m_appId + loc.second + "::run::SAML2SI";
193 setAddress(address.c_str());
197 void SAML2SessionInitiator::setParent(const PropertySet* parent)
199 DOMPropertySet::setParent(parent);
200 pair<bool,const char*> loc = getString("Location");
202 string address = m_appId + loc.second + "::run::SAML2SI";
203 setAddress(address.c_str());
206 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
210 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
212 // First check for ECP support, since that doesn't require an IdP to be known.
214 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
215 string PAOS = request.getHeader("PAOS");
216 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
220 // We have to know the IdP to function unless this is ECP.
221 if (!ECP && (entityID.empty()))
222 return make_pair(false,0L);
225 const Handler* ACS=NULL;
227 pair<bool,const char*> acClass;
228 pair<bool,const char*> acComp;
229 bool isPassive=false,forceAuthn=false;
230 const Application& app=request.getApplication();
232 // ECP means the ACS will be by value no matter what.
233 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
236 option=request.getParameter("acsIndex");
238 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
240 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
241 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
242 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
247 option = request.getParameter("target");
251 // Always need to recover target URL to compute handler below.
252 recoverRelayState(request.getApplication(), request, request, target, false);
254 pair<bool,bool> flag;
255 option = request.getParameter("isPassive");
257 isPassive = (*option=='1' || *option=='t');
260 flag = getBool("isPassive");
261 isPassive = (flag.first && flag.second);
264 option = request.getParameter("forceAuthn");
266 forceAuthn = (*option=='1' || *option=='t');
269 flag = getBool("forceAuthn");
270 forceAuthn = (flag.first && flag.second);
274 if (acClass.second = request.getParameter("authnContextClassRef"))
275 acClass.first = true;
277 acClass = getString("authnContextClassRef");
279 if (acComp.second = request.getParameter("authnContextComparison"))
282 acComp = getString("authnContextComparison");
285 // We're running as a "virtual handler" from within the filter.
286 // The target resource is the current one and everything else is defaulted.
287 target=request.getRequestURL();
288 const PropertySet* settings = request.getRequestSettings().first;
290 pair<bool,bool> flag = settings->getBool("isPassive");
292 flag = getBool("isPassive");
293 isPassive = flag.first && flag.second;
295 flag = settings->getBool("forceAuthn");
297 flag = getBool("forceAuthn");
298 forceAuthn = flag.first && flag.second;
301 acClass = settings->getString("authnContextClassRef");
303 acClass = getString("authnContextClassRef");
304 acComp = settings->getString("authnContextComparison");
306 acComp = getString("authnContextComparison");
310 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
312 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
316 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
317 if (handlers.empty())
318 throw ConfigurationException("Unable to locate PAOS response endpoint.");
319 ACS = handlers.front();
322 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
324 ACS = app.getAssertionConsumerServiceByIndex(index.second);
326 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
329 ACS = app.getDefaultAssertionConsumerService();
333 // To invoke the request builder, the key requirement is to figure out how
334 // to express the ACS, by index or value, and if by value, where.
335 // We have to compute the handlerURL no matter what, because we may need to
336 // flip the index to an SSL-version.
337 string ACSloc=request.getHandlerURL(target.c_str());
339 SPConfig& conf = SPConfig::getConfig();
340 if (conf.isEnabled(SPConfig::OutOfProcess)) {
341 if (!acsByIndex.first || acsByIndex.second) {
344 // We may already have RelayState set if we looped back here,
345 // but just in case target is a resource, we reset it back.
347 option = request.getParameter("target");
352 // Determine index to use.
353 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
355 if (!strncmp(ACSloc.c_str(), "https", 5)) {
356 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
358 ix = ACS->getXMLString("index");
361 ix = ACS->getXMLString("index");
366 app, request, entityID.c_str(),
368 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
370 isPassive, forceAuthn,
371 acClass.first ? acClass.second : NULL,
372 acComp.first ? acComp.second : NULL,
377 // Since we're not passing by index, we need to fully compute the return URL and binding.
378 // Compute the ACS URL. We add the ACS location to the base handlerURL.
379 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
380 if (loc.first) ACSloc+=loc.second;
383 // We may already have RelayState set if we looped back here,
384 // but just in case target is a resource, we reset it back.
386 option = request.getParameter("target");
392 app, request, entityID.c_str(),
394 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
395 ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
396 isPassive, forceAuthn,
397 acClass.first ? acClass.second : NULL,
398 acComp.first ? acComp.second : NULL,
404 DDF out,in = DDF(m_address.c_str()).structure();
405 DDFJanitor jin(in), jout(out);
406 in.addmember("application_id").string(app.getId());
407 if (!entityID.empty())
408 in.addmember("entity_id").string(entityID.c_str());
410 in.addmember("isPassive").integer(1);
412 in.addmember("forceAuthn").integer(1);
414 in.addmember("authnContextClassRef").string(acClass.second);
416 in.addmember("authnContextComparison").string(acComp.second);
417 if (!acsByIndex.first || acsByIndex.second) {
419 // Determine index to use.
420 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
421 if (!strncmp(ACSloc.c_str(), "https", 5)) {
422 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
424 ix = ACS->getString("index");
427 ix = ACS->getString("index");
429 in.addmember("acsIndex").string(ix.second);
430 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
431 in.addmember("artifact").integer(1);
435 // Since we're not passing by index, we need to fully compute the return URL and binding.
436 // Compute the ACS URL. We add the ACS location to the base handlerURL.
437 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
438 if (loc.first) ACSloc+=loc.second;
439 in.addmember("acsLocation").string(ACSloc.c_str());
441 loc = ACS->getString("Binding");
442 in.addmember("acsBinding").string(loc.second);
443 if (XMLString::equals(loc.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
444 in.addmember("artifact").integer(1);
449 // We may already have RelayState set if we looped back here,
450 // but just in case target is a resource, we reset it back.
452 option = request.getParameter("target");
457 in.addmember("RelayState").string(target.c_str());
459 // Remote the processing.
460 out = request.getServiceProvider().getListenerService()->send(in);
461 return unwrap(request, out);
464 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
467 const char* aid=in["application_id"].string();
468 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
470 // Something's horribly wrong.
471 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
472 throw ConfigurationException("Unable to locate application for new session, deleted?");
476 DDFJanitor jout(ret);
478 // Wrap the outgoing object with a Response facade.
479 auto_ptr<HTTPResponse> http(getResponse(ret));
481 auto_ptr_XMLCh index(in["acsIndex"].string());
482 auto_ptr_XMLCh bind(in["acsBinding"].string());
484 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
486 // Since we're remoted, the result should either be a throw, which we pass on,
487 // a false/0 return, which we just return as an empty structure, or a response/redirect,
488 // which we capture in the facade and send back.
490 *app, *http.get(), in["entity_id"].string(),
492 (in["artifact"].integer() != 0),
493 in["acsLocation"].string(), bind.get(),
494 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
495 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
503 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
506 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
507 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
513 pair<bool,long> SAML2SessionInitiator::doRequest(
514 const Application& app,
515 HTTPResponse& httpResponse,
516 const char* entityID,
517 const XMLCh* acsIndex,
518 bool artifactInbound,
519 const char* acsLocation,
520 const XMLCh* acsBinding,
523 const char* authnContextClassRef,
524 const char* authnContextComparison,
529 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
531 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
532 const IDPSSODescriptor* role = NULL;
533 const EndpointType* ep = NULL;
534 const MessageEncoder* encoder = NULL;
536 // We won't need this for ECP, but safety dictates we get the lock here.
537 MetadataProvider* m=app.getMetadataProvider();
543 m_log.error("MessageEncoder for PAOS binding not available");
544 return make_pair(false,0L);
548 // Use metadata to locate the IdP's SSO service.
549 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
550 entity=m->getEntityDescriptor(mc);
552 m_log.warn("unable to locate metadata for provider (%s)", entityID);
553 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
555 else if (!entity.second) {
556 m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
558 return make_pair(false,0L);
559 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
561 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
562 m_log.warn("artifact binding selected for response, but identity provider lacks support");
564 return make_pair(false,0L);
565 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
568 // Loop over the supportable outgoing bindings.
569 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
570 vector<const XMLCh*>::const_iterator b;
571 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
572 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
573 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
574 if (enc!=m_encoders.end())
575 encoder = enc->second;
579 if (!ep || !encoder) {
580 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
582 return make_pair(false,0L);
583 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
587 preserveRelayState(app, httpResponse, relayState);
589 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
590 if (m_requestTemplate) {
591 // Freshen TS and ID.
593 req->setIssueInstant(time(NULL));
597 req->setDestination(ep->getLocation());
598 if (acsIndex && *acsIndex)
599 req->setAssertionConsumerServiceIndex(acsIndex);
601 auto_ptr_XMLCh wideloc(acsLocation);
602 req->setAssertionConsumerServiceURL(wideloc.get());
604 if (acsBinding && *acsBinding)
605 req->setProtocolBinding(acsBinding);
607 req->IsPassive(isPassive);
609 req->ForceAuthn(forceAuthn);
610 if (!req->getIssuer()) {
611 Issuer* issuer = IssuerBuilder::buildIssuer();
612 req->setIssuer(issuer);
613 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
615 if (!req->getNameIDPolicy()) {
616 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
617 req->setNameIDPolicy(namepol);
618 namepol->AllowCreate(true);
620 if (authnContextClassRef || authnContextComparison) {
621 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
623 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
624 req->setRequestedAuthnContext(reqContext);
626 if (authnContextClassRef) {
627 reqContext->getAuthnContextDeclRefs().clear();
628 auto_ptr_XMLCh wideclass(authnContextClassRef);
629 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
630 cref->setReference(wideclass.get());
631 reqContext->getAuthnContextClassRefs().push_back(cref);
634 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
635 req->setRequestedAuthnContext(NULL);
637 else if (authnContextComparison) {
638 auto_ptr_XMLCh widecomp(authnContextComparison);
639 reqContext->setComparison(widecomp.get());
643 if (ECP && entityID) {
644 auto_ptr_XMLCh wideid(entityID);
645 Scoping* scoping = req->getScoping();
647 scoping = ScopingBuilder::buildScoping();
648 req->setScoping(scoping);
650 IDPList* idplist = scoping->getIDPList();
652 idplist = IDPListBuilder::buildIDPList();
653 scoping->setIDPList(idplist);
655 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
656 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
657 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
658 entry->setProviderID(wideid.get());
659 entries.push_back(entry);
663 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
665 long ret = sendMessage(
666 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
668 req.release(); // freed by encoder
669 return make_pair(true,ret);
671 return make_pair(false,0L);