https://issues.shibboleth.net/jira/browse/SSPCPP-352
[shibboleth/cpp-sp.git] / shibsp / handler / impl / Shib1SessionInitiator.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * Shib1SessionInitiator.cpp
23  *
24  * Shibboleth 1.x AuthnRequest support.
25  */
26
27 #include "internal.h"
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"
35
36 #ifndef SHIBSP_LITE
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>
42 #else
43 # include "lite/SAMLConstants.h"
44 #endif
45 #include <boost/scoped_ptr.hpp>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/URLEncoder.h>
48
49 using namespace shibsp;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace xmltooling;
53 using namespace boost;
54 using namespace std;
55
56 namespace shibsp {
57
58 #if defined (_MSC_VER)
59     #pragma warning( push )
60     #pragma warning( disable : 4250 )
61 #endif
62
63     class SHIBSP_DLLLOCAL Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
64     {
65     public:
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");
70             if (loc.first) {
71                 string address = m_appId + loc.second + "::run::Shib1SI";
72                 setAddress(address.c_str());
73             }
74         }
75         virtual ~Shib1SessionInitiator() {}
76
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;
81
82         const XMLCh* getProtocolFamily() const {
83             return samlconstants::SAML11_PROTOCOL_ENUM;
84         }
85
86     private:
87         pair<bool,long> doRequest(
88             const Application& application,
89             const HTTPRequest* httpRequest,
90             HTTPResponse& httpResponse,
91             const char* entityID,
92             const char* acsLocation,
93             bool artifact,
94             string& relayState
95             ) const;
96         string m_appId;
97     };
98
99 #if defined (_MSC_VER)
100     #pragma warning( pop )
101 #endif
102
103     SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
104     {
105         return new Shib1SessionInitiator(p.first, p.second);
106     }
107
108 };
109
110 void Shib1SessionInitiator::setParent(const PropertySet* parent)
111 {
112     DOMPropertySet::setParent(parent);
113     pair<bool,const char*> loc = getString("Location");
114     if (loc.first) {
115         string address = m_appId + loc.second + "::run::Shib1SI";
116         setAddress(address.c_str());
117     }
118     else {
119         m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
120     }
121 }
122
123 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
124 {
125     // We have to know the IdP to function.
126     if (entityID.empty() || !checkCompatibility(request, isHandler))
127         return make_pair(false, 0L);
128
129     string target;
130     pair<bool,const char*> prop;
131     const Handler* ACS = nullptr;
132     const Application& app = request.getApplication();
133
134     if (isHandler) {
135         prop.second = request.getParameter("acsIndex");
136         if (prop.second && *prop.second) {
137             ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
138             if (!ACS)
139                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
140         }
141
142         prop = getString("target", request);
143         if (prop.first)
144             target = prop.second;
145
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());
150     }
151     else {
152         // Check for a hardwired target value in the map or handler.
153         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
154         if (prop.first)
155             target = prop.second;
156         else
157             target = request.getRequestURL();
158     }
159
160     if (!ACS) {
161         // Try fixed index property.
162         pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
163         if (index.first)
164             ACS = app.getAssertionConsumerServiceByIndex(index.second);
165     }
166
167     // If we picked by index, validate the ACS for use with this protocol.
168     if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
169         if (ACS)
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());
172         if (!ACS)
173             throw ConfigurationException("Unable to locate a SAML 1.x ACS endpoint to use for response.");
174     }
175
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");
180     if (prop.first)
181         ACSloc += prop.second;
182
183     if (isHandler) {
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;
190     }
191
192     // Is the in-bound binding artifact?
193     bool artifactInbound = XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT);
194
195     m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID.c_str());
196
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);
202     }
203
204     // Remote the call.
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());
210     if (artifactInbound)
211         in.addmember("artifact").integer(1);
212     if (!target.empty())
213         in.addmember("RelayState").unsafe_string(target.c_str());
214
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);
218 }
219
220 pair<bool,long> Shib1SessionInitiator::unwrap(SPRequest& request, DDF& out) const
221 {
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());
226     }
227     return RemotedHandler::unwrap(request, out);
228 }
229
230 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
231 {
232     // Find application.
233     const char* aid = in["application_id"].string();
234     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
235     if (!app) {
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?");
239     }
240
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.");
245
246     DDF ret(nullptr);
247     DDFJanitor jout(ret);
248
249     // Wrap the outgoing object with a Response facade.
250     scoped_ptr<HTTPResponse> http(getResponse(ret));
251
252     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
253
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);
258     if (!ret.isstruct())
259         ret.structure();
260     ret.addmember("RelayState").unsafe_string(relayState.c_str());
261     out << ret;
262 }
263
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,
270     bool artifact,
271     string& relayState
272     ) const
273 {
274 #ifndef SHIBSP_LITE
275     // Use metadata to invoke the SSO service directly.
276     MetadataProvider* m = app.getMetadataProvider();
277     Locker locker(m);
278     MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, shibspconstants::SHIB1_PROTOCOL_ENUM);
279     pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
280     if (!entity.first) {
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));
283     }
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);
286         if (getParent())
287             return make_pair(false, 0L);
288         throw MetadataException("Unable to locate Shibboleth-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
289     }
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");
292         if (getParent())
293             return make_pair(false, 0L);
294         throw MetadataException("Identity provider ($entityID) lacks SAML artifact support.", namedparams(1, "entityID", entityID));
295     }
296
297     const EndpointType* ep = EndpointManager<SingleSignOnService>(
298         dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
299         ).getByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
300     if (!ep) {
301         m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
302         if (getParent())
303             return make_pair(false, 0L);
304         throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
305     }
306
307     preserveRelayState(app, httpResponse, relayState);
308
309     scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
310     if (ar_event) {
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);
317     }
318
319     // Shib 1.x requires a target value.
320     if (relayState.empty())
321         relayState = "default";
322
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);
328
329     if (httpRequest) {
330         // If the request object is available, we're responsible for the POST data.
331         preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
332     }
333
334     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
335 #else
336     return make_pair(false, 0L);
337 #endif
338 }