e3977a60ee950c2b6ceefcd7a4e853273c98166f
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.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  * SAMLDSSessionInitiator.cpp
23  *
24  * SAML Discovery Service support.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "handler/AbstractHandler.h"
31 #include "handler/SessionInitiator.h"
32
33 #include <boost/algorithm/string.hpp>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/util/URLEncoder.h>
36
37 using namespace shibsp;
38 using namespace opensaml;
39 using namespace xmltooling;
40 using namespace boost;
41 using namespace std;
42
43 #ifndef SHIBSP_LITE
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <saml/saml2/metadata/MetadataProvider.h>
46 using namespace opensaml::saml2md;
47 #endif
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 SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
57     {
58     public:
59         SAMLDSSessionInitiator(const DOMElement* e, const char* appId);
60         virtual ~SAMLDSSessionInitiator() {}
61
62         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
63
64 #ifndef SHIBSP_LITE
65         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66             // Initial guess at index to use.
67             pair<bool,unsigned int> ix = getUnsignedInt("index");
68             if (!ix.first)
69                 ix.second = 1;
70
71             // Find maximum index in use and go one higher.
72             if (role.getExtensions()) {
73                 const vector<XMLObject*>& exts = const_cast<const Extensions*>(role.getExtensions())->getUnknownXMLObjects();
74                 for (vector<XMLObject*>::const_reverse_iterator i = exts.rbegin(); i != exts.rend(); ++i) {
75                     const DiscoveryResponse* sub = dynamic_cast<DiscoveryResponse*>(*i);
76                     if (sub) {
77                         pair<bool,int> val = sub->getIndex();
78                         if (val.first) {
79                             if (ix.second <= val.second)
80                                 ix.second = val.second + 1;
81                             break;
82                         }
83                     }
84                 }
85             }
86
87             const char* loc = getString("Location").second;
88             string hurl(handlerURL);
89             if (*loc != '/')
90                 hurl += '/';
91             hurl += loc;
92             auto_ptr_XMLCh widen(hurl.c_str());
93
94             DiscoveryResponse* ep = DiscoveryResponseBuilder::buildDiscoveryResponse();
95             ep->setLocation(widen.get());
96             ep->setBinding(samlconstants::IDP_DISCOVERY_PROTOCOL_NS);
97             ep->setIndex(ix.second);
98             Extensions* ext = role.getExtensions();
99             if (!ext) {
100                 ext = ExtensionsBuilder::buildExtensions();
101                 role.setExtensions(ext);
102             }
103             ext->getUnknownXMLObjects().push_back(ep);
104         }
105 #endif
106
107     private:
108         const char* m_url;
109         const char* m_returnParam;
110         vector<string> m_preservedOptions;
111     };
112
113 #if defined (_MSC_VER)
114     #pragma warning( pop )
115 #endif
116
117     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
118     {
119         return new SAMLDSSessionInitiator(p.first, p.second);
120     }
121
122 };
123
124 SAMLDSSessionInitiator::SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
125         : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(nullptr), m_returnParam(nullptr)
126 {
127     pair<bool,const char*> url = getString("URL");
128     if (!url.first)
129         throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
130     m_url = url.second;
131     url = getString("entityIDParam");
132     if (url.first)
133         m_returnParam = url.second;
134
135     pair<bool,const char*> options = getString("preservedOptions");
136     if (options.first) {
137         string opt = options.second;
138         split(m_preservedOptions, opt, is_space(), algorithm::token_compress_on);
139     }
140     else {
141         m_preservedOptions.push_back("isPassive");
142         m_preservedOptions.push_back("forceAuthn");
143         m_preservedOptions.push_back("authnContextClassRef");
144         m_preservedOptions.push_back("authnContextComparison");
145         m_preservedOptions.push_back("NameIDFormat");
146         m_preservedOptions.push_back("SPNameQualifier");
147         m_preservedOptions.push_back("acsIndex");
148     }
149
150     m_supportedOptions.insert("isPassive");
151 }
152
153 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
154 {
155     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
156     // anytime the IdP's metadata was wrong.
157     if (!entityID.empty() || !checkCompatibility(request, isHandler))
158         return make_pair(false,0L);
159
160     string target;
161     pair<bool,const char*> prop;
162     bool isPassive = false;
163     const Application& app = request.getApplication();
164     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
165
166     if (isHandler) {
167         prop.second = request.getParameter("SAMLDS");
168         if (prop.second && !strcmp(prop.second,"1")) {
169             saml2md::MetadataException ex("No identity provider was selected by user.");
170             ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
171             ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
172             ex.raise();
173         }
174
175         prop = getString("target", request);
176         if (prop.first)
177             target = prop.second;
178
179         recoverRelayState(app, request, request, target, false);
180
181         pair<bool,bool> passopt = getBool("isPassive", request);
182         isPassive = passopt.first && passopt.second;
183
184         prop.second = request.getParameter("discoveryURL");
185         if (prop.second && *prop.second)
186             discoveryURL.second = prop.second;
187     }
188     else {
189         // Check for a hardwired target value in the map or handler.
190         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
191         if (prop.first)
192             target = prop.second;
193         else
194             target = request.getRequestURL();
195
196         pair<bool,bool> passopt = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
197         isPassive = passopt.first && passopt.second;
198         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
199     }
200
201     if (!discoveryURL.first)
202         discoveryURL.second = m_url;
203     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
204
205     // Compute the return URL. We start with a self-referential link.
206     string returnURL = request.getHandlerURL(target.c_str());
207     prop = getString("Location");
208     if (prop.first)
209         returnURL += prop.second;
210     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
211
212     if (isHandler) {
213         // We may already have RelayState set if we looped back here,
214         // but we've turned it back into a resource by this point, so if there's
215         // a target on the URL, reset to that value.
216         prop.second = request.getParameter("target");
217         if (prop.second && *prop.second)
218             target = prop.second;
219     }
220     preserveRelayState(app, request, target);
221     if (!isHandler)
222         preservePostData(app, request, request, target.c_str());
223
224     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
225     if (isHandler) {
226         // Now the hard part. The base assumption is to append the entire query string, if any,
227         // to the self-link. But we want to replace target with the RelayState-preserved value
228         // to hide it from the DS.
229         const char* query = request.getQueryString();
230         if (query) {
231             // See if it starts with target.
232             if (!strncmp(query, "target=", 7)) {
233                 // We skip this altogether and advance the query past it to the first separator.
234                 query = strchr(query, '&');
235                 // If we still have more, just append it.
236                 if (query && *(++query))
237                     returnURL = returnURL + '&' + query;
238             }
239             else {
240                 // There's something in the query before target appears, so we have to find it.
241                 prop.second = strstr(query, "&target=");
242                 if (prop.second) {
243                     // We found it, so first append everything up to it.
244                     returnURL += '&';
245                     returnURL.append(query, prop.second - query);
246                     query = prop.second + 8; // move up just past the equals sign.
247                     prop.second = strchr(query, '&');
248                     if (prop.second)
249                         returnURL += prop.second;
250                 }
251                 else {
252                     // No target in the existing query, so just append it as is.
253                     returnURL = returnURL + '&' + query;
254                 }
255             }
256         }
257
258         // Now append the sanitized target as needed.
259         if (!target.empty())
260             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
261     }
262     else {
263         // For a virtual handler, we append target to the return link.
264          if (!target.empty())
265             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
266          // Preserve designated request settings on the URL.
267          for (vector<string>::const_iterator opt = m_preservedOptions.begin(); opt != m_preservedOptions.end(); ++ opt) {
268              prop = request.getRequestSettings().first->getString(opt->c_str());
269              if (prop.first)
270                  returnURL = returnURL + '&' + (*opt) + '=' + urlenc->encode(prop.second);
271          }
272     }
273
274     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
275         "&return=" + urlenc->encode(returnURL.c_str());
276     if (m_returnParam)
277         req = req + "&returnIDParam=" + m_returnParam;
278     if (isPassive)
279         req += "&isPassive=true";
280     prop = getString("discoveryPolicy");
281     if (prop.first)
282         req += "&policy=" + urlenc->encode(prop.second);
283
284     return make_pair(true, request.sendRedirect(req.c_str()));
285 }