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