2 * Copyright 2001-2010 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 * Shib1SessionInitiator.cpp
20 * Shibboleth 1.x AuthnRequest support.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "handler/SessionInitiator.h"
30 #include "util/SPConstants.h"
33 # include "metadata/MetadataProviderCriteria.h"
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/EndpointManager.h>
36 # include <saml/util/SAMLConstants.h>
38 # include "lite/SAMLConstants.h"
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/URLEncoder.h>
43 using namespace shibsp;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
46 using namespace xmltooling;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
59 Shib1SessionInitiator(const DOMElement* e, const char* appId)
60 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Shib1"), nullptr, &m_remapper), m_appId(appId) {
61 // If Location isn't set, defer address registration until the setParent call.
62 pair<bool,const char*> loc = getString("Location");
64 string address = m_appId + loc.second + "::run::Shib1SI";
65 setAddress(address.c_str());
68 virtual ~Shib1SessionInitiator() {}
70 void setParent(const PropertySet* parent);
71 void receive(DDF& in, ostream& out);
72 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
73 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
75 const XMLCh* getProtocolFamily() const {
76 return samlconstants::SAML11_PROTOCOL_ENUM;
80 pair<bool,long> doRequest(
81 const Application& application,
82 const HTTPRequest* httpRequest,
83 HTTPResponse& httpResponse,
85 const char* acsLocation,
92 #if defined (_MSC_VER)
93 #pragma warning( pop )
96 SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
98 return new Shib1SessionInitiator(p.first, p.second);
103 void Shib1SessionInitiator::setParent(const PropertySet* parent)
105 DOMPropertySet::setParent(parent);
106 pair<bool,const char*> loc = getString("Location");
108 string address = m_appId + loc.second + "::run::Shib1SI";
109 setAddress(address.c_str());
112 m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
116 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
118 // We have to know the IdP to function.
119 if (entityID.empty() || !checkCompatibility(request, isHandler))
120 return make_pair(false,0L);
123 pair<bool,const char*> prop;
124 const Handler* ACS=nullptr;
125 const Application& app = request.getApplication();
128 prop.second = request.getParameter("acsIndex");
129 if (prop.second && *prop.second) {
130 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
132 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
135 prop = getString("target", request);
137 target = prop.second;
139 // Since we're passing the ACS by value, we need to compute the return URL,
140 // so we'll need the target resource for real.
141 recoverRelayState(app, request, request, target, false);
144 // Check for a hardwired target value in the map or handler.
145 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
147 target = prop.second;
149 target = request.getRequestURL();
153 // Try fixed index property.
154 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
156 ACS = app.getAssertionConsumerServiceByIndex(index.second);
159 // If we picked by index, validate the ACS for use with this protocol.
160 if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
162 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 1.x ACS, using default SAML 1.x ACS");
163 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
165 throw ConfigurationException("Unable to locate a SAML 1.x ACS endpoint to use for response.");
168 // Since we're not passing by index, we need to fully compute the return URL.
169 // Compute the ACS URL. We add the ACS location to the base handlerURL.
170 string ACSloc = request.getHandlerURL(target.c_str());
171 prop = ACS->getString("Location");
173 ACSloc += prop.second;
176 // We may already have RelayState set if we looped back here,
177 // but we've turned it back into a resource by this point, so if there's
178 // a target on the URL, reset to that value.
179 prop.second = request.getParameter("target");
180 if (prop.second && *prop.second)
181 target = prop.second;
184 // Is the in-bound binding artifact?
185 bool artifactInbound = XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT);
187 m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
189 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
190 // Out of process means the POST data via the request can be exposed directly to the private method.
191 // The method will handle POST preservation if necessary *before* issuing the response, but only if
192 // it dispatches to an IdP.
193 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), artifactInbound, target);
197 DDF out,in = DDF(m_address.c_str()).structure();
198 DDFJanitor jin(in), jout(out);
199 in.addmember("application_id").string(app.getId());
200 in.addmember("entity_id").string(entityID.c_str());
201 in.addmember("acsLocation").string(ACSloc.c_str());
203 in.addmember("artifact").integer(1);
205 in.addmember("RelayState").unsafe_string(target.c_str());
207 // Remote the processing. Our unwrap method will handle POST data if necessary.
208 out = request.getServiceProvider().getListenerService()->send(in);
209 return unwrap(request, out);
212 pair<bool,long> Shib1SessionInitiator::unwrap(SPRequest& request, DDF& out) const
214 // See if there's any response to send back.
215 if (!out["redirect"].isnull() || !out["response"].isnull()) {
216 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
217 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
219 return RemotedHandler::unwrap(request, out);
222 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
225 const char* aid=in["application_id"].string();
226 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
228 // Something's horribly wrong.
229 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
230 throw ConfigurationException("Unable to locate application for new session, deleted?");
233 const char* entityID = in["entity_id"].string();
234 const char* acsLocation = in["acsLocation"].string();
235 if (!entityID || !acsLocation)
236 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
239 DDFJanitor jout(ret);
241 // Wrap the outgoing object with a Response facade.
242 auto_ptr<HTTPResponse> http(getResponse(ret));
244 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
246 // Since we're remoted, the result should either be a throw, which we pass on,
247 // a false/0 return, which we just return as an empty structure, or a response/redirect,
248 // which we capture in the facade and send back.
249 doRequest(*app, nullptr, *http.get(), entityID, acsLocation, (in["artifact"].integer() != 0), relayState);
252 ret.addmember("RelayState").unsafe_string(relayState.c_str());
256 pair<bool,long> Shib1SessionInitiator::doRequest(
257 const Application& app,
258 const HTTPRequest* httpRequest,
259 HTTPResponse& httpResponse,
260 const char* entityID,
261 const char* acsLocation,
267 // Use metadata to invoke the SSO service directly.
268 MetadataProvider* m=app.getMetadataProvider();
270 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
271 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
273 m_log.warn("unable to locate metadata for provider (%s)", entityID);
274 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
276 else if (!entity.second) {
277 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
279 return make_pair(false,0L);
280 throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
282 else if (artifact && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
283 m_log.warn("artifact profile selected for response, but identity provider lacks support");
285 return make_pair(false,0L);
286 throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
289 const EndpointType* ep=EndpointManager<SingleSignOnService>(
290 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
291 ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
293 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
295 return make_pair(false,0L);
296 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
299 preserveRelayState(app, httpResponse, relayState);
301 // Shib 1.x requires a target value.
302 if (relayState.empty())
303 relayState = "default";
306 sprintf(timebuf,"%lu",time(nullptr));
307 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
308 auto_ptr_char dest(ep->getLocation());
309 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
310 "&time=" + timebuf + "&target=" + urlenc->encode(relayState.c_str()) +
311 "&providerId=" + urlenc->encode(app.getRelyingParty(entity.first)->getString("entityID").second);
314 // If the request object is available, we're responsible for the POST data.
315 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
318 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
320 return make_pair(false,0L);