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/binding/MessageEncoder.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;
45 using namespace shibsp;
46 using namespace opensaml;
47 using namespace xmltooling;
48 using namespace log4cpp;
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, const char* entityID=NULL, 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,
94 vector<const XMLCh*> m_bindings;
95 map<const XMLCh*,MessageEncoder*> m_encoders;
96 AuthnRequest* m_requestTemplate;
100 #if defined (_MSC_VER)
101 #pragma warning( pop )
104 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
106 return new SAML2SessionInitiator(p.first, p.second);
111 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
112 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId)
116 m_requestTemplate=NULL;
117 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
118 // Check for a template AuthnRequest to build from.
119 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
121 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
123 // Handle outgoing binding setup.
124 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
125 if (outgoing.first) {
126 m_outgoing = XMLString::replicate(outgoing.second);
129 // No override, so we'll install a default binding precedence.
130 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
131 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
132 m_outgoing = XMLString::transcode(prec.c_str());
133 XMLString::trim(m_outgoing);
137 XMLCh* start = m_outgoing;
138 while (start && *start) {
139 pos = XMLString::indexOf(start,chSpace);
141 *(start + pos)=chNull;
142 m_bindings.push_back(start);
144 auto_ptr_char b(start);
145 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
146 m_encoders[start] = encoder;
147 m_log.info("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 throw ConfigurationException("AssertionConsumerService with index ($1) not found, check configuration.", params(1,option));
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);
244 // To invoke the request builder, the key requirement is to figure out how and whether
245 // to express the ACS, by index or value, and if by value, where.
247 SPConfig& conf = SPConfig::getConfig();
248 if (conf.isEnabled(SPConfig::OutOfProcess)) {
249 if (!acsByIndex.first || acsByIndex.second) {
250 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
252 // We may already have RelayState set if we looped back here,
253 // but just in case target is a resource, we reset it back.
255 option = request.getParameter("target");
260 app, request, entityID,
261 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
262 isPassive, forceAuthn,
263 acClass.first ? acClass.second : NULL,
264 acComp.first ? acComp.second : NULL,
269 // Since we're not passing by index, we need to fully compute the return URL and binding.
271 ACS = app.getDefaultAssertionConsumerService();
273 // Compute the ACS URL. We add the ACS location to the base handlerURL.
274 string ACSloc=request.getHandlerURL(target.c_str());
275 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
276 if (loc.first) ACSloc+=loc.second;
279 // We may already have RelayState set if we looped back here,
280 // but just in case target is a resource, we reset it back.
282 option = request.getParameter("target");
288 app, request, entityID,
289 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
290 isPassive, forceAuthn,
291 acClass.first ? acClass.second : NULL,
292 acComp.first ? acComp.second : NULL,
298 DDF out,in = DDF(m_address.c_str()).structure();
299 DDFJanitor jin(in), jout(out);
300 in.addmember("application_id").string(app.getId());
301 in.addmember("entity_id").string(entityID);
303 in.addmember("isPassive").integer(1);
305 in.addmember("forceAuthn").integer(1);
307 in.addmember("authnContextClassRef").string(acClass.second);
309 in.addmember("authnContextComparison").string(acComp.second);
310 if (!acsByIndex.first || acsByIndex.second) {
312 in.addmember("acsIndex").string(ACS->getString("index").second);
315 // Since we're not passing by index, we need to fully compute the return URL and binding.
317 ACS = app.getDefaultAssertionConsumerService();
319 // Compute the ACS URL. We add the ACS location to the base handlerURL.
320 string ACSloc=request.getHandlerURL(target.c_str());
321 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
322 if (loc.first) ACSloc+=loc.second;
323 in.addmember("acsLocation").string(ACSloc.c_str());
325 in.addmember("acsBinding").string(ACS->getString("Binding").second);
329 // We may already have RelayState set if we looped back here,
330 // but just in case target is a resource, we reset it back.
332 option = request.getParameter("target");
337 in.addmember("RelayState").string(target.c_str());
339 // Remote the processing.
340 out = request.getServiceProvider().getListenerService()->send(in);
341 return unwrap(request, out);
344 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
347 const char* aid=in["application_id"].string();
348 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
350 // Something's horribly wrong.
351 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
352 throw ConfigurationException("Unable to locate application for new session, deleted?");
355 const char* entityID = in["entity_id"].string();
357 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
360 DDFJanitor jout(ret);
362 // Wrap the outgoing object with a Response facade.
363 auto_ptr<HTTPResponse> http(getResponse(ret));
365 auto_ptr_XMLCh index(in["acsIndex"].string());
366 auto_ptr_XMLCh bind(in["acsBinding"].string());
368 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
370 // Since we're remoted, the result should either be a throw, which we pass on,
371 // a false/0 return, which we just return as an empty structure, or a response/redirect,
372 // which we capture in the facade and send back.
374 *app, *http.get(), entityID,
375 index.get(), in["acsLocation"].string(), bind.get(),
376 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
377 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
383 pair<bool,long> SAML2SessionInitiator::doRequest(
384 const Application& app,
385 HTTPResponse& httpResponse,
386 const char* entityID,
387 const XMLCh* acsIndex,
388 const char* acsLocation,
389 const XMLCh* acsBinding,
392 const char* authnContextClassRef,
393 const char* authnContextComparison,
398 // Use metadata to locate the IdP's SSO service.
399 MetadataProvider* m=app.getMetadataProvider();
401 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
403 m_log.error("unable to locate metadata for provider (%s)", entityID);
404 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
405 namedparams(1, "entityID", entityID));
407 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
409 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
410 return make_pair(false,0);
413 // Loop over the supportable outgoing bindings.
414 const EndpointType* ep=NULL;
415 const MessageEncoder* encoder=NULL;
416 vector<const XMLCh*>::const_iterator b;
417 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
418 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
419 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
420 if (enc!=m_encoders.end())
421 encoder = enc->second;
425 if (!ep || !encoder) {
426 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
427 return make_pair(false,0);
430 preserveRelayState(app, httpResponse, relayState);
432 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
433 if (m_requestTemplate) {
434 // Freshen TS and ID.
436 req->setIssueInstant(time(NULL));
439 req->setDestination(ep->getLocation());
440 if (acsIndex && *acsIndex)
441 req->setAssertionConsumerServiceIndex(acsIndex);
443 auto_ptr_XMLCh wideloc(acsLocation);
444 req->setAssertionConsumerServiceURL(wideloc.get());
446 if (acsBinding && *acsBinding)
447 req->setProtocolBinding(acsBinding);
449 req->IsPassive(isPassive);
451 req->ForceAuthn(forceAuthn);
452 if (!req->getIssuer()) {
453 Issuer* issuer = IssuerBuilder::buildIssuer();
454 req->setIssuer(issuer);
455 issuer->setName(app.getXMLString("entityID").second);
457 if (!req->getNameIDPolicy()) {
458 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
459 req->setNameIDPolicy(namepol);
460 namepol->AllowCreate(true);
462 if (authnContextClassRef || authnContextComparison) {
463 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
465 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
466 req->setRequestedAuthnContext(reqContext);
468 if (authnContextClassRef) {
469 reqContext->getAuthnContextDeclRefs().clear();
470 auto_ptr_XMLCh wideclass(authnContextClassRef);
471 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
472 cref->setReference(wideclass.get());
473 reqContext->getAuthnContextClassRefs().push_back(cref);
475 if (authnContextComparison &&
476 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
477 auto_ptr_XMLCh widecomp(authnContextComparison);
478 reqContext->setComparison(widecomp.get());
482 auto_ptr_char dest(ep->getLocation());
484 // Check for signing.
485 const PropertySet* relyingParty = app.getRelyingParty(entity);
486 pair<bool,bool> flag = relyingParty->getBool("signRequests");
487 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
488 CredentialResolver* credResolver=app.getCredentialResolver();
490 Locker credLocker(credResolver);
491 // Fill in criteria to use.
492 MetadataCredentialCriteria mcc(*role);
493 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
494 pair<bool,const char*> keyName = relyingParty->getString("keyName");
496 mcc.getKeyNames().insert(keyName.second);
497 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
499 mcc.setXMLAlgorithm(sigalg.second);
500 const Credential* cred = credResolver->resolve(&mcc);
503 long ret = encoder->encode(
511 relyingParty->getXMLString("digestAlg").second
513 req.release(); // freed by encoder
514 return make_pair(true,ret);
517 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
523 long ret = encoder->encode(httpResponse, req.get(), dest.get(), entity, relayState.c_str());
524 req.release(); // freed by encoder
525 return make_pair(true,ret);
527 return make_pair(false,0);