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