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 throw ConfigurationException("AssertionConsumerService with index ($1) not found, check configuration.", params(1,option));
194 option = request.getParameter("target");
197 if (acsByIndex.first && !acsByIndex.second) {
198 // Since we're passing the ACS by value, we need to compute the return URL,
199 // so we'll need the target resource for real.
200 recoverRelayState(request.getApplication(), request, target, false);
203 option = request.getParameter("isPassive");
204 isPassive = (option && (*option=='1' || *option=='t'));
206 option = request.getParameter("forceAuthn");
207 forceAuthn = (option && (*option=='1' || *option=='t'));
210 acClass.second = request.getParameter("authnContextClassRef");
211 acClass.first = (acClass.second!=NULL);
212 acComp.second = request.getParameter("authnContextComparison");
213 acComp.first = (acComp.second!=NULL);
216 // We're running as a "virtual handler" from within the filter.
217 // The target resource is the current one and everything else is defaulted.
218 target=request.getRequestURL();
219 const PropertySet* settings = request.getRequestSettings().first;
221 pair<bool,bool> flag = settings->getBool("isPassive");
222 isPassive = flag.first && flag.second;
224 flag = settings->getBool("forceAuthn");
225 forceAuthn = flag.first && flag.second;
228 acClass = settings->getString("authnContextClassRef");
229 acComp = settings->getString("authnContextComparison");
232 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
234 // To invoke the request builder, the key requirement is to figure out how and whether
235 // to express the ACS, by index or value, and if by value, where.
237 SPConfig& conf = SPConfig::getConfig();
238 if (conf.isEnabled(SPConfig::OutOfProcess)) {
239 if (!acsByIndex.first || acsByIndex.second) {
240 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
242 // We may already have RelayState set if we looped back here,
243 // but just in case target is a resource, we reset it back.
245 option = request.getParameter("target");
250 app, request, entityID,
251 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
252 isPassive, forceAuthn,
253 acClass.first ? acClass.second : NULL,
254 acComp.first ? acComp.second : NULL,
259 // Since we're not passing by index, we need to fully compute the return URL and binding.
261 ACS = app.getDefaultAssertionConsumerService();
263 // Compute the ACS URL. We add the ACS location to the base handlerURL.
264 string ACSloc=request.getHandlerURL(target.c_str());
265 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
266 if (loc.first) ACSloc+=loc.second;
269 // We may already have RelayState set if we looped back here,
270 // but just in case target is a resource, we reset it back.
272 option = request.getParameter("target");
278 app, request, entityID,
279 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
280 isPassive, forceAuthn,
281 acClass.first ? acClass.second : NULL,
282 acComp.first ? acComp.second : NULL,
288 DDF out,in = DDF(m_address.c_str()).structure();
289 DDFJanitor jin(in), jout(out);
290 in.addmember("application_id").string(app.getId());
291 in.addmember("entity_id").string(entityID);
293 in.addmember("isPassive").integer(1);
295 in.addmember("forceAuthn").integer(1);
297 in.addmember("authnContextClassRef").string(acClass.second);
299 in.addmember("authnContextComparison").string(acComp.second);
300 if (!acsByIndex.first || acsByIndex.second) {
302 in.addmember("acsIndex").string(ACS->getString("index").second);
305 // Since we're not passing by index, we need to fully compute the return URL and binding.
307 ACS = app.getDefaultAssertionConsumerService();
309 // Compute the ACS URL. We add the ACS location to the base handlerURL.
310 string ACSloc=request.getHandlerURL(target.c_str());
311 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
312 if (loc.first) ACSloc+=loc.second;
313 in.addmember("acsLocation").string(ACSloc.c_str());
315 in.addmember("acsBinding").string(ACS->getString("Binding").second);
319 // We may already have RelayState set if we looped back here,
320 // but just in case target is a resource, we reset it back.
322 option = request.getParameter("target");
327 in.addmember("RelayState").string(target.c_str());
329 // Remote the processing.
330 out = request.getServiceProvider().getListenerService()->send(in);
331 return unwrap(request, out);
334 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
337 const char* aid=in["application_id"].string();
338 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
340 // Something's horribly wrong.
341 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
342 throw ConfigurationException("Unable to locate application for new session, deleted?");
345 const char* entityID = in["entity_id"].string();
347 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
350 DDFJanitor jout(ret);
352 // Wrap the outgoing object with a Response facade.
353 auto_ptr<HTTPResponse> http(getResponse(ret));
355 auto_ptr_XMLCh index(in["acsIndex"].string());
356 auto_ptr_XMLCh bind(in["acsBinding"].string());
358 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
360 // Since we're remoted, the result should either be a throw, which we pass on,
361 // a false/0 return, which we just return as an empty structure, or a response/redirect,
362 // which we capture in the facade and send back.
364 *app, *http.get(), entityID,
365 index.get(), in["acsLocation"].string(), bind.get(),
366 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
367 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
373 pair<bool,long> SAML2SessionInitiator::doRequest(
374 const Application& app,
375 HTTPResponse& httpResponse,
376 const char* entityID,
377 const XMLCh* acsIndex,
378 const char* acsLocation,
379 const XMLCh* acsBinding,
382 const char* authnContextClassRef,
383 const char* authnContextComparison,
387 // Use metadata to locate the IdP's SSO service.
388 MetadataProvider* m=app.getMetadataProvider();
390 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
392 m_log.error("unable to locate metadata for provider (%s)", entityID);
393 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
394 namedparams(1, "entityID", entityID));
396 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
398 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
399 return make_pair(false,0);
402 // Loop over the supportable outgoing bindings.
403 const EndpointType* ep=NULL;
404 const MessageEncoder* encoder=NULL;
405 vector<const XMLCh*>::const_iterator b;
406 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
407 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
408 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
409 if (enc!=m_encoders.end())
410 encoder = enc->second;
414 if (!ep || !encoder) {
415 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
416 return make_pair(false,0);
419 preserveRelayState(app, httpResponse, relayState);
421 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
422 if (m_requestTemplate) {
423 // Freshen TS and ID.
425 req->setIssueInstant(time(NULL));
428 req->setDestination(ep->getLocation());
429 if (acsIndex && *acsIndex)
430 req->setAssertionConsumerServiceIndex(acsIndex);
432 auto_ptr_XMLCh wideloc(acsLocation);
433 req->setAssertionConsumerServiceURL(wideloc.get());
435 if (acsBinding && *acsBinding)
436 req->setProtocolBinding(acsBinding);
438 req->IsPassive(isPassive);
440 req->ForceAuthn(forceAuthn);
441 if (!req->getIssuer()) {
442 Issuer* issuer = IssuerBuilder::buildIssuer();
443 req->setIssuer(issuer);
444 issuer->setName(app.getXMLString("entityID").second);
446 if (!req->getNameIDPolicy()) {
447 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
448 req->setNameIDPolicy(namepol);
449 namepol->AllowCreate(true);
451 if (authnContextClassRef || authnContextComparison) {
452 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
454 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
455 req->setRequestedAuthnContext(reqContext);
457 if (authnContextClassRef) {
458 reqContext->getAuthnContextDeclRefs().clear();
459 auto_ptr_XMLCh wideclass(authnContextClassRef);
460 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
461 cref->setReference(wideclass.get());
462 reqContext->getAuthnContextClassRefs().push_back(cref);
464 if (authnContextComparison &&
465 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
466 auto_ptr_XMLCh widecomp(authnContextComparison);
467 reqContext->setComparison(widecomp.get());
471 auto_ptr_char dest(ep->getLocation());
473 // Check for signing.
474 const PropertySet* relyingParty = app.getRelyingParty(entity);
475 pair<bool,bool> flag = relyingParty->getBool("signRequests");
476 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
477 CredentialResolver* credResolver=app.getCredentialResolver();
479 Locker credLocker(credResolver);
480 // Fill in criteria to use.
481 MetadataCredentialCriteria mcc(*role);
482 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
483 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
485 mcc.setXMLAlgorithm(sigalg.second);
486 const Credential* cred = credResolver->resolve(&mcc);
489 long ret = encoder->encode(
497 relyingParty->getXMLString("digestAlg").second
499 req.release(); // freed by encoder
500 return make_pair(true,ret);
503 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
509 long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
510 req.release(); // freed by encoder
511 return make_pair(true,ret);