SSPCPP-616 - clean up concatenated string literals
[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         trim(opt);
139         split(m_preservedOptions, opt, is_space(), algorithm::token_compress_on);
140     }
141     else {
142         m_preservedOptions.push_back("isPassive");
143         m_preservedOptions.push_back("forceAuthn");
144         m_preservedOptions.push_back("authnContextClassRef");
145         m_preservedOptions.push_back("authnContextComparison");
146         m_preservedOptions.push_back("NameIDFormat");
147         m_preservedOptions.push_back("SPNameQualifier");
148         m_preservedOptions.push_back("acsIndex");
149     }
150
151     m_supportedOptions.insert("isPassive");
152 }
153
154 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
155 {
156     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
157     // anytime the IdP's metadata was wrong.
158     if (!entityID.empty() || !checkCompatibility(request, isHandler))
159         return make_pair(false,0L);
160
161     string target;
162     pair<bool,const char*> prop;
163     bool isPassive = false;
164     const Application& app = request.getApplication();
165     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
166
167     if (isHandler) {
168         prop.second = request.getParameter("SAMLDS");
169         if (prop.second && !strcmp(prop.second,"1")) {
170             saml2md::MetadataException ex("No identity provider was selected by user.");
171             ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
172             ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
173             ex.raise();
174         }
175
176         prop = getString("target", request);
177         if (prop.first)
178             target = prop.second;
179
180         recoverRelayState(app, request, request, target, false);
181
182         pair<bool,bool> passopt = getBool("isPassive", request);
183         isPassive = passopt.first && passopt.second;
184
185         prop.second = request.getParameter("discoveryURL");
186         if (prop.second && *prop.second)
187             discoveryURL.second = prop.second;
188     }
189     else {
190         // Check for a hardwired target value in the map or handler.
191         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
192         if (prop.first)
193             target = prop.second;
194         else
195             target = request.getRequestURL();
196
197         pair<bool,bool> passopt = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
198         isPassive = passopt.first && passopt.second;
199         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
200     }
201
202     if (!discoveryURL.first)
203         discoveryURL.second = m_url;
204     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
205
206     // Compute the return URL. We start with a self-referential link.
207     string returnURL = request.getHandlerURL(target.c_str());
208     prop = getString("Location");
209     if (prop.first)
210         returnURL += prop.second;
211     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
212
213     if (isHandler) {
214         // We may already have RelayState set if we looped back here,
215         // but we've turned it back into a resource by this point, so if there's
216         // a target on the URL, reset to that value.
217         prop.second = request.getParameter("target");
218         if (prop.second && *prop.second)
219             target = prop.second;
220     }
221     preserveRelayState(app, request, target);
222     if (!isHandler)
223         preservePostData(app, request, request, target.c_str());
224
225     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
226     if (isHandler) {
227         // Now the hard part. The base assumption is to append the entire query string, if any,
228         // to the self-link. But we want to replace target with the RelayState-preserved value
229         // to hide it from the DS.
230         const char* query = request.getQueryString();
231         if (query) {
232             // See if it starts with target.
233             if (!strncmp(query, "target=", 7)) {
234                 // We skip this altogether and advance the query past it to the first separator.
235                 query = strchr(query, '&');
236                 // If we still have more, just append it.
237                 if (query && *(++query))
238                     returnURL = returnURL + '&' + query;
239             }
240             else {
241                 // There's something in the query before target appears, so we have to find it.
242                 prop.second = strstr(query, "&target=");
243                 if (prop.second) {
244                     // We found it, so first append everything up to it.
245                     returnURL += '&';
246                     returnURL.append(query, prop.second - query);
247                     query = prop.second + 8; // move up just past the equals sign.
248                     prop.second = strchr(query, '&');
249                     if (prop.second)
250                         returnURL += prop.second;
251                 }
252                 else {
253                     // No target in the existing query, so just append it as is.
254                     returnURL = returnURL + '&' + query;
255                 }
256             }
257         }
258
259         // Now append the sanitized target as needed.
260         if (!target.empty())
261             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
262     }
263     else {
264         // For a virtual handler, we append target to the return link.
265          if (!target.empty())
266             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
267          // Preserve designated request settings on the URL.
268          for (vector<string>::const_iterator opt = m_preservedOptions.begin(); opt != m_preservedOptions.end(); ++ opt) {
269              prop = request.getRequestSettings().first->getString(opt->c_str());
270              if (prop.first)
271                  returnURL = returnURL + '&' + (*opt) + '=' + urlenc->encode(prop.second);
272          }
273     }
274
275     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
276         "&return=" + urlenc->encode(returnURL.c_str());
277     if (m_returnParam)
278         req = req + "&returnIDParam=" + m_returnParam;
279     if (isPassive)
280         req += "&isPassive=true";
281     prop = getString("discoveryPolicy");
282     if (prop.first)
283         req += "&policy=" + urlenc->encode(prop.second);
284
285     return make_pair(true, request.sendRedirect(req.c_str()));
286 }