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;
44 using namespace shibsp;
45 using namespace opensaml;
46 using namespace xmltooling;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
59 SAML2SessionInitiator(const DOMElement* e, const char* appId);
60 virtual ~SAML2SessionInitiator() {
62 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
63 XMLString::release(&m_outgoing);
64 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
65 delete m_requestTemplate;
70 void setParent(const PropertySet* parent);
71 void receive(DDF& in, ostream& out);
72 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
75 pair<bool,long> doRequest(
76 const Application& application,
77 HTTPResponse& httpResponse,
79 const XMLCh* acsIndex,
80 const char* acsLocation,
81 const XMLCh* acsBinding,
84 const char* authnContextClassRef,
85 const char* authnContextComparison,
92 vector<const XMLCh*> m_bindings;
93 map<const XMLCh*,MessageEncoder*> m_encoders;
94 AuthnRequest* m_requestTemplate;
98 #if defined (_MSC_VER)
99 #pragma warning( pop )
102 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
104 return new SAML2SessionInitiator(p.first, p.second);
109 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
110 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId)
114 m_requestTemplate=NULL;
115 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
116 // Check for a template AuthnRequest to build from.
117 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
119 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
121 // Handle outgoing binding setup.
122 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
123 if (outgoing.first) {
124 m_outgoing = XMLString::replicate(outgoing.second);
125 XMLString::trim(m_outgoing);
128 // No override, so we'll install a default binding precedence.
129 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
130 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
131 m_outgoing = XMLString::transcode(prec.c_str());
135 XMLCh* start = m_outgoing;
136 while (start && *start) {
137 pos = XMLString::indexOf(start,chSpace);
139 *(start + pos)=chNull;
140 m_bindings.push_back(start);
142 auto_ptr_char b(start);
143 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
144 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
146 m_encoders[start] = encoder;
147 m_log.debug("supporting outgoing binding (%s)", b.get());
149 catch (exception& ex) {
150 m_log.error("error building MessageEncoder: %s", ex.what());
153 start = start + pos + 1;
160 // If Location isn't set, defer address registration until the setParent call.
161 pair<bool,const char*> loc = getString("Location");
163 string address = m_appId + loc.second + "::run::SAML2SI";
164 setAddress(address.c_str());
168 void SAML2SessionInitiator::setParent(const PropertySet* parent)
170 DOMPropertySet::setParent(parent);
171 pair<bool,const char*> loc = getString("Location");
173 string address = m_appId + loc.second + "::run::SAML2SI";
174 setAddress(address.c_str());
177 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
181 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
183 // We have to know the IdP to function.
184 if (!entityID || !*entityID)
185 return make_pair(false,0);
188 const Handler* ACS=NULL;
190 pair<bool,const char*> acClass;
191 pair<bool,const char*> acComp;
192 bool isPassive=false,forceAuthn=false;
193 const Application& app=request.getApplication();
194 pair<bool,bool> acsByIndex = getBool("acsByIndex");
197 option=request.getParameter("acsIndex");
199 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
201 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
204 option = request.getParameter("target");
207 if (acsByIndex.first && !acsByIndex.second) {
208 // Since we're passing the ACS by value, we need to compute the return URL,
209 // so we'll need the target resource for real.
210 recoverRelayState(request.getApplication(), request, target, false);
213 option = request.getParameter("isPassive");
214 isPassive = (option && (*option=='1' || *option=='t'));
216 option = request.getParameter("forceAuthn");
217 forceAuthn = (option && (*option=='1' || *option=='t'));
220 acClass.second = request.getParameter("authnContextClassRef");
221 acClass.first = (acClass.second!=NULL);
222 acComp.second = request.getParameter("authnContextComparison");
223 acComp.first = (acComp.second!=NULL);
226 // We're running as a "virtual handler" from within the filter.
227 // The target resource is the current one and everything else is defaulted.
228 target=request.getRequestURL();
229 const PropertySet* settings = request.getRequestSettings().first;
231 pair<bool,bool> flag = settings->getBool("isPassive");
232 isPassive = flag.first && flag.second;
234 flag = settings->getBool("forceAuthn");
235 forceAuthn = flag.first && flag.second;
238 acClass = settings->getString("authnContextClassRef");
239 acComp = settings->getString("authnContextComparison");
242 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
245 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
247 ACS = app.getAssertionConsumerServiceByIndex(index.second);
249 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
252 ACS = app.getDefaultAssertionConsumerService();
255 // To invoke the request builder, the key requirement is to figure out how
256 // to express the ACS, by index or value, and if by value, where.
258 SPConfig& conf = SPConfig::getConfig();
259 if (conf.isEnabled(SPConfig::OutOfProcess)) {
260 if (!acsByIndex.first || acsByIndex.second) {
263 // We may already have RelayState set if we looped back here,
264 // but just in case target is a resource, we reset it back.
266 option = request.getParameter("target");
271 app, request, entityID,
272 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
273 isPassive, forceAuthn,
274 acClass.first ? acClass.second : NULL,
275 acComp.first ? acComp.second : NULL,
280 // Since we're not passing by index, we need to fully compute the return URL and binding.
281 // Compute the ACS URL. We add the ACS location to the base handlerURL.
282 string ACSloc=request.getHandlerURL(target.c_str());
283 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
284 if (loc.first) ACSloc+=loc.second;
287 // We may already have RelayState set if we looped back here,
288 // but just in case target is a resource, we reset it back.
290 option = request.getParameter("target");
296 app, request, entityID,
297 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
298 isPassive, forceAuthn,
299 acClass.first ? acClass.second : NULL,
300 acComp.first ? acComp.second : NULL,
306 DDF out,in = DDF(m_address.c_str()).structure();
307 DDFJanitor jin(in), jout(out);
308 in.addmember("application_id").string(app.getId());
309 in.addmember("entity_id").string(entityID);
311 in.addmember("isPassive").integer(1);
313 in.addmember("forceAuthn").integer(1);
315 in.addmember("authnContextClassRef").string(acClass.second);
317 in.addmember("authnContextComparison").string(acComp.second);
318 if (!acsByIndex.first || acsByIndex.second) {
320 in.addmember("acsIndex").string(ACS->getString("index").second);
323 // Since we're not passing by index, we need to fully compute the return URL and binding.
324 // Compute the ACS URL. We add the ACS location to the base handlerURL.
325 string ACSloc=request.getHandlerURL(target.c_str());
326 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
327 if (loc.first) ACSloc+=loc.second;
328 in.addmember("acsLocation").string(ACSloc.c_str());
330 in.addmember("acsBinding").string(ACS->getString("Binding").second);
334 // We may already have RelayState set if we looped back here,
335 // but just in case target is a resource, we reset it back.
337 option = request.getParameter("target");
342 in.addmember("RelayState").string(target.c_str());
344 // Remote the processing.
345 out = request.getServiceProvider().getListenerService()->send(in);
346 return unwrap(request, out);
349 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
352 const char* aid=in["application_id"].string();
353 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
355 // Something's horribly wrong.
356 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
357 throw ConfigurationException("Unable to locate application for new session, deleted?");
360 const char* entityID = in["entity_id"].string();
362 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
365 DDFJanitor jout(ret);
367 // Wrap the outgoing object with a Response facade.
368 auto_ptr<HTTPResponse> http(getResponse(ret));
370 auto_ptr_XMLCh index(in["acsIndex"].string());
371 auto_ptr_XMLCh bind(in["acsBinding"].string());
373 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
375 // Since we're remoted, the result should either be a throw, which we pass on,
376 // a false/0 return, which we just return as an empty structure, or a response/redirect,
377 // which we capture in the facade and send back.
379 *app, *http.get(), entityID,
380 index.get(), in["acsLocation"].string(), bind.get(),
381 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
382 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
388 pair<bool,long> SAML2SessionInitiator::doRequest(
389 const Application& app,
390 HTTPResponse& httpResponse,
391 const char* entityID,
392 const XMLCh* acsIndex,
393 const char* acsLocation,
394 const XMLCh* acsBinding,
397 const char* authnContextClassRef,
398 const char* authnContextComparison,
403 // Use metadata to locate the IdP's SSO service.
404 MetadataProvider* m=app.getMetadataProvider();
406 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
408 m_log.error("unable to locate metadata for provider (%s)", entityID);
409 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
410 namedparams(1, "entityID", entityID));
412 const IDPSSODescriptor* role=find_if(entity->getIDPSSODescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
414 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
415 return make_pair(false,0);
418 // Loop over the supportable outgoing bindings.
419 const EndpointType* ep=NULL;
420 const MessageEncoder* encoder=NULL;
421 vector<const XMLCh*>::const_iterator b;
422 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
423 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
424 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
425 if (enc!=m_encoders.end())
426 encoder = enc->second;
430 if (!ep || !encoder) {
431 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
432 return make_pair(false,0);
435 preserveRelayState(app, httpResponse, relayState);
437 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
438 if (m_requestTemplate) {
439 // Freshen TS and ID.
441 req->setIssueInstant(time(NULL));
444 req->setDestination(ep->getLocation());
445 if (acsIndex && *acsIndex)
446 req->setAssertionConsumerServiceIndex(acsIndex);
448 auto_ptr_XMLCh wideloc(acsLocation);
449 req->setAssertionConsumerServiceURL(wideloc.get());
451 if (acsBinding && *acsBinding)
452 req->setProtocolBinding(acsBinding);
454 req->IsPassive(isPassive);
456 req->ForceAuthn(forceAuthn);
457 if (!req->getIssuer()) {
458 Issuer* issuer = IssuerBuilder::buildIssuer();
459 req->setIssuer(issuer);
460 issuer->setName(app.getXMLString("entityID").second);
462 if (!req->getNameIDPolicy()) {
463 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
464 req->setNameIDPolicy(namepol);
465 namepol->AllowCreate(true);
467 if (authnContextClassRef || authnContextComparison) {
468 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
470 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
471 req->setRequestedAuthnContext(reqContext);
473 if (authnContextClassRef) {
474 reqContext->getAuthnContextDeclRefs().clear();
475 auto_ptr_XMLCh wideclass(authnContextClassRef);
476 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
477 cref->setReference(wideclass.get());
478 reqContext->getAuthnContextClassRefs().push_back(cref);
480 if (authnContextComparison &&
481 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
482 auto_ptr_XMLCh widecomp(authnContextComparison);
483 reqContext->setComparison(widecomp.get());
487 auto_ptr_char dest(ep->getLocation());
489 long ret = sendMessage(
490 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role->WantAuthnRequestsSigned()
492 req.release(); // freed by encoder
493 return make_pair(true,ret);
495 return make_pair(false,0);