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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 * SAMLDSSessionInitiator.cpp
24 * SAML Discovery Service support.
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "handler/AbstractHandler.h"
31 #include "handler/SessionInitiator.h"
33 #include <boost/algorithm/string.hpp>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/util/URLEncoder.h>
37 using namespace shibsp;
38 using namespace opensaml;
39 using namespace xmltooling;
40 using namespace boost;
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <saml/saml2/metadata/MetadataProvider.h>
46 using namespace opensaml::saml2md;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
59 SAMLDSSessionInitiator(const DOMElement* e, const char* appId);
60 virtual ~SAMLDSSessionInitiator() {}
62 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
65 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66 // Initial guess at index to use.
67 pair<bool,unsigned int> ix = getUnsignedInt("index");
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);
77 pair<bool,int> val = sub->getIndex();
79 if (ix.second <= val.second)
80 ix.second = val.second + 1;
87 const char* loc = getString("Location").second;
88 string hurl(handlerURL);
92 auto_ptr_XMLCh widen(hurl.c_str());
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();
100 ext = ExtensionsBuilder::buildExtensions();
101 role.setExtensions(ext);
103 ext->getUnknownXMLObjects().push_back(ep);
109 const char* m_returnParam;
110 vector<string> m_preservedOptions;
113 #if defined (_MSC_VER)
114 #pragma warning( pop )
117 SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
119 return new SAMLDSSessionInitiator(p.first, p.second);
124 SAMLDSSessionInitiator::SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
125 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.SAMLDS")), m_url(nullptr), m_returnParam(nullptr)
127 pair<bool,const char*> url = getString("URL");
129 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
131 url = getString("entityIDParam");
133 m_returnParam = url.second;
135 pair<bool,const char*> options = getString("preservedOptions");
137 string opt = options.second;
139 split(m_preservedOptions, opt, is_space(), algorithm::token_compress_on);
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");
151 m_supportedOptions.insert("isPassive");
154 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
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);
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);
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");
176 prop = getString("target", request);
178 target = prop.second;
180 recoverRelayState(app, request, request, target, false);
182 pair<bool,bool> passopt = getBool("isPassive", request);
183 isPassive = passopt.first && passopt.second;
185 prop.second = request.getParameter("discoveryURL");
186 if (prop.second && *prop.second)
187 discoveryURL.second = prop.second;
190 // Check for a hardwired target value in the map or handler.
191 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
193 target = prop.second;
195 target = request.getRequestURL();
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");
202 if (!discoveryURL.first)
203 discoveryURL.second = m_url;
204 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
206 // Compute the return URL. We start with a self-referential link.
207 string returnURL = request.getHandlerURL(target.c_str());
208 prop = getString("Location");
210 returnURL += prop.second;
211 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
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;
221 preserveRelayState(app, request, target);
223 preservePostData(app, request, request, target.c_str());
225 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
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();
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;
241 // There's something in the query before target appears, so we have to find it.
242 prop.second = strstr(query, "&target=");
244 // We found it, so first append everything up to it.
246 returnURL.append(query, prop.second - query);
247 query = prop.second + 8; // move up just past the equals sign.
248 prop.second = strchr(query, '&');
250 returnURL += prop.second;
253 // No target in the existing query, so just append it as is.
254 returnURL = returnURL + '&' + query;
259 // Now append the sanitized target as needed.
261 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
264 // For a virtual handler, we append target to the return link.
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());
271 returnURL = returnURL + '&' + (*opt) + '=' + urlenc->encode(prop.second);
275 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
276 "&return=" + urlenc->encode(returnURL.c_str());
278 req = req + "&returnIDParam=" + m_returnParam;
280 req += "&isPassive=true";
281 prop = getString("discoveryPolicy");
283 req += "&policy=" + urlenc->encode(prop.second);
285 return make_pair(true, request.sendRedirect(req.c_str()));