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 pair<bool,long> doRequest(
88 const Application& application,
89 const HTTPRequest* httpRequest,
90 HTTPResponse& httpResponse,
92 const char* acsLocation,
99 #if defined (_MSC_VER)
100 #pragma warning( pop )
103 SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
105 return new Shib1SessionInitiator(p.first, p.second);
110 void Shib1SessionInitiator::setParent(const PropertySet* parent)
112 DOMPropertySet::setParent(parent);
113 pair<bool,const char*> loc = getString("Location");
115 string address = m_appId + loc.second + "::run::Shib1SI";
116 setAddress(address.c_str());
119 m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
123 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
125 // We have to know the IdP to function.
126 if (entityID.empty() || !checkCompatibility(request, isHandler))
127 return make_pair(false, 0L);
130 pair<bool,const char*> prop;
131 const Handler* ACS = nullptr;
132 const Application& app = request.getApplication();
135 prop.second = request.getParameter("acsIndex");
136 if (prop.second && *prop.second) {
137 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
139 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
142 prop = getString("target", request);
144 target = prop.second;
146 // Since we're passing the ACS by value, we need to compute the return URL,
147 // so we'll need the target resource for real.
148 recoverRelayState(app, request, request, target, false);
149 app.limitRedirect(request, target.c_str());
152 // Check for a hardwired target value in the map or handler.
153 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
155 target = prop.second;
157 target = request.getRequestURL();
161 // Try fixed index property.
162 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
164 ACS = app.getAssertionConsumerServiceByIndex(index.second);
167 // If we picked by index, validate the ACS for use with this protocol.
168 if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
170 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 1.x ACS, using default SAML 1.x ACS");
171 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
173 throw ConfigurationException("Unable to locate a SAML 1.x ACS endpoint to use for response.");
176 // Since we're not passing by index, we need to fully compute the return URL.
177 // Compute the ACS URL. We add the ACS location to the base handlerURL.
178 string ACSloc = request.getHandlerURL(target.c_str());
179 prop = ACS->getString("Location");
181 ACSloc += prop.second;
184 // We may already have RelayState set if we looped back here,
185 // but we've turned it back into a resource by this point, so if there's
186 // a target on the URL, reset to that value.
187 prop.second = request.getParameter("target");
188 if (prop.second && *prop.second)
189 target = prop.second;
192 // Is the in-bound binding artifact?
193 bool artifactInbound = XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT);
195 m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
197 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
198 // Out of process means the POST data via the request can be exposed directly to the private method.
199 // The method will handle POST preservation if necessary *before* issuing the response, but only if
200 // it dispatches to an IdP.
201 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), artifactInbound, target);
205 DDF out,in = DDF(m_address.c_str()).structure();
206 DDFJanitor jin(in), jout(out);
207 in.addmember("application_id").string(app.getId());
208 in.addmember("entity_id").string(entityID.c_str());
209 in.addmember("acsLocation").string(ACSloc.c_str());
211 in.addmember("artifact").integer(1);
213 in.addmember("RelayState").unsafe_string(target.c_str());
215 // Remote the processing. Our unwrap method will handle POST data if necessary.
216 out = request.getServiceProvider().getListenerService()->send(in);
217 return unwrap(request, out);
220 pair<bool,long> Shib1SessionInitiator::unwrap(SPRequest& request, DDF& out) const
222 // See if there's any response to send back.
223 if (!out["redirect"].isnull() || !out["response"].isnull()) {
224 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
225 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
227 return RemotedHandler::unwrap(request, out);
230 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
233 const char* aid = in["application_id"].string();
234 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
236 // Something's horribly wrong.
237 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
238 throw ConfigurationException("Unable to locate application for new session, deleted?");
241 const char* entityID = in["entity_id"].string();
242 const char* acsLocation = in["acsLocation"].string();
243 if (!entityID || !acsLocation)
244 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
247 DDFJanitor jout(ret);
249 // Wrap the outgoing object with a Response facade.
250 scoped_ptr<HTTPResponse> http(getResponse(ret));
252 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
254 // Since we're remoted, the result should either be a throw, which we pass on,
255 // a false/0 return, which we just return as an empty structure, or a response/redirect,
256 // which we capture in the facade and send back.
257 doRequest(*app, nullptr, *http, entityID, acsLocation, (in["artifact"].integer() != 0), relayState);
260 ret.addmember("RelayState").unsafe_string(relayState.c_str());
264 pair<bool,long> Shib1SessionInitiator::doRequest(
265 const Application& app,
266 const HTTPRequest* httpRequest,
267 HTTPResponse& httpResponse,
268 const char* entityID,
269 const char* acsLocation,
275 // Use metadata to invoke the SSO service directly.
276 MetadataProvider* m = app.getMetadataProvider();
278 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
279 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
281 m_log.warn("unable to locate metadata for provider (%s)", entityID);
282 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
284 else if (!entity.second) {
285 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
287 return make_pair(false, 0L);
288 throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
290 else if (artifact && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
291 m_log.warn("artifact profile selected for response, but identity provider lacks support");
293 return make_pair(false, 0L);
294 throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
297 const EndpointType* ep = EndpointManager<SingleSignOnService>(
298 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
299 ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
301 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
303 return make_pair(false, 0L);
304 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
307 preserveRelayState(app, httpResponse, relayState);
309 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
311 auto_ptr_char prot(getProtocolFamily());
312 ar_event->m_protocol = prot.get();
313 auto_ptr_char b(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
314 ar_event->m_binding = b.get();
315 ar_event->m_peer = entity.first;
316 app.getServiceProvider().getTransactionLog()->write(*ar_event);
319 // Shib 1.x requires a target value.
320 if (relayState.empty())
321 relayState = "default";
323 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
324 auto_ptr_char dest(ep->getLocation());
325 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
326 "&time=" + lexical_cast<string>(time(nullptr)) + "&target=" + urlenc->encode(relayState.c_str()) +
327 "&providerId=" + urlenc->encode(app.getRelyingParty(entity.first)->getString("entityID").second);
330 // If the request object is available, we're responsible for the POST data.
331 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
334 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
336 return make_pair(false, 0L);