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"
33 #include <saml/SAMLConfig.h>
34 #include <saml/binding/MessageEncoder.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>
40 using namespace shibsp;
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
45 using namespace xmltooling;
46 using namespace log4cpp;
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() {
61 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
62 XMLString::release(&m_outgoing);
63 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
64 delete m_requestTemplate;
68 void setParent(const PropertySet* parent);
69 void receive(DDF& in, ostream& out);
70 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
73 pair<bool,long> doRequest(
74 const Application& application,
75 HTTPResponse& httpResponse,
77 const XMLCh* acsIndex,
78 const char* acsLocation,
79 const XMLCh* acsBinding,
82 const char* authnContextClassRef,
83 const char* authnContextComparison,
89 vector<const XMLCh*> m_bindings;
90 map<const XMLCh*,MessageEncoder*> m_encoders;
91 AuthnRequest* m_requestTemplate;
94 #if defined (_MSC_VER)
95 #pragma warning( pop )
98 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
100 return new SAML2SessionInitiator(p.first, p.second);
105 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
106 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_outgoing(NULL), m_requestTemplate(NULL)
108 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
109 // Check for a template AuthnRequest to build from.
110 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
112 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
114 // Handle outgoing binding setup.
115 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
116 if (outgoing.first) {
117 m_outgoing = XMLString::replicate(outgoing.second);
120 // No override, so we'll install a default binding precedence.
121 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
122 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
123 m_outgoing = XMLString::transcode(prec.c_str());
124 XMLString::trim(m_outgoing);
128 XMLCh* start = m_outgoing;
129 while (start && *start) {
130 pos = XMLString::indexOf(start,chSpace);
132 *(start + pos)=chNull;
133 m_bindings.push_back(start);
135 auto_ptr_char b(start);
136 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
137 m_encoders[start] = encoder;
138 m_log.info("supporting outgoing binding (%s)", b.get());
140 catch (exception& ex) {
141 m_log.error("error building MessageEncoder: %s", ex.what());
144 start = start + pos + 1;
150 // If Location isn't set, defer address registration until the setParent call.
151 pair<bool,const char*> loc = getString("Location");
153 string address = m_appId + loc.second + "::run::SAML2SI";
154 setAddress(address.c_str());
158 void SAML2SessionInitiator::setParent(const PropertySet* parent)
160 DOMPropertySet::setParent(parent);
161 pair<bool,const char*> loc = getString("Location");
163 string address = m_appId + loc.second + "::run::SAML2SI";
164 setAddress(address.c_str());
167 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
171 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
173 // We have to know the IdP to function.
174 if (!entityID || !*entityID)
175 return make_pair(false,0);
178 const Handler* ACS=NULL;
180 pair<bool,const char*> acClass;
181 pair<bool,const char*> acComp;
182 bool isPassive=false,forceAuthn=false;
183 const Application& app=request.getApplication();
184 pair<bool,bool> acsByIndex = getBool("acsByIndex");
187 option=request.getParameter("acsIndex");
189 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
191 option = request.getParameter("target");
194 if (!acsByIndex.first || !acsByIndex.second) {
195 // Since we're passing the ACS by value, we need to compute the return URL,
196 // so we'll need the target resource for real.
197 recoverRelayState(request.getApplication(), request, target, false);
200 option = request.getParameter("isPassive");
201 isPassive = (option && (*option=='1' || *option=='t'));
203 option = request.getParameter("forceAuthn");
204 forceAuthn = (option && (*option=='1' || *option=='t'));
207 acClass.second = request.getParameter("authnContextClassRef");
208 acClass.first = (acClass.second!=NULL);
209 acComp.second = request.getParameter("authnContextComparison");
210 acComp.first = (acComp.second!=NULL);
213 // We're running as a "virtual handler" from within the filter.
214 // The target resource is the current one and everything else is defaulted.
215 target=request.getRequestURL();
216 const PropertySet* settings = request.getRequestSettings().first;
218 pair<bool,bool> flag = settings->getBool("isPassive");
219 isPassive = flag.first && flag.second;
221 flag = settings->getBool("forceAuthn");
222 forceAuthn = flag.first && flag.second;
225 acClass = settings->getString("authnContextClassRef");
226 acComp = settings->getString("authnContextComparison");
229 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
231 // To invoke the request builder, the key requirement is to figure out how and whether
232 // to express the ACS, by index or value, and if by value, where.
234 SPConfig& conf = SPConfig::getConfig();
235 if (conf.isEnabled(SPConfig::OutOfProcess)) {
236 if (acsByIndex.first && acsByIndex.second) {
237 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
239 // We may already have RelayState set if we looped back here,
240 // but just in case target is a resource, we reset it back.
242 option = request.getParameter("target");
247 app, request, entityID,
248 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
249 isPassive, forceAuthn,
250 acClass.first ? acClass.second : NULL,
251 acComp.first ? acComp.second : NULL,
256 // Since we're not passing by index, we need to fully compute the return URL and binding.
258 ACS = app.getDefaultAssertionConsumerService();
260 // Compute the ACS URL. We add the ACS location to the base handlerURL.
261 string ACSloc=request.getHandlerURL(target.c_str());
262 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
263 if (loc.first) ACSloc+=loc.second;
266 // We may already have RelayState set if we looped back here,
267 // but just in case target is a resource, we reset it back.
269 option = request.getParameter("target");
275 app, request, entityID,
276 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
277 isPassive, forceAuthn,
278 acClass.first ? acClass.second : NULL,
279 acComp.first ? acComp.second : NULL,
285 DDF out,in = DDF(m_address.c_str()).structure();
286 DDFJanitor jin(in), jout(out);
287 in.addmember("application_id").string(app.getId());
288 in.addmember("entity_id").string(entityID);
290 in.addmember("isPassive").integer(1);
292 in.addmember("forceAuthn").integer(1);
294 in.addmember("authnContextClassRef").string(acClass.second);
296 in.addmember("authnContextComparison").string(acComp.second);
297 if (acsByIndex.first && acsByIndex.second) {
299 in.addmember("acsIndex").string(ACS->getString("index").second);
302 // Since we're not passing by index, we need to fully compute the return URL and binding.
304 ACS = app.getDefaultAssertionConsumerService();
306 // Compute the ACS URL. We add the ACS location to the base handlerURL.
307 string ACSloc=request.getHandlerURL(target.c_str());
308 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
309 if (loc.first) ACSloc+=loc.second;
310 in.addmember("acsLocation").string(ACSloc.c_str());
312 in.addmember("acsBinding").string(ACS->getString("Binding").second);
316 // We may already have RelayState set if we looped back here,
317 // but just in case target is a resource, we reset it back.
319 option = request.getParameter("target");
324 in.addmember("RelayState").string(target.c_str());
326 // Remote the processing.
327 out = request.getServiceProvider().getListenerService()->send(in);
328 return unwrap(request, out);
331 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
334 const char* aid=in["application_id"].string();
335 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
337 // Something's horribly wrong.
338 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
339 throw ConfigurationException("Unable to locate application for new session, deleted?");
342 const char* entityID = in["entity_id"].string();
344 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
347 DDFJanitor jout(ret);
349 // Wrap the outgoing object with a Response facade.
350 auto_ptr<HTTPResponse> http(getResponse(ret));
352 auto_ptr_XMLCh index(in["acsIndex"].string());
353 auto_ptr_XMLCh bind(in["acsBinding"].string());
355 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
357 // Since we're remoted, the result should either be a throw, which we pass on,
358 // a false/0 return, which we just return as an empty structure, or a response/redirect,
359 // which we capture in the facade and send back.
361 *app, *http.get(), entityID,
362 index.get(), in["acsLocation"].string(), bind.get(),
363 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
364 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
370 pair<bool,long> SAML2SessionInitiator::doRequest(
371 const Application& app,
372 HTTPResponse& httpResponse,
373 const char* entityID,
374 const XMLCh* acsIndex,
375 const char* acsLocation,
376 const XMLCh* acsBinding,
379 const char* authnContextClassRef,
380 const char* authnContextComparison,
384 // Use metadata to locate the IdP's SSO service.
385 MetadataProvider* m=app.getMetadataProvider();
387 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
389 m_log.error("unable to locate metadata for provider (%s)", entityID);
390 return make_pair(false,0);
392 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
394 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
395 return make_pair(false,0);
398 // Loop over the supportable outgoing bindings.
399 const EndpointType* ep=NULL;
400 const MessageEncoder* encoder=NULL;
401 vector<const XMLCh*>::const_iterator b;
402 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
403 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
404 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
405 if (enc!=m_encoders.end())
406 encoder = enc->second;
410 if (!ep || !encoder) {
411 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
412 return make_pair(false,0);
415 preserveRelayState(app, httpResponse, relayState);
417 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
418 if (m_requestTemplate) {
419 // Freshen TS and ID.
421 req->setIssueInstant(time(NULL));
424 req->setDestination(ep->getLocation());
426 req->setAssertionConsumerServiceIndex(acsIndex);
428 auto_ptr_XMLCh wideloc(acsLocation);
429 req->setAssertionConsumerServiceURL(wideloc.get());
432 req->setProtocolBinding(acsBinding);
434 req->IsPassive(isPassive);
436 req->ForceAuthn(forceAuthn);
437 if (!req->getIssuer()) {
438 Issuer* issuer = IssuerBuilder::buildIssuer();
439 req->setIssuer(issuer);
440 issuer->setName(app.getXMLString("providerId").second);
442 if (!req->getNameIDPolicy()) {
443 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
444 req->setNameIDPolicy(namepol);
445 namepol->AllowCreate(true);
447 if (authnContextClassRef || authnContextComparison) {
448 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
450 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
451 req->setRequestedAuthnContext(reqContext);
453 if (authnContextClassRef) {
454 reqContext->getAuthnContextDeclRefs().clear();
455 auto_ptr_XMLCh wideclass(authnContextClassRef);
456 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
457 cref->setReference(wideclass.get());
458 reqContext->getAuthnContextClassRefs().push_back(cref);
460 if (authnContextComparison &&
461 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
462 auto_ptr_XMLCh widecomp(authnContextComparison);
463 reqContext->setComparison(widecomp.get());
467 auto_ptr_char dest(ep->getLocation());
469 // Check for signing.
470 const PropertySet* relyingParty = app.getRelyingParty(entity);
471 pair<bool,bool> flag = relyingParty->getBool("signRequests");
472 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
473 CredentialResolver* credResolver=app.getCredentialResolver();
475 Locker credLocker(credResolver);
476 // Fill in criteria to use.
477 MetadataCredentialCriteria mcc(*role);
478 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
479 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
481 mcc.setXMLAlgorithm(sigalg.second);
482 const Credential* cred = credResolver->resolve(&mcc);
485 long ret = encoder->encode(
493 relyingParty->getXMLString("digestAlg").second
495 req.release(); // freed by encoder
496 return make_pair(true,ret);
499 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
505 long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
506 req.release(); // freed by encoder
507 return make_pair(true,ret);