2 * Copyright 2001-2009 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 "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/saml2/metadata/Metadata.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/util/URLEncoder.h>
41 using namespace shibsp;
42 using namespace opensaml::saml2md;
43 using namespace opensaml;
44 using namespace xmltooling;
49 #if defined (_MSC_VER)
50 #pragma warning( push )
51 #pragma warning( disable : 4250 )
54 class SHIBSP_DLLLOCAL Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
57 Shib1SessionInitiator(const DOMElement* e, const char* appId)
58 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Shib1")), m_appId(appId) {
59 // If Location isn't set, defer address registration until the setParent call.
60 pair<bool,const char*> loc = getString("Location");
62 string address = m_appId + loc.second + "::run::Shib1SI";
63 setAddress(address.c_str());
66 virtual ~Shib1SessionInitiator() {}
68 void setParent(const PropertySet* parent);
69 void receive(DDF& in, ostream& out);
70 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
73 pair<bool,long> doRequest(
74 const Application& application,
75 HTTPResponse& httpResponse,
77 const char* acsLocation,
85 #if defined (_MSC_VER)
86 #pragma warning( pop )
89 SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
91 return new Shib1SessionInitiator(p.first, p.second);
96 void Shib1SessionInitiator::setParent(const PropertySet* parent)
98 DOMPropertySet::setParent(parent);
99 pair<bool,const char*> loc = getString("Location");
101 string address = m_appId + loc.second + "::run::Shib1SI";
102 setAddress(address.c_str());
105 m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
109 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
111 // We have to know the IdP to function.
112 if (entityID.empty())
113 return make_pair(false,0L);
117 const Handler* ACS=NULL;
119 const Application& app=request.getApplication();
122 option=request.getParameter("acsIndex");
124 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
126 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
129 option = request.getParameter("target");
133 // Since we're passing the ACS by value, we need to compute the return URL,
134 // so we'll need the target resource for real.
135 recoverRelayState(request.getApplication(), request, request, target, false);
138 // We're running as a "virtual handler" from within the filter.
139 // The target resource is the current one and everything else is defaulted.
140 target=request.getRequestURL();
141 postData = getPostData(request);
144 // Since we're not passing by index, we need to fully compute the return URL.
146 pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
148 ACS = app.getAssertionConsumerServiceByIndex(index.second);
150 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
153 ACS = app.getDefaultAssertionConsumerService();
156 // Compute the ACS URL. We add the ACS location to the base handlerURL.
157 string ACSloc=request.getHandlerURL(target.c_str());
158 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
159 if (loc.first) ACSloc+=loc.second;
162 // We may already have RelayState set if we looped back here,
163 // but just in case target is a resource, we reset it back.
165 option = request.getParameter("target");
170 // Is the in-bound binding artifact?
171 bool artifactInbound = ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT) : false;
173 m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
175 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
176 return doRequest(app, request, entityID.c_str(), ACSloc.c_str(), artifactInbound, target, postData);
179 DDF out,in = DDF(m_address.c_str()).structure();
180 DDFJanitor jin(in), jout(out);
181 in.addmember("application_id").string(app.getId());
182 in.addmember("entity_id").string(entityID.c_str());
183 in.addmember("acsLocation").string(ACSloc.c_str());
185 in.addmember("artifact").integer(1);
187 in.addmember("RelayState").string(target.c_str());
189 if (!postData.empty()) {
190 in.addmember("PostData").string(postData.c_str());
191 m_log.debug("shib1SI remoting %d posted bytes", postData.length());
194 // Remote the processing.
195 out = request.getServiceProvider().getListenerService()->send(in);
196 return unwrap(request, out);
199 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
202 const char* aid=in["application_id"].string();
203 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
205 // Something's horribly wrong.
206 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
207 throw ConfigurationException("Unable to locate application for new session, deleted?");
210 const char* entityID = in["entity_id"].string();
211 const char* acsLocation = in["acsLocation"].string();
212 if (!entityID || !acsLocation)
213 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
216 DDFJanitor jout(ret);
218 // Wrap the outgoing object with a Response facade.
219 auto_ptr<HTTPResponse> http(getResponse(ret));
221 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
222 string postData(in["PostData"].string() ? in["PostData"].string() : "");
224 // Since we're remoted, the result should either be a throw, which we pass on,
225 // a false/0 return, which we just return as an empty structure, or a response/redirect,
226 // which we capture in the facade and send back.
227 doRequest(*app, *http.get(), entityID, acsLocation, (in["artifact"].integer() != 0), relayState, postData);
231 pair<bool,long> Shib1SessionInitiator::doRequest(
232 const Application& app,
233 HTTPResponse& httpResponse,
234 const char* entityID,
235 const char* acsLocation,
242 // Use metadata to invoke the SSO service directly.
243 MetadataProvider* m=app.getMetadataProvider();
245 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
246 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
248 m_log.warn("unable to locate metadata for provider (%s)", entityID);
249 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
251 else if (!entity.second) {
252 m_log.warn("unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
254 return make_pair(false,0L);
255 throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
257 else if (artifact && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
258 m_log.warn("artifact profile selected for response, but identity provider lacks support");
260 return make_pair(false,0L);
261 throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
264 const EndpointType* ep=EndpointManager<SingleSignOnService>(
265 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
266 ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
268 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
270 return make_pair(false,0L);
271 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
274 preserveRelayState(app, httpResponse, relayState);
275 preservePostData(app, httpResponse, postData, relayState);
277 // Shib 1.x requires a target value.
278 if (relayState.empty())
279 relayState = "default";
282 sprintf(timebuf,"%lu",time(NULL));
283 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
284 auto_ptr_char dest(ep->getLocation());
285 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
286 "&time=" + timebuf + "&target=" + urlenc->encode(relayState.c_str()) +
287 "&providerId=" + urlenc->encode(app.getRelyingParty(entity.first)->getString("entityID").second);
289 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
291 return make_pair(false,0L);