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