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>());
67 void setParent(const PropertySet* parent);
68 void receive(DDF& in, ostream& out);
69 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
72 pair<bool,long> doRequest(
73 const Application& application,
74 HTTPResponse& httpResponse,
76 const XMLCh* acsIndex,
77 const char* acsLocation,
78 const XMLCh* acsBinding,
86 vector<const XMLCh*> m_bindings;
87 map<const XMLCh*,MessageEncoder*> m_encoders;
90 #if defined (_MSC_VER)
91 #pragma warning( pop )
94 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
96 return new SAML2SessionInitiator(p.first, p.second);
101 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
102 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_outgoing(NULL)
104 // If Location isn't set, defer address registration until the setParent call.
105 pair<bool,const char*> loc = getString("Location");
107 string address = m_appId + loc.second + "::run::SAML2SI";
108 setAddress(address.c_str());
111 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
112 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
113 if (outgoing.first) {
114 m_outgoing = XMLString::replicate(outgoing.second);
117 // No override, so we'll install a default binding precedence.
118 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
119 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
120 m_outgoing = XMLString::transcode(prec.c_str());
121 XMLString::trim(m_outgoing);
125 XMLCh* start = m_outgoing;
126 while (start && *start) {
127 pos = XMLString::indexOf(start,chSpace);
129 *(start + pos)=chNull;
130 m_bindings.push_back(start);
132 auto_ptr_char b(start);
133 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
134 m_encoders[start] = encoder;
135 m_log.info("supporting outgoing binding (%s)", b.get());
137 catch (exception& ex) {
138 m_log.error("error building MessageEncoder: %s", ex.what());
141 start = start + pos + 1;
148 void SAML2SessionInitiator::setParent(const PropertySet* parent)
150 DOMPropertySet::setParent(parent);
151 pair<bool,const char*> loc = getString("Location");
153 string address = m_appId + loc.second + "::run::SAML2SI";
154 setAddress(address.c_str());
157 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
161 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
163 // We have to know the IdP to function.
164 if (!entityID || !*entityID)
165 return make_pair(false,0);
168 const Handler* ACS=NULL;
170 pair<bool,const char*> acClass;
171 pair<bool,const char*> acComp;
172 bool isPassive=false,forceAuthn=false;
173 const Application& app=request.getApplication();
174 pair<bool,bool> acsByIndex = getBool("acsByIndex");
177 option=request.getParameter("acsIndex");
179 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
181 option = request.getParameter("target");
184 if (!acsByIndex.first || !acsByIndex.second) {
185 // Since we're passing the ACS by value, we need to compute the return URL,
186 // so we'll need the target resource for real.
187 recoverRelayState(request.getApplication(), request, target, false);
190 option = request.getParameter("isPassive");
191 isPassive = (option && (*option=='1' || *option=='t'));
193 option = request.getParameter("forceAuthn");
194 forceAuthn = (option && (*option=='1' || *option=='t'));
197 acClass.second = request.getParameter("authnContextClassRef");
198 acClass.first = (acClass.second!=NULL);
199 acComp.second = request.getParameter("authnContextComparison");
200 acComp.first = (acComp.second!=NULL);
203 // We're running as a "virtual handler" from within the filter.
204 // The target resource is the current one and everything else is defaulted.
205 target=request.getRequestURL();
206 const PropertySet* settings = request.getRequestSettings().first;
208 pair<bool,bool> flag = settings->getBool("isPassive");
209 isPassive = flag.first && flag.second;
211 flag = settings->getBool("forceAuthn");
212 forceAuthn = flag.first && flag.second;
215 acClass = settings->getString("authnContextClassRef");
216 acComp = settings->getString("authnContextComparison");
219 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
221 // To invoke the request builder, the key requirement is to figure out how and whether
222 // to express the ACS, by index or value, and if by value, where.
224 SPConfig& conf = SPConfig::getConfig();
225 if (conf.isEnabled(SPConfig::OutOfProcess)) {
226 if (acsByIndex.first && acsByIndex.second) {
227 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
229 // We may already have RelayState set if we looped back here,
230 // but just in case target is a resource, we reset it back.
232 option = request.getParameter("target");
237 app, request, entityID, ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL, isPassive, forceAuthn, target
241 // Since we're not passing by index, we need to fully compute the return URL and binding.
243 ACS = app.getDefaultAssertionConsumerService();
245 // Compute the ACS URL. We add the ACS location to the base handlerURL.
246 string ACSloc=request.getHandlerURL(target.c_str());
247 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
248 if (loc.first) ACSloc+=loc.second;
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");
260 app, request, entityID, NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL, isPassive, forceAuthn, target
265 DDF out,in = DDF(m_address.c_str()).structure();
266 DDFJanitor jin(in), jout(out);
267 in.addmember("application_id").string(app.getId());
268 in.addmember("entity_id").string(entityID);
270 in.addmember("isPassive").integer(1);
272 in.addmember("forceAuthn").integer(1);
274 in.addmember("authnContextClassRef").string(acClass.second);
276 in.addmember("authnContextComparison").string(acComp.second);
277 if (acsByIndex.first && acsByIndex.second) {
279 in.addmember("acsIndex").string(ACS->getString("index").second);
282 // Since we're not passing by index, we need to fully compute the return URL and binding.
284 ACS = app.getDefaultAssertionConsumerService();
286 // Compute the ACS URL. We add the ACS location to the base handlerURL.
287 string ACSloc=request.getHandlerURL(target.c_str());
288 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
289 if (loc.first) ACSloc+=loc.second;
290 in.addmember("acsLocation").string(ACSloc.c_str());
292 in.addmember("acsBinding").string(ACS->getString("Binding").second);
296 // We may already have RelayState set if we looped back here,
297 // but just in case target is a resource, we reset it back.
299 option = request.getParameter("target");
304 in.addmember("RelayState").string(target.c_str());
306 // Remote the processing.
307 out = request.getServiceProvider().getListenerService()->send(in);
308 return unwrap(request, out);
311 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
314 const char* aid=in["application_id"].string();
315 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
317 // Something's horribly wrong.
318 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
319 throw ConfigurationException("Unable to locate application for new session, deleted?");
322 const char* entityID = in["entity_id"].string();
324 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
327 DDFJanitor jout(ret);
329 // Wrap the outgoing object with a Response facade.
330 auto_ptr<HTTPResponse> http(getResponse(ret));
332 auto_ptr_XMLCh index(in["acsIndex"].string());
333 auto_ptr_XMLCh bind(in["acsBinding"].string());
335 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
337 // Since we're remoted, the result should either be a throw, which we pass on,
338 // a false/0 return, which we just return as an empty structure, or a response/redirect,
339 // which we capture in the facade and send back.
341 *app, *http.get(), entityID,
342 index.get(), in["acsLocation"].string(), bind.get(),
343 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
349 pair<bool,long> SAML2SessionInitiator::doRequest(
350 const Application& app,
351 HTTPResponse& httpResponse,
352 const char* entityID,
353 const XMLCh* acsIndex,
354 const char* acsLocation,
355 const XMLCh* acsBinding,
361 // Use metadata to locate the IdP's SSO service.
362 MetadataProvider* m=app.getMetadataProvider();
364 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
366 m_log.error("unable to locate metadata for provider (%s)", entityID);
367 return make_pair(false,0);
369 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
371 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
372 return make_pair(false,0);
375 // Loop over the supportable outgoing bindings.
376 const EndpointType* ep=NULL;
377 const MessageEncoder* encoder=NULL;
378 vector<const XMLCh*>::const_iterator b;
379 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
380 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
381 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
382 if (enc!=m_encoders.end())
383 encoder = enc->second;
387 if (!ep || !encoder) {
388 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
389 return make_pair(false,0);
392 preserveRelayState(app, httpResponse, relayState);
394 // For now just build a dummy AuthnRequest.
395 auto_ptr<AuthnRequest> req(AuthnRequestBuilder::buildAuthnRequest());
396 req->setDestination(ep->getLocation());
398 req->setAssertionConsumerServiceIndex(acsIndex);
400 auto_ptr_XMLCh wideloc(acsLocation);
401 req->setAssertionConsumerServiceURL(wideloc.get());
404 req->setProtocolBinding(acsBinding);
406 req->IsPassive(isPassive);
408 req->ForceAuthn(forceAuthn);
409 Issuer* issuer = IssuerBuilder::buildIssuer();
410 req->setIssuer(issuer);
411 issuer->setName(app.getXMLString("providerId").second);
413 auto_ptr_char dest(ep->getLocation());
415 // Check for signing.
416 const PropertySet* relyingParty = app.getRelyingParty(entity);
417 pair<bool,bool> flag = relyingParty->getBool("signRequests");
418 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
419 CredentialResolver* credResolver=app.getCredentialResolver();
421 Locker credLocker(credResolver);
422 // Fill in criteria to use.
423 MetadataCredentialCriteria mcc(*role);
424 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
425 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
427 mcc.setXMLAlgorithm(sigalg.second);
428 const Credential* cred = credResolver->resolve(&mcc);
431 long ret = encoder->encode(
439 relyingParty->getXMLString("digestAlg").second
441 req.release(); // freed by encoder
442 return make_pair(true,ret);
445 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
451 long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
452 req.release(); // freed by encoder
453 return make_pair(true,ret);