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