2 * Copyright 2001-2007 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 <saml/SAMLConfig.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
43 #include <xercesc/util/XMLUniDefs.hpp>
46 using namespace shibsp;
47 using namespace opensaml;
48 using namespace xmltooling;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
61 SAML2SessionInitiator(const DOMElement* e, const char* appId);
62 virtual ~SAML2SessionInitiator() {
64 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
65 XMLString::release(&m_outgoing);
66 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
67 delete m_requestTemplate;
72 void setParent(const PropertySet* parent);
73 void receive(DDF& in, ostream& out);
74 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
77 pair<bool,long> doRequest(
78 const Application& application,
79 HTTPResponse& httpResponse,
81 const XMLCh* acsIndex,
82 const char* acsLocation,
83 const XMLCh* acsBinding,
86 const char* authnContextClassRef,
87 const char* authnContextComparison,
92 auto_ptr_char m_paosNS,m_ecpNS;
93 auto_ptr_XMLCh m_paosBinding;
96 vector<const XMLCh*> m_bindings;
97 map<const XMLCh*,MessageEncoder*> m_encoders;
98 MessageEncoder* m_ecp;
99 AuthnRequest* m_requestTemplate;
105 #if defined (_MSC_VER)
106 #pragma warning( pop )
109 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
111 return new SAML2SessionInitiator(p.first, p.second);
116 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
117 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
118 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
120 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
121 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
123 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
127 m_requestTemplate=NULL;
129 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
130 // Check for a template AuthnRequest to build from.
131 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
133 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
135 // If directed, build an ECP encoder.
136 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
138 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
139 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
142 catch (exception& ex) {
143 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
147 // Handle outgoing binding setup.
148 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
149 if (outgoing.first) {
150 m_outgoing = XMLString::replicate(outgoing.second);
151 XMLString::trim(m_outgoing);
154 // No override, so we'll install a default binding precedence.
155 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
156 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
157 m_outgoing = XMLString::transcode(prec.c_str());
161 XMLCh* start = m_outgoing;
162 while (start && *start) {
163 pos = XMLString::indexOf(start,chSpace);
165 *(start + pos)=chNull;
166 m_bindings.push_back(start);
168 auto_ptr_char b(start);
169 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
170 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
172 m_encoders[start] = encoder;
173 m_log.debug("supporting outgoing binding (%s)", b.get());
175 catch (exception& ex) {
176 m_log.error("error building MessageEncoder: %s", ex.what());
179 start = start + pos + 1;
186 // If Location isn't set, defer address registration until the setParent call.
187 pair<bool,const char*> loc = getString("Location");
189 string address = m_appId + loc.second + "::run::SAML2SI";
190 setAddress(address.c_str());
194 void SAML2SessionInitiator::setParent(const PropertySet* parent)
196 DOMPropertySet::setParent(parent);
197 pair<bool,const char*> loc = getString("Location");
199 string address = m_appId + loc.second + "::run::SAML2SI";
200 setAddress(address.c_str());
203 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
207 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
209 // First check for ECP support, since that doesn't require an IdP to be known.
211 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
212 string PAOS = request.getHeader("PAOS");
213 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
217 // We have to know the IdP to function unless this is ECP.
218 if (!ECP && (entityID.empty()))
219 return make_pair(false,0L);
222 const Handler* ACS=NULL;
224 pair<bool,const char*> acClass;
225 pair<bool,const char*> acComp;
226 bool isPassive=false,forceAuthn=false;
227 const Application& app=request.getApplication();
229 // ECP means the ACS will be by value no matter what.
230 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
233 option=request.getParameter("acsIndex");
235 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
237 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
238 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
239 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
244 option = request.getParameter("target");
247 if (acsByIndex.first && !acsByIndex.second) {
248 // Since we're passing the ACS by value, we need to compute the return URL,
249 // so we'll need the target resource for real.
250 recoverRelayState(request.getApplication(), request, request, target, false);
253 pair<bool,bool> flag;
254 option = request.getParameter("isPassive");
256 isPassive = (*option=='1' || *option=='t');
259 flag = getBool("isPassive");
260 isPassive = (flag.first && flag.second);
263 option = request.getParameter("forceAuthn");
265 forceAuthn = (*option=='1' || *option=='t');
268 flag = getBool("forceAuthn");
269 forceAuthn = (flag.first && flag.second);
273 if (acClass.second = request.getParameter("authnContextClassRef"))
274 acClass.first = true;
276 acClass = getString("authnContextClassRef");
278 if (acComp.second = request.getParameter("authnContextComparison"))
281 acComp = getString("authnContextComparison");
284 // We're running as a "virtual handler" from within the filter.
285 // The target resource is the current one and everything else is defaulted.
286 target=request.getRequestURL();
287 const PropertySet* settings = request.getRequestSettings().first;
289 pair<bool,bool> flag = settings->getBool("isPassive");
291 flag = getBool("isPassive");
292 isPassive = flag.first && flag.second;
294 flag = settings->getBool("forceAuthn");
296 flag = getBool("forceAuthn");
297 forceAuthn = flag.first && flag.second;
300 acClass = settings->getString("authnContextClassRef");
302 acClass = getString("authnContextClassRef");
303 acComp = settings->getString("authnContextComparison");
305 acComp = getString("authnContextComparison");
309 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
311 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
315 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
316 if (handlers.empty())
317 throw ConfigurationException("Unable to locate PAOS response endpoint.");
318 ACS = handlers.front();
321 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
323 ACS = app.getAssertionConsumerServiceByIndex(index.second);
325 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
328 ACS = app.getDefaultAssertionConsumerService();
332 // To invoke the request builder, the key requirement is to figure out how
333 // to express the ACS, by index or value, and if by value, where.
334 // We have to compute the handlerURL no matter what, because we may need to
335 // flip the index to an SSL-version.
336 string ACSloc=request.getHandlerURL(target.c_str());
338 SPConfig& conf = SPConfig::getConfig();
339 if (conf.isEnabled(SPConfig::OutOfProcess)) {
340 if (!acsByIndex.first || acsByIndex.second) {
343 // We may already have RelayState set if we looped back here,
344 // but just in case target is a resource, we reset it back.
346 option = request.getParameter("target");
351 // Determine index to use.
352 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
354 if (!strncmp(ACSloc.c_str(), "https", 5)) {
355 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
357 ix = ACS->getXMLString("index");
360 ix = ACS->getXMLString("index");
365 app, request, entityID.c_str(),
366 ix.second, NULL, NULL,
367 isPassive, forceAuthn,
368 acClass.first ? acClass.second : NULL,
369 acComp.first ? acComp.second : NULL,
374 // Since we're not passing by index, we need to fully compute the return URL and binding.
375 // Compute the ACS URL. We add the ACS location to the base handlerURL.
376 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
377 if (loc.first) ACSloc+=loc.second;
380 // We may already have RelayState set if we looped back here,
381 // but just in case target is a resource, we reset it back.
383 option = request.getParameter("target");
389 app, request, entityID.c_str(),
390 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
391 isPassive, forceAuthn,
392 acClass.first ? acClass.second : NULL,
393 acComp.first ? acComp.second : NULL,
399 DDF out,in = DDF(m_address.c_str()).structure();
400 DDFJanitor jin(in), jout(out);
401 in.addmember("application_id").string(app.getId());
402 if (!entityID.empty())
403 in.addmember("entity_id").string(entityID.c_str());
405 in.addmember("isPassive").integer(1);
407 in.addmember("forceAuthn").integer(1);
409 in.addmember("authnContextClassRef").string(acClass.second);
411 in.addmember("authnContextComparison").string(acComp.second);
412 if (!acsByIndex.first || acsByIndex.second) {
414 // Determine index to use.
415 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
416 if (!strncmp(ACSloc.c_str(), "https", 5)) {
417 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
419 ix = ACS->getString("index");
422 ix = ACS->getString("index");
424 in.addmember("acsIndex").string(ix.second);
428 // Since we're not passing by index, we need to fully compute the return URL and binding.
429 // Compute the ACS URL. We add the ACS location to the base handlerURL.
430 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
431 if (loc.first) ACSloc+=loc.second;
432 in.addmember("acsLocation").string(ACSloc.c_str());
434 in.addmember("acsBinding").string(ACS->getString("Binding").second);
438 // We may already have RelayState set if we looped back here,
439 // but just in case target is a resource, we reset it back.
441 option = request.getParameter("target");
446 in.addmember("RelayState").string(target.c_str());
448 // Remote the processing.
449 out = request.getServiceProvider().getListenerService()->send(in);
450 return unwrap(request, out);
453 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
456 const char* aid=in["application_id"].string();
457 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
459 // Something's horribly wrong.
460 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
461 throw ConfigurationException("Unable to locate application for new session, deleted?");
465 DDFJanitor jout(ret);
467 // Wrap the outgoing object with a Response facade.
468 auto_ptr<HTTPResponse> http(getResponse(ret));
470 auto_ptr_XMLCh index(in["acsIndex"].string());
471 auto_ptr_XMLCh bind(in["acsBinding"].string());
473 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
475 // Since we're remoted, the result should either be a throw, which we pass on,
476 // a false/0 return, which we just return as an empty structure, or a response/redirect,
477 // which we capture in the facade and send back.
479 *app, *http.get(), in["entity_id"].string(),
480 index.get(), in["acsLocation"].string(), bind.get(),
481 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
482 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
490 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
493 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
494 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
500 pair<bool,long> SAML2SessionInitiator::doRequest(
501 const Application& app,
502 HTTPResponse& httpResponse,
503 const char* entityID,
504 const XMLCh* acsIndex,
505 const char* acsLocation,
506 const XMLCh* acsBinding,
509 const char* authnContextClassRef,
510 const char* authnContextComparison,
515 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
517 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
518 const IDPSSODescriptor* role = NULL;
519 const EndpointType* ep = NULL;
520 const MessageEncoder* encoder = NULL;
522 // We won't need this for ECP, but safety dictates we get the lock here.
523 MetadataProvider* m=app.getMetadataProvider();
529 m_log.error("MessageEncoder for PAOS binding not available");
530 return make_pair(false,0L);
534 // Use metadata to locate the IdP's SSO service.
535 MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
536 entity=m->getEntityDescriptor(mc);
538 m_log.warn("unable to locate metadata for provider (%s)", entityID);
539 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
541 else if (!entity.second) {
542 m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
544 return make_pair(false,0L);
545 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
548 // Loop over the supportable outgoing bindings.
549 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
550 vector<const XMLCh*>::const_iterator b;
551 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
552 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
553 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
554 if (enc!=m_encoders.end())
555 encoder = enc->second;
559 if (!ep || !encoder) {
560 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
562 return make_pair(false,0L);
563 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
567 preserveRelayState(app, httpResponse, relayState);
569 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
570 if (m_requestTemplate) {
571 // Freshen TS and ID.
573 req->setIssueInstant(time(NULL));
577 req->setDestination(ep->getLocation());
578 if (acsIndex && *acsIndex)
579 req->setAssertionConsumerServiceIndex(acsIndex);
581 auto_ptr_XMLCh wideloc(acsLocation);
582 req->setAssertionConsumerServiceURL(wideloc.get());
584 if (acsBinding && *acsBinding)
585 req->setProtocolBinding(acsBinding);
587 req->IsPassive(isPassive);
589 req->ForceAuthn(forceAuthn);
590 if (!req->getIssuer()) {
591 Issuer* issuer = IssuerBuilder::buildIssuer();
592 req->setIssuer(issuer);
593 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
595 if (!req->getNameIDPolicy()) {
596 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
597 req->setNameIDPolicy(namepol);
598 namepol->AllowCreate(true);
600 if (authnContextClassRef || authnContextComparison) {
601 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
603 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
604 req->setRequestedAuthnContext(reqContext);
606 if (authnContextClassRef) {
607 reqContext->getAuthnContextDeclRefs().clear();
608 auto_ptr_XMLCh wideclass(authnContextClassRef);
609 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
610 cref->setReference(wideclass.get());
611 reqContext->getAuthnContextClassRefs().push_back(cref);
613 if (authnContextComparison &&
614 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
615 auto_ptr_XMLCh widecomp(authnContextComparison);
616 reqContext->setComparison(widecomp.get());
620 if (ECP && entityID) {
621 auto_ptr_XMLCh wideid(entityID);
622 Scoping* scoping = req->getScoping();
624 scoping = ScopingBuilder::buildScoping();
625 req->setScoping(scoping);
627 IDPList* idplist = scoping->getIDPList();
629 idplist = IDPListBuilder::buildIDPList();
630 scoping->setIDPList(idplist);
632 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
633 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
634 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
635 entry->setProviderID(wideid.get());
636 entries.push_back(entry);
640 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
642 long ret = sendMessage(
643 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
645 req.release(); // freed by encoder
646 return make_pair(true,ret);
648 return make_pair(false,0L);