Imported Upstream version 2.3+dfsg
[shibboleth/sp.git] / shibsp / handler / impl / Shib1SessionInitiator.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * Shib1SessionInitiator.cpp
19  *
20  * Shibboleth 1.x AuthnRequest support.
21  */
22
23 #include "internal.h"
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"
32
33 #ifndef SHIBSP_LITE
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/saml2/metadata/Metadata.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/util/SAMLConstants.h>
38 #else
39 # include "lite/SAMLConstants.h"
40 #endif
41 #include <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/util/URLEncoder.h>
43
44 using namespace shibsp;
45 using namespace opensaml::saml2md;
46 using namespace opensaml;
47 using namespace xmltooling;
48 using namespace std;
49
50 namespace shibsp {
51
52 #if defined (_MSC_VER)
53     #pragma warning( push )
54     #pragma warning( disable : 4250 )
55 #endif
56
57     class SHIBSP_DLLLOCAL Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
58     {
59     public:
60         Shib1SessionInitiator(const DOMElement* e, const char* appId)
61                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Shib1"), NULL, &m_remapper), m_appId(appId) {
62             // If Location isn't set, defer address registration until the setParent call.
63             pair<bool,const char*> loc = getString("Location");
64             if (loc.first) {
65                 string address = m_appId + loc.second + "::run::Shib1SI";
66                 setAddress(address.c_str());
67             }
68         }
69         virtual ~Shib1SessionInitiator() {}
70
71         void setParent(const PropertySet* parent);
72         void receive(DDF& in, ostream& out);
73         pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
74         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
75
76     private:
77         pair<bool,long> doRequest(
78             const Application& application,
79             const HTTPRequest* httpRequest,
80             HTTPResponse& httpResponse,
81             const char* entityID,
82             const char* acsLocation,
83             bool artifact,
84             string& relayState
85             ) const;
86         string m_appId;
87     };
88
89 #if defined (_MSC_VER)
90     #pragma warning( pop )
91 #endif
92
93     SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
94     {
95         return new Shib1SessionInitiator(p.first, p.second);
96     }
97
98 };
99
100 void Shib1SessionInitiator::setParent(const PropertySet* parent)
101 {
102     DOMPropertySet::setParent(parent);
103     pair<bool,const char*> loc = getString("Location");
104     if (loc.first) {
105         string address = m_appId + loc.second + "::run::Shib1SI";
106         setAddress(address.c_str());
107     }
108     else {
109         m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
110     }
111 }
112
113 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
114 {
115     // We have to know the IdP to function.
116     if (entityID.empty())
117         return make_pair(false,0L);
118
119     string target;
120     string postData;
121     const Handler* ACS=NULL;
122     const char* option;
123     const Application& app=request.getApplication();
124
125     if (isHandler) {
126         option=request.getParameter("acsIndex");
127         if (option) {
128             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
129             if (!ACS)
130                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
131         }
132
133         option = request.getParameter("target");
134         if (option)
135             target = option;
136
137         // Since we're passing the ACS by value, we need to compute the return URL,
138         // so we'll need the target resource for real.
139         recoverRelayState(request.getApplication(), request, request, target, false);
140     }
141     else {
142         // We're running as a "virtual handler" from within the filter.
143         // The target resource is the current one and everything else is defaulted.
144         target=request.getRequestURL();
145     }
146
147     // Since we're not passing by index, we need to fully compute the return URL.
148     if (!ACS) {
149         pair<bool,unsigned int> index = getUnsignedInt("acsIndex");
150         if (index.first) {
151             ACS = app.getAssertionConsumerServiceByIndex(index.second);
152             if (!ACS)
153                 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
154         }
155         if (!ACS)
156             ACS = app.getDefaultAssertionConsumerService();
157     }
158
159     // Validate the ACS for use with this protocol.
160     pair<bool,const char*> ACSbinding = ACS ? ACS->getString("Binding") : pair<bool,const char*>(false,NULL);
161     if (ACSbinding.first) {
162         pair<bool,const char*> compatibleBindings = getString("compatibleBindings");
163         if (compatibleBindings.first && strstr(compatibleBindings.second, ACSbinding.second) == NULL) {
164             m_log.error("configured or requested ACS has non-SAML 1.x binding");
165             throw ConfigurationException("Configured or requested ACS has non-SAML 1.x binding ($1).", params(1, ACSbinding.second));
166         }
167         else if (strcmp(ACSbinding.second, samlconstants::SAML1_PROFILE_BROWSER_POST) &&
168                  strcmp(ACSbinding.second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT)) {
169             m_log.error("configured or requested ACS has non-SAML 1.x binding");
170             throw ConfigurationException("Configured or requested ACS has non-SAML 1.x binding ($1).", params(1, ACSbinding.second));
171         }
172     }
173
174     // Compute the ACS URL. We add the ACS location to the base handlerURL.
175     string ACSloc=request.getHandlerURL(target.c_str());
176     pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
177     if (loc.first) ACSloc+=loc.second;
178
179     if (isHandler) {
180         // We may already have RelayState set if we looped back here,
181         // but just in case target is a resource, we reset it back.
182         target.erase();
183         option = request.getParameter("target");
184         if (option)
185             target = option;
186     }
187
188     // Is the in-bound binding artifact?
189     bool artifactInbound = ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT) : false;
190
191     m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
192
193     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
194         // Out of process means the POST data via the request can be exposed directly to the private method.
195         // The method will handle POST preservation if necessary *before* issuing the response, but only if
196         // it dispatches to an IdP.
197         return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), artifactInbound, target);
198     }
199
200     // Remote the call.
201     DDF out,in = DDF(m_address.c_str()).structure();
202     DDFJanitor jin(in), jout(out);
203     in.addmember("application_id").string(app.getId());
204     in.addmember("entity_id").string(entityID.c_str());
205     in.addmember("acsLocation").string(ACSloc.c_str());
206     if (artifactInbound)
207         in.addmember("artifact").integer(1);
208     if (!target.empty())
209         in.addmember("RelayState").unsafe_string(target.c_str());
210
211     // Remote the processing. Our unwrap method will handle POST data if necessary.
212     out = request.getServiceProvider().getListenerService()->send(in);
213     return unwrap(request, out);
214 }
215
216 pair<bool,long> Shib1SessionInitiator::unwrap(SPRequest& request, DDF& out) const
217 {
218     // See if there's any response to send back.
219     if (!out["redirect"].isnull() || !out["response"].isnull()) {
220         // If so, we're responsible for handling the POST data, probably by dropping a cookie.
221         preservePostData(request.getApplication(), request, request, out["RelayState"].string());
222     }
223     return RemotedHandler::unwrap(request, out);
224 }
225
226 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
227 {
228     // Find application.
229     const char* aid=in["application_id"].string();
230     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
231     if (!app) {
232         // Something's horribly wrong.
233         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
234         throw ConfigurationException("Unable to locate application for new session, deleted?");
235     }
236
237     const char* entityID = in["entity_id"].string();
238     const char* acsLocation = in["acsLocation"].string();
239     if (!entityID || !acsLocation)
240         throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
241
242     DDF ret(NULL);
243     DDFJanitor jout(ret);
244
245     // Wrap the outgoing object with a Response facade.
246     auto_ptr<HTTPResponse> http(getResponse(ret));
247
248     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
249
250     // Since we're remoted, the result should either be a throw, which we pass on,
251     // a false/0 return, which we just return as an empty structure, or a response/redirect,
252     // which we capture in the facade and send back.
253     doRequest(*app, NULL, *http.get(), entityID, acsLocation, (in["artifact"].integer() != 0), relayState);
254     if (!ret.isstruct())
255         ret.structure();
256     ret.addmember("RelayState").unsafe_string(relayState.c_str());
257     out << ret;
258 }
259
260 pair<bool,long> Shib1SessionInitiator::doRequest(
261     const Application& app,
262     const HTTPRequest* httpRequest,
263     HTTPResponse& httpResponse,
264     const char* entityID,
265     const char* acsLocation,
266     bool artifact,
267     string& relayState
268     ) const
269 {
270 #ifndef SHIBSP_LITE
271     // Use metadata to invoke the SSO service directly.
272     MetadataProvider* m=app.getMetadataProvider();
273     Locker locker(m);
274     MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
275     pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
276     if (!entity.first) {
277         m_log.warn("unable to locate metadata for provider (%s)", entityID);
278         throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
279     }
280     else if (!entity.second) {
281         m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
282         if (getParent())
283             return make_pair(false,0L);
284         throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
285     }
286     else if (artifact && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
287         m_log.warn("artifact profile selected for response, but identity provider lacks support");
288         if (getParent())
289             return make_pair(false,0L);
290         throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
291     }
292
293     const EndpointType* ep=EndpointManager<SingleSignOnService>(
294         dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
295         ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
296     if (!ep) {
297         m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
298         if (getParent())
299             return make_pair(false,0L);
300         throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
301     }
302
303     preserveRelayState(app, httpResponse, relayState);
304
305     // Shib 1.x requires a target value.
306     if (relayState.empty())
307         relayState = "default";
308
309     char timebuf[16];
310     sprintf(timebuf,"%lu",time(NULL));
311     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
312     auto_ptr_char dest(ep->getLocation());
313     string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
314         "&time=" + timebuf + "&target=" + urlenc->encode(relayState.c_str()) +
315         "&providerId=" + urlenc->encode(app.getRelyingParty(entity.first)->getString("entityID").second);
316
317     if (httpRequest) {
318         // If the request object is available, we're responsible for the POST data.
319         preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
320     }
321
322     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
323 #else
324     return make_pair(false,0L);
325 #endif
326 }