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;
47 using namespace log4cpp;
52 #if defined (_MSC_VER)
53 #pragma warning( push )
54 #pragma warning( disable : 4250 )
57 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
60 SAML2SessionInitiator(const DOMElement* e, const char* appId);
61 virtual ~SAML2SessionInitiator() {
63 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
64 XMLString::release(&m_outgoing);
65 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
66 delete m_requestTemplate;
71 void setParent(const PropertySet* parent);
72 void receive(DDF& in, ostream& out);
73 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
76 pair<bool,long> doRequest(
77 const Application& application,
78 HTTPResponse& httpResponse,
80 const XMLCh* acsIndex,
81 const char* acsLocation,
82 const XMLCh* acsBinding,
85 const char* authnContextClassRef,
86 const char* authnContextComparison,
93 vector<const XMLCh*> m_bindings;
94 map<const XMLCh*,MessageEncoder*> m_encoders;
95 AuthnRequest* m_requestTemplate;
99 #if defined (_MSC_VER)
100 #pragma warning( pop )
103 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
105 return new SAML2SessionInitiator(p.first, p.second);
110 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
111 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId)
115 m_requestTemplate=NULL;
116 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
117 // Check for a template AuthnRequest to build from.
118 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
120 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
122 // Handle outgoing binding setup.
123 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
124 if (outgoing.first) {
125 m_outgoing = XMLString::replicate(outgoing.second);
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());
132 XMLString::trim(m_outgoing);
136 XMLCh* start = m_outgoing;
137 while (start && *start) {
138 pos = XMLString::indexOf(start,chSpace);
140 *(start + pos)=chNull;
141 m_bindings.push_back(start);
143 auto_ptr_char b(start);
144 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
145 m_encoders[start] = encoder;
146 m_log.debug("supporting outgoing binding (%s)", b.get());
148 catch (exception& ex) {
149 m_log.error("error building MessageEncoder: %s", ex.what());
152 start = start + pos + 1;
159 // If Location isn't set, defer address registration until the setParent call.
160 pair<bool,const char*> loc = getString("Location");
162 string address = m_appId + loc.second + "::run::SAML2SI";
163 setAddress(address.c_str());
167 void SAML2SessionInitiator::setParent(const PropertySet* parent)
169 DOMPropertySet::setParent(parent);
170 pair<bool,const char*> loc = getString("Location");
172 string address = m_appId + loc.second + "::run::SAML2SI";
173 setAddress(address.c_str());
176 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
180 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
182 // We have to know the IdP to function.
183 if (!entityID || !*entityID)
184 return make_pair(false,0);
187 const Handler* ACS=NULL;
189 pair<bool,const char*> acClass;
190 pair<bool,const char*> acComp;
191 bool isPassive=false,forceAuthn=false;
192 const Application& app=request.getApplication();
193 pair<bool,bool> acsByIndex = getBool("acsByIndex");
196 option=request.getParameter("acsIndex");
198 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
200 throw ConfigurationException("AssertionConsumerService with index ($1) not found, check configuration.", params(1,option));
203 option = request.getParameter("target");
206 if (acsByIndex.first && !acsByIndex.second) {
207 // Since we're passing the ACS by value, we need to compute the return URL,
208 // so we'll need the target resource for real.
209 recoverRelayState(request.getApplication(), request, target, false);
212 option = request.getParameter("isPassive");
213 isPassive = (option && (*option=='1' || *option=='t'));
215 option = request.getParameter("forceAuthn");
216 forceAuthn = (option && (*option=='1' || *option=='t'));
219 acClass.second = request.getParameter("authnContextClassRef");
220 acClass.first = (acClass.second!=NULL);
221 acComp.second = request.getParameter("authnContextComparison");
222 acComp.first = (acComp.second!=NULL);
225 // We're running as a "virtual handler" from within the filter.
226 // The target resource is the current one and everything else is defaulted.
227 target=request.getRequestURL();
228 const PropertySet* settings = request.getRequestSettings().first;
230 pair<bool,bool> flag = settings->getBool("isPassive");
231 isPassive = flag.first && flag.second;
233 flag = settings->getBool("forceAuthn");
234 forceAuthn = flag.first && flag.second;
237 acClass = settings->getString("authnContextClassRef");
238 acComp = settings->getString("authnContextComparison");
241 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
243 // To invoke the request builder, the key requirement is to figure out how and whether
244 // to express the ACS, by index or value, and if by value, where.
246 SPConfig& conf = SPConfig::getConfig();
247 if (conf.isEnabled(SPConfig::OutOfProcess)) {
248 if (!acsByIndex.first || acsByIndex.second) {
249 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
251 // We may already have RelayState set if we looped back here,
252 // but just in case target is a resource, we reset it back.
254 option = request.getParameter("target");
259 app, request, entityID,
260 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
261 isPassive, forceAuthn,
262 acClass.first ? acClass.second : NULL,
263 acComp.first ? acComp.second : NULL,
268 // Since we're not passing by index, we need to fully compute the return URL and binding.
270 ACS = app.getDefaultAssertionConsumerService();
272 // Compute the ACS URL. We add the ACS location to the base handlerURL.
273 string ACSloc=request.getHandlerURL(target.c_str());
274 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
275 if (loc.first) ACSloc+=loc.second;
278 // We may already have RelayState set if we looped back here,
279 // but just in case target is a resource, we reset it back.
281 option = request.getParameter("target");
287 app, request, entityID,
288 NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
289 isPassive, forceAuthn,
290 acClass.first ? acClass.second : NULL,
291 acComp.first ? acComp.second : NULL,
297 DDF out,in = DDF(m_address.c_str()).structure();
298 DDFJanitor jin(in), jout(out);
299 in.addmember("application_id").string(app.getId());
300 in.addmember("entity_id").string(entityID);
302 in.addmember("isPassive").integer(1);
304 in.addmember("forceAuthn").integer(1);
306 in.addmember("authnContextClassRef").string(acClass.second);
308 in.addmember("authnContextComparison").string(acComp.second);
309 if (!acsByIndex.first || acsByIndex.second) {
311 in.addmember("acsIndex").string(ACS->getString("index").second);
314 // Since we're not passing by index, we need to fully compute the return URL and binding.
316 ACS = app.getDefaultAssertionConsumerService();
318 // Compute the ACS URL. We add the ACS location to the base handlerURL.
319 string ACSloc=request.getHandlerURL(target.c_str());
320 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
321 if (loc.first) ACSloc+=loc.second;
322 in.addmember("acsLocation").string(ACSloc.c_str());
324 in.addmember("acsBinding").string(ACS->getString("Binding").second);
328 // We may already have RelayState set if we looped back here,
329 // but just in case target is a resource, we reset it back.
331 option = request.getParameter("target");
336 in.addmember("RelayState").string(target.c_str());
338 // Remote the processing.
339 out = request.getServiceProvider().getListenerService()->send(in);
340 return unwrap(request, out);
343 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
346 const char* aid=in["application_id"].string();
347 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
349 // Something's horribly wrong.
350 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
351 throw ConfigurationException("Unable to locate application for new session, deleted?");
354 const char* entityID = in["entity_id"].string();
356 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
359 DDFJanitor jout(ret);
361 // Wrap the outgoing object with a Response facade.
362 auto_ptr<HTTPResponse> http(getResponse(ret));
364 auto_ptr_XMLCh index(in["acsIndex"].string());
365 auto_ptr_XMLCh bind(in["acsBinding"].string());
367 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
369 // Since we're remoted, the result should either be a throw, which we pass on,
370 // a false/0 return, which we just return as an empty structure, or a response/redirect,
371 // which we capture in the facade and send back.
373 *app, *http.get(), entityID,
374 index.get(), in["acsLocation"].string(), bind.get(),
375 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
376 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
382 pair<bool,long> SAML2SessionInitiator::doRequest(
383 const Application& app,
384 HTTPResponse& httpResponse,
385 const char* entityID,
386 const XMLCh* acsIndex,
387 const char* acsLocation,
388 const XMLCh* acsBinding,
391 const char* authnContextClassRef,
392 const char* authnContextComparison,
397 // Use metadata to locate the IdP's SSO service.
398 MetadataProvider* m=app.getMetadataProvider();
400 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
402 m_log.error("unable to locate metadata for provider (%s)", entityID);
403 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
404 namedparams(1, "entityID", entityID));
406 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
408 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
409 return make_pair(false,0);
412 // Loop over the supportable outgoing bindings.
413 const EndpointType* ep=NULL;
414 const MessageEncoder* encoder=NULL;
415 vector<const XMLCh*>::const_iterator b;
416 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
417 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
418 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
419 if (enc!=m_encoders.end())
420 encoder = enc->second;
424 if (!ep || !encoder) {
425 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
426 return make_pair(false,0);
429 preserveRelayState(app, httpResponse, relayState);
431 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
432 if (m_requestTemplate) {
433 // Freshen TS and ID.
435 req->setIssueInstant(time(NULL));
438 req->setDestination(ep->getLocation());
439 if (acsIndex && *acsIndex)
440 req->setAssertionConsumerServiceIndex(acsIndex);
442 auto_ptr_XMLCh wideloc(acsLocation);
443 req->setAssertionConsumerServiceURL(wideloc.get());
445 if (acsBinding && *acsBinding)
446 req->setProtocolBinding(acsBinding);
448 req->IsPassive(isPassive);
450 req->ForceAuthn(forceAuthn);
451 if (!req->getIssuer()) {
452 Issuer* issuer = IssuerBuilder::buildIssuer();
453 req->setIssuer(issuer);
454 issuer->setName(app.getXMLString("entityID").second);
456 if (!req->getNameIDPolicy()) {
457 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
458 req->setNameIDPolicy(namepol);
459 namepol->AllowCreate(true);
461 if (authnContextClassRef || authnContextComparison) {
462 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
464 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
465 req->setRequestedAuthnContext(reqContext);
467 if (authnContextClassRef) {
468 reqContext->getAuthnContextDeclRefs().clear();
469 auto_ptr_XMLCh wideclass(authnContextClassRef);
470 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
471 cref->setReference(wideclass.get());
472 reqContext->getAuthnContextClassRefs().push_back(cref);
474 if (authnContextComparison &&
475 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
476 auto_ptr_XMLCh widecomp(authnContextComparison);
477 reqContext->setComparison(widecomp.get());
481 auto_ptr_char dest(ep->getLocation());
483 // Check for signing.
484 const PropertySet* relyingParty = app.getRelyingParty(entity);
485 pair<bool,bool> flag = relyingParty->getBool("signRequests");
486 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
487 CredentialResolver* credResolver=app.getCredentialResolver();
489 Locker credLocker(credResolver);
490 // Fill in criteria to use.
491 MetadataCredentialCriteria mcc(*role);
492 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
493 pair<bool,const char*> keyName = relyingParty->getString("keyName");
495 mcc.getKeyNames().insert(keyName.second);
496 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
498 mcc.setXMLAlgorithm(sigalg.second);
499 const Credential* cred = credResolver->resolve(&mcc);
502 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(), &app);
524 req.release(); // freed by encoder
525 return make_pair(true,ret);
527 return make_pair(false,0);