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 "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;
73 void setParent(const PropertySet* parent);
74 void receive(DDF& in, ostream& out);
75 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
78 pair<bool,long> doRequest(
79 const Application& application,
80 HTTPResponse& httpResponse,
82 const XMLCh* acsIndex,
83 const char* acsLocation,
84 const XMLCh* acsBinding,
87 const char* authnContextClassRef,
88 const char* authnContextComparison,
93 auto_ptr_char m_paosNS,m_ecpNS;
94 auto_ptr_XMLCh m_paosBinding;
97 vector<const XMLCh*> m_bindings;
98 map<const XMLCh*,MessageEncoder*> m_encoders;
99 MessageEncoder* m_ecp;
100 AuthnRequest* m_requestTemplate;
106 #if defined (_MSC_VER)
107 #pragma warning( pop )
110 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
112 return new SAML2SessionInitiator(p.first, p.second);
117 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
118 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
119 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
121 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
122 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
124 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
128 m_requestTemplate=NULL;
130 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
131 // Check for a template AuthnRequest to build from.
132 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
134 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
136 // If directed, build an ECP encoder.
137 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
139 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
140 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
143 catch (exception& ex) {
144 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
148 // Handle outgoing binding setup.
149 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
150 if (outgoing.first) {
151 m_outgoing = XMLString::replicate(outgoing.second);
152 XMLString::trim(m_outgoing);
155 // No override, so we'll install a default binding precedence.
156 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
157 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
158 m_outgoing = XMLString::transcode(prec.c_str());
162 XMLCh* start = m_outgoing;
163 while (start && *start) {
164 pos = XMLString::indexOf(start,chSpace);
166 *(start + pos)=chNull;
167 m_bindings.push_back(start);
169 auto_ptr_char b(start);
170 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
171 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
173 m_encoders[start] = encoder;
174 m_log.debug("supporting outgoing binding (%s)", b.get());
176 catch (exception& ex) {
177 m_log.error("error building MessageEncoder: %s", ex.what());
180 start = start + pos + 1;
187 // If Location isn't set, defer address registration until the setParent call.
188 pair<bool,const char*> loc = getString("Location");
190 string address = m_appId + loc.second + "::run::SAML2SI";
191 setAddress(address.c_str());
195 void SAML2SessionInitiator::setParent(const PropertySet* parent)
197 DOMPropertySet::setParent(parent);
198 pair<bool,const char*> loc = getString("Location");
200 string address = m_appId + loc.second + "::run::SAML2SI";
201 setAddress(address.c_str());
204 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
208 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
210 // First check for ECP support, since that doesn't require an IdP to be known.
212 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
213 string PAOS = request.getHeader("PAOS");
214 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
218 // We have to know the IdP to function unless this is ECP.
219 if (!ECP && (entityID.empty()))
220 return make_pair(false,0L);
223 const Handler* ACS=NULL;
225 pair<bool,const char*> acClass;
226 pair<bool,const char*> acComp;
227 bool isPassive=false,forceAuthn=false;
228 const Application& app=request.getApplication();
230 // ECP means the ACS will be by value no matter what.
231 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
234 option=request.getParameter("acsIndex");
236 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
238 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
239 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
240 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
245 option = request.getParameter("target");
249 // Always need to recover target URL to compute handler below.
250 recoverRelayState(request.getApplication(), request, request, target, false);
252 pair<bool,bool> flag;
253 option = request.getParameter("isPassive");
255 isPassive = (*option=='1' || *option=='t');
258 flag = getBool("isPassive");
259 isPassive = (flag.first && flag.second);
262 option = request.getParameter("forceAuthn");
264 forceAuthn = (*option=='1' || *option=='t');
267 flag = getBool("forceAuthn");
268 forceAuthn = (flag.first && flag.second);
272 if (acClass.second = request.getParameter("authnContextClassRef"))
273 acClass.first = true;
275 acClass = getString("authnContextClassRef");
277 if (acComp.second = request.getParameter("authnContextComparison"))
280 acComp = getString("authnContextComparison");
283 // We're running as a "virtual handler" from within the filter.
284 // The target resource is the current one and everything else is defaulted.
285 target=request.getRequestURL();
286 const PropertySet* settings = request.getRequestSettings().first;
288 pair<bool,bool> flag = settings->getBool("isPassive");
290 flag = getBool("isPassive");
291 isPassive = flag.first && flag.second;
293 flag = settings->getBool("forceAuthn");
295 flag = getBool("forceAuthn");
296 forceAuthn = flag.first && flag.second;
299 acClass = settings->getString("authnContextClassRef");
301 acClass = getString("authnContextClassRef");
302 acComp = settings->getString("authnContextComparison");
304 acComp = getString("authnContextComparison");
308 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
310 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
314 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
315 if (handlers.empty())
316 throw ConfigurationException("Unable to locate PAOS response endpoint.");
317 ACS = handlers.front();
320 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
322 ACS = app.getAssertionConsumerServiceByIndex(index.second);
324 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
327 ACS = app.getDefaultAssertionConsumerService();
331 // To invoke the request builder, the key requirement is to figure out how
332 // to express the ACS, by index or value, and if by value, where.
333 // We have to compute the handlerURL no matter what, because we may need to
334 // flip the index to an SSL-version.
335 string ACSloc=request.getHandlerURL(target.c_str());
337 SPConfig& conf = SPConfig::getConfig();
338 if (conf.isEnabled(SPConfig::OutOfProcess)) {
339 if (!acsByIndex.first || acsByIndex.second) {
342 // We may already have RelayState set if we looped back here,
343 // but just in case target is a resource, we reset it back.
345 option = request.getParameter("target");
350 // Determine index to use.
351 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
353 if (!strncmp(ACSloc.c_str(), "https", 5)) {
354 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
356 ix = ACS->getXMLString("index");
359 ix = ACS->getXMLString("index");
364 app, request, entityID.c_str(),
365 ix.second, NULL, NULL,
366 isPassive, forceAuthn,
367 acClass.first ? acClass.second : NULL,
368 acComp.first ? acComp.second : NULL,
373 // Since we're not passing by index, we need to fully compute the return URL and binding.
374 // Compute the ACS URL. We add the ACS location to the base handlerURL.
375 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
376 if (loc.first) ACSloc+=loc.second;
379 // We may already have RelayState set if we looped back here,
380 // but just in case target is a resource, we reset it back.
382 option = request.getParameter("target");
388 app, request, entityID.c_str(),
389 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
390 isPassive, forceAuthn,
391 acClass.first ? acClass.second : NULL,
392 acComp.first ? acComp.second : NULL,
398 DDF out,in = DDF(m_address.c_str()).structure();
399 DDFJanitor jin(in), jout(out);
400 in.addmember("application_id").string(app.getId());
401 if (!entityID.empty())
402 in.addmember("entity_id").string(entityID.c_str());
404 in.addmember("isPassive").integer(1);
406 in.addmember("forceAuthn").integer(1);
408 in.addmember("authnContextClassRef").string(acClass.second);
410 in.addmember("authnContextComparison").string(acComp.second);
411 if (!acsByIndex.first || acsByIndex.second) {
413 // Determine index to use.
414 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
415 if (!strncmp(ACSloc.c_str(), "https", 5)) {
416 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
418 ix = ACS->getString("index");
421 ix = ACS->getString("index");
423 in.addmember("acsIndex").string(ix.second);
427 // Since we're not passing by index, we need to fully compute the return URL and binding.
428 // Compute the ACS URL. We add the ACS location to the base handlerURL.
429 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
430 if (loc.first) ACSloc+=loc.second;
431 in.addmember("acsLocation").string(ACSloc.c_str());
433 in.addmember("acsBinding").string(ACS->getString("Binding").second);
437 // We may already have RelayState set if we looped back here,
438 // but just in case target is a resource, we reset it back.
440 option = request.getParameter("target");
445 in.addmember("RelayState").string(target.c_str());
447 // Remote the processing.
448 out = request.getServiceProvider().getListenerService()->send(in);
449 return unwrap(request, out);
452 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
455 const char* aid=in["application_id"].string();
456 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
458 // Something's horribly wrong.
459 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
460 throw ConfigurationException("Unable to locate application for new session, deleted?");
464 DDFJanitor jout(ret);
466 // Wrap the outgoing object with a Response facade.
467 auto_ptr<HTTPResponse> http(getResponse(ret));
469 auto_ptr_XMLCh index(in["acsIndex"].string());
470 auto_ptr_XMLCh bind(in["acsBinding"].string());
472 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
474 // Since we're remoted, the result should either be a throw, which we pass on,
475 // a false/0 return, which we just return as an empty structure, or a response/redirect,
476 // which we capture in the facade and send back.
478 *app, *http.get(), in["entity_id"].string(),
479 index.get(), in["acsLocation"].string(), bind.get(),
480 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
481 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
489 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
492 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
493 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
499 pair<bool,long> SAML2SessionInitiator::doRequest(
500 const Application& app,
501 HTTPResponse& httpResponse,
502 const char* entityID,
503 const XMLCh* acsIndex,
504 const char* acsLocation,
505 const XMLCh* acsBinding,
508 const char* authnContextClassRef,
509 const char* authnContextComparison,
514 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
516 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
517 const IDPSSODescriptor* role = NULL;
518 const EndpointType* ep = NULL;
519 const MessageEncoder* encoder = NULL;
521 // We won't need this for ECP, but safety dictates we get the lock here.
522 MetadataProvider* m=app.getMetadataProvider();
528 m_log.error("MessageEncoder for PAOS binding not available");
529 return make_pair(false,0L);
533 // Use metadata to locate the IdP's SSO service.
534 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
535 entity=m->getEntityDescriptor(mc);
537 m_log.warn("unable to locate metadata for provider (%s)", entityID);
538 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
540 else if (!entity.second) {
541 m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
543 return make_pair(false,0L);
544 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
547 // Loop over the supportable outgoing bindings.
548 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
549 vector<const XMLCh*>::const_iterator b;
550 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
551 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
552 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
553 if (enc!=m_encoders.end())
554 encoder = enc->second;
558 if (!ep || !encoder) {
559 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
561 return make_pair(false,0L);
562 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
566 preserveRelayState(app, httpResponse, relayState);
568 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
569 if (m_requestTemplate) {
570 // Freshen TS and ID.
572 req->setIssueInstant(time(NULL));
576 req->setDestination(ep->getLocation());
577 if (acsIndex && *acsIndex)
578 req->setAssertionConsumerServiceIndex(acsIndex);
580 auto_ptr_XMLCh wideloc(acsLocation);
581 req->setAssertionConsumerServiceURL(wideloc.get());
583 if (acsBinding && *acsBinding)
584 req->setProtocolBinding(acsBinding);
586 req->IsPassive(isPassive);
588 req->ForceAuthn(forceAuthn);
589 if (!req->getIssuer()) {
590 Issuer* issuer = IssuerBuilder::buildIssuer();
591 req->setIssuer(issuer);
592 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
594 if (!req->getNameIDPolicy()) {
595 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
596 req->setNameIDPolicy(namepol);
597 namepol->AllowCreate(true);
599 if (authnContextClassRef || authnContextComparison) {
600 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
602 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
603 req->setRequestedAuthnContext(reqContext);
605 if (authnContextClassRef) {
606 reqContext->getAuthnContextDeclRefs().clear();
607 auto_ptr_XMLCh wideclass(authnContextClassRef);
608 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
609 cref->setReference(wideclass.get());
610 reqContext->getAuthnContextClassRefs().push_back(cref);
613 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
614 req->setRequestedAuthnContext(NULL);
616 else if (authnContextComparison) {
617 auto_ptr_XMLCh widecomp(authnContextComparison);
618 reqContext->setComparison(widecomp.get());
622 if (ECP && entityID) {
623 auto_ptr_XMLCh wideid(entityID);
624 Scoping* scoping = req->getScoping();
626 scoping = ScopingBuilder::buildScoping();
627 req->setScoping(scoping);
629 IDPList* idplist = scoping->getIDPList();
631 idplist = IDPListBuilder::buildIDPList();
632 scoping->setIDPList(idplist);
634 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
635 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
636 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
637 entry->setProviderID(wideid.get());
638 entries.push_back(entry);
642 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
644 long ret = sendMessage(
645 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
647 req.release(); // freed by encoder
648 return make_pair(true,ret);
650 return make_pair(false,0L);