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