2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * Shib1SessionInitiator.cpp
24 * Shibboleth 1.x AuthnRequest support.
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "handler/AbstractHandler.h"
32 #include "handler/RemotedHandler.h"
33 #include "handler/SessionInitiator.h"
34 #include "util/SPConstants.h"
37 # include "metadata/MetadataProviderCriteria.h"
38 # include <boost/lexical_cast.hpp>
39 # include <saml/saml2/metadata/Metadata.h>
40 # include <saml/saml2/metadata/EndpointManager.h>
41 # include <saml/util/SAMLConstants.h>
43 # include "lite/SAMLConstants.h"
45 #include <boost/scoped_ptr.hpp>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/URLEncoder.h>
49 using namespace shibsp;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace xmltooling;
53 using namespace boost;
58 #if defined (_MSC_VER)
59 #pragma warning( push )
60 #pragma warning( disable : 4250 )
63 class SHIBSP_DLLLOCAL Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
66 Shib1SessionInitiator(const DOMElement* e, const char* appId)
67 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.Shib1"), nullptr, &m_remapper), m_appId(appId) {
68 // If Location isn't set, defer address registration until the setParent call.
69 pair<bool,const char*> loc = getString("Location");
71 string address = m_appId + loc.second + "::run::Shib1SI";
72 setAddress(address.c_str());
75 virtual ~Shib1SessionInitiator() {}
77 void setParent(const PropertySet* parent);
78 void receive(DDF& in, ostream& out);
79 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
80 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
82 const XMLCh* getProtocolFamily() const {
83 return samlconstants::SAML11_PROTOCOL_ENUM;
87 void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
88 doGenerateMetadata(role, handlerURL);
93 pair<bool,long> doRequest(
94 const Application& application,
95 const HTTPRequest* httpRequest,
96 HTTPResponse& httpResponse,
98 const char* acsLocation,
105 #if defined (_MSC_VER)
106 #pragma warning( pop )
109 SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
111 return new Shib1SessionInitiator(p.first, p.second);
116 void Shib1SessionInitiator::setParent(const PropertySet* parent)
118 DOMPropertySet::setParent(parent);
119 pair<bool,const char*> loc = getString("Location");
121 string address = m_appId + loc.second + "::run::Shib1SI";
122 setAddress(address.c_str());
125 m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
129 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
131 // We have to know the IdP to function.
132 if (entityID.empty() || !checkCompatibility(request, isHandler))
133 return make_pair(false, 0L);
136 pair<bool,const char*> prop;
137 const Handler* ACS = nullptr;
138 const Application& app = request.getApplication();
141 prop.second = request.getParameter("acsIndex");
142 if (prop.second && *prop.second) {
143 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
145 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
148 prop = getString("target", request);
150 target = prop.second;
152 // Since we're passing the ACS by value, we need to compute the return URL,
153 // so we'll need the target resource for real.
154 recoverRelayState(app, request, request, target, false);
155 app.limitRedirect(request, target.c_str());
158 // Check for a hardwired target value in the map or handler.
159 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
161 target = prop.second;
163 target = request.getRequestURL();
167 // Try fixed index property.
168 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
170 ACS = app.getAssertionConsumerServiceByIndex(index.second);
173 // If we picked by index, validate the ACS for use with this protocol.
174 if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
176 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 1.x ACS, using default SAML 1.x ACS");
177 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
179 throw ConfigurationException("Unable to locate a SAML 1.x ACS endpoint to use for response.");
182 // Since we're not passing by index, we need to fully compute the return URL.
183 // Compute the ACS URL. We add the ACS location to the base handlerURL.
184 string ACSloc = request.getHandlerURL(target.c_str());
185 prop = ACS->getString("Location");
187 ACSloc += prop.second;
190 // We may already have RelayState set if we looped back here,
191 // but we've turned it back into a resource by this point, so if there's
192 // a target on the URL, reset to that value.
193 prop.second = request.getParameter("target");
194 if (prop.second && *prop.second)
195 target = prop.second;
198 // Is the in-bound binding artifact?
199 bool artifactInbound = XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT);
201 m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
203 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
204 // Out of process means the POST data via the request can be exposed directly to the private method.
205 // The method will handle POST preservation if necessary *before* issuing the response, but only if
206 // it dispatches to an IdP.
207 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), artifactInbound, target);
211 DDF out,in = DDF(m_address.c_str()).structure();
212 DDFJanitor jin(in), jout(out);
213 in.addmember("application_id").string(app.getId());
214 in.addmember("entity_id").string(entityID.c_str());
215 in.addmember("acsLocation").string(ACSloc.c_str());
217 in.addmember("artifact").integer(1);
219 in.addmember("RelayState").unsafe_string(target.c_str());
221 // Remote the processing. Our unwrap method will handle POST data if necessary.
222 out = request.getServiceProvider().getListenerService()->send(in);
223 return unwrap(request, out);
226 pair<bool,long> Shib1SessionInitiator::unwrap(SPRequest& request, DDF& out) const
228 // See if there's any response to send back.
229 if (!out["redirect"].isnull() || !out["response"].isnull()) {
230 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
231 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
233 return RemotedHandler::unwrap(request, out);
236 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
239 const char* aid = in["application_id"].string();
240 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
242 // Something's horribly wrong.
243 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
244 throw ConfigurationException("Unable to locate application for new session, deleted?");
247 const char* entityID = in["entity_id"].string();
248 const char* acsLocation = in["acsLocation"].string();
249 if (!entityID || !acsLocation)
250 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
253 DDFJanitor jout(ret);
255 // Wrap the outgoing object with a Response facade.
256 scoped_ptr<HTTPResponse> http(getResponse(ret));
258 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
260 // Since we're remoted, the result should either be a throw, which we pass on,
261 // a false/0 return, which we just return as an empty structure, or a response/redirect,
262 // which we capture in the facade and send back.
263 doRequest(*app, nullptr, *http, entityID, acsLocation, (in["artifact"].integer() != 0), relayState);
266 ret.addmember("RelayState").unsafe_string(relayState.c_str());
270 pair<bool,long> Shib1SessionInitiator::doRequest(
271 const Application& app,
272 const HTTPRequest* httpRequest,
273 HTTPResponse& httpResponse,
274 const char* entityID,
275 const char* acsLocation,
281 // Use metadata to invoke the SSO service directly.
282 MetadataProvider* m = app.getMetadataProvider();
284 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
285 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
287 m_log.warn("unable to locate metadata for provider (%s)", entityID);
288 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
290 else if (!entity.second) {
291 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
293 return make_pair(false, 0L);
294 throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
296 else if (artifact && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
297 m_log.warn("artifact profile selected for response, but identity provider lacks support");
299 return make_pair(false, 0L);
300 throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
303 const EndpointType* ep = EndpointManager<SingleSignOnService>(
304 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
305 ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
307 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
309 return make_pair(false, 0L);
310 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
313 preserveRelayState(app, httpResponse, relayState);
315 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
317 auto_ptr_char prot(getProtocolFamily());
318 ar_event->m_protocol = prot.get();
319 auto_ptr_char b(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
320 ar_event->m_binding = b.get();
321 ar_event->m_peer = entity.first;
322 app.getServiceProvider().getTransactionLog()->write(*ar_event);
325 // Shib 1.x requires a target value.
326 if (relayState.empty())
327 relayState = "default";
329 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
330 auto_ptr_char dest(ep->getLocation());
331 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
332 "&time=" + lexical_cast<string>(time(nullptr)) + "&target=" + urlenc->encode(relayState.c_str()) +
333 "&providerId=" + urlenc->encode(app.getRelyingParty(entity.first)->getString("entityID").second);
336 // If the request object is available, we're responsible for the POST data.
337 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
340 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
342 return make_pair(false, 0L);