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 XMLCh* acsLocation,
78 const XMLCh* acsBinding,
84 vector<const XMLCh*> m_bindings;
85 map<const XMLCh*,MessageEncoder*> m_encoders;
88 #if defined (_MSC_VER)
89 #pragma warning( pop )
92 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
94 return new SAML2SessionInitiator(p.first, p.second);
99 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
100 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_outgoing(NULL)
102 // If Location isn't set, defer address registration until the setParent call.
103 pair<bool,const char*> loc = getString("Location");
105 string address = m_appId + loc.second + "::run::SAML2SI";
106 setAddress(address.c_str());
109 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
110 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
111 if (outgoing.first) {
112 m_outgoing = XMLString::replicate(outgoing.second);
115 // No override, so we'll install a default binding precedence.
116 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
117 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
118 m_outgoing = XMLString::transcode(prec.c_str());
119 XMLString::trim(m_outgoing);
123 XMLCh* start = m_outgoing;
124 while (start && *start) {
125 pos = XMLString::indexOf(start,chSpace);
127 *(start + pos)=chNull;
128 m_bindings.push_back(start);
130 auto_ptr_char b(start);
131 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
132 m_encoders[start] = encoder;
133 m_log.info("supporting outgoing binding (%s)", b.get());
135 catch (exception& ex) {
136 m_log.error("error building MessageEncoder: %s", ex.what());
139 start = start + pos + 1;
146 void SAML2SessionInitiator::setParent(const PropertySet* parent)
148 DOMPropertySet::setParent(parent);
149 pair<bool,const char*> loc = getString("Location");
151 string address = m_appId + loc.second + "::run::SAML2SI";
152 setAddress(address.c_str());
155 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
159 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
161 // We have to know the IdP to function.
162 if (!entityID || !*entityID)
163 return make_pair(false,0);
166 const Handler* ACS=NULL;
168 const Application& app=request.getApplication();
169 pair<bool,bool> acsByIndex = getBool("acsByIndex");
172 option=request.getParameter("acsIndex");
174 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
176 option = request.getParameter("target");
179 if (!acsByIndex.first || !acsByIndex.second) {
180 // Since we're passing the ACS by value, we need to compute the return URL,
181 // so we'll need the target resource for real.
182 recoverRelayState(request.getApplication(), request, target, false);
186 // We're running as a "virtual handler" from within the filter.
187 // The target resource is the current one and everything else is defaulted.
188 target=request.getRequestURL();
191 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
193 // To invoke the request builder, the key requirement is to figure out how and whether
194 // to express the ACS, by index or value, and if by value, where.
196 SPConfig& conf = SPConfig::getConfig();
197 if (conf.isEnabled(SPConfig::OutOfProcess)) {
198 if (acsByIndex.first && acsByIndex.second) {
199 // Pass by Index. This also allows for defaulting it entirely and sending nothing.
201 // We may already have RelayState set if we looped back here,
202 // but just in case target is a resource, we reset it back.
204 option = request.getParameter("target");
208 return doRequest(app, request, entityID, ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL, target);
211 // Since we're not passing by index, we need to fully compute the return URL and binding.
213 ACS = app.getDefaultAssertionConsumerService();
215 // Compute the ACS URL. We add the ACS location to the base handlerURL.
216 string ACSloc=request.getHandlerURL(target.c_str());
217 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
218 if (loc.first) ACSloc+=loc.second;
221 // We may already have RelayState set if we looped back here,
222 // but just in case target is a resource, we reset it back.
224 option = request.getParameter("target");
229 auto_ptr_XMLCh wideloc(ACSloc.c_str());
230 return doRequest(app, request, entityID, NULL, wideloc.get(), ACS ? ACS->getXMLString("Binding").second : NULL, target);
234 DDF out,in = DDF(m_address.c_str()).structure();
235 DDFJanitor jin(in), jout(out);
236 in.addmember("application_id").string(app.getId());
237 in.addmember("entity_id").string(entityID);
238 if (acsByIndex.first && acsByIndex.second) {
240 in.addmember("acsIndex").string(ACS->getString("index").second);
243 // Since we're not passing by index, we need to fully compute the return URL and binding.
245 ACS = app.getDefaultAssertionConsumerService();
247 // Compute the ACS URL. We add the ACS location to the base handlerURL.
248 string ACSloc=request.getHandlerURL(target.c_str());
249 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
250 if (loc.first) ACSloc+=loc.second;
251 in.addmember("acsLocation").string(ACSloc.c_str());
253 in.addmember("acsBinding").string(ACS->getString("Binding").second);
257 // We may already have RelayState set if we looped back here,
258 // but just in case target is a resource, we reset it back.
260 option = request.getParameter("target");
265 in.addmember("RelayState").string(target.c_str());
267 // Remote the processing.
268 out = request.getServiceProvider().getListenerService()->send(in);
269 return unwrap(request, out);
272 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
275 const char* aid=in["application_id"].string();
276 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
278 // Something's horribly wrong.
279 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
280 throw ConfigurationException("Unable to locate application for new session, deleted?");
283 const char* entityID = in["entity_id"].string();
285 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
288 DDFJanitor jout(ret);
290 // Wrap the outgoing object with a Response facade.
291 auto_ptr<HTTPResponse> http(getResponse(ret));
293 auto_ptr_XMLCh index(in["acsIndex"].string());
294 auto_ptr_XMLCh loc(in["acsLocation"].string());
295 auto_ptr_XMLCh bind(in["acsBinding"].string());
297 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
299 // Since we're remoted, the result should either be a throw, which we pass on,
300 // a false/0 return, which we just return as an empty structure, or a response/redirect,
301 // which we capture in the facade and send back.
302 doRequest(*app, *http.get(), entityID, index.get(), loc.get(), bind.get(), relayState);
306 pair<bool,long> SAML2SessionInitiator::doRequest(
307 const Application& app,
308 HTTPResponse& httpResponse,
309 const char* entityID,
310 const XMLCh* acsIndex,
311 const XMLCh* acsLocation,
312 const XMLCh* acsBinding,
316 // Use metadata to locate the IdP's SSO service.
317 MetadataProvider* m=app.getMetadataProvider();
319 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
321 m_log.error("unable to locate metadata for provider (%s)", entityID);
322 return make_pair(false,0);
324 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
326 m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
327 return make_pair(false,0);
330 // Loop over the supportable outgoing bindings.
331 const EndpointType* ep=NULL;
332 const MessageEncoder* encoder=NULL;
333 vector<const XMLCh*>::const_iterator b;
334 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
335 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
336 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
337 if (enc!=m_encoders.end())
338 encoder = enc->second;
342 if (!ep || !encoder) {
343 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
344 return make_pair(false,0);
347 preserveRelayState(app, httpResponse, relayState);
349 // For now just build a dummy AuthnRequest.
350 auto_ptr<AuthnRequest> req(AuthnRequestBuilder::buildAuthnRequest());
351 req->setDestination(ep->getLocation());
353 req->setAssertionConsumerServiceIndex(acsIndex);
355 req->setAssertionConsumerServiceURL(acsLocation);
357 req->setProtocolBinding(acsBinding);
358 Issuer* issuer = IssuerBuilder::buildIssuer();
359 req->setIssuer(issuer);
360 issuer->setName(app.getXMLString("providerId").second);
362 auto_ptr_char dest(ep->getLocation());
364 // Check for signing.
365 const PropertySet* relyingParty = app.getRelyingParty(entity);
366 pair<bool,bool> flag = relyingParty->getBool("signRequests");
367 if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
368 CredentialResolver* credResolver=app.getCredentialResolver();
370 Locker credLocker(credResolver);
371 // Fill in criteria to use.
372 MetadataCredentialCriteria mcc(*role);
373 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
374 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
376 mcc.setXMLAlgorithm(sigalg.second);
377 const Credential* cred = credResolver->resolve(&mcc);
380 long ret = encoder->encode(
388 relyingParty->getXMLString("digestAlg").second
390 req.release(); // freed by encoder
391 return make_pair(true,ret);
394 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
400 long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
401 req.release(); // freed by encoder
402 return make_pair(true,ret);