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 <xmltooling/XMLToolingConfig.h>
34 #include <xmltooling/util/URLEncoder.h>
36 using namespace shibsp;
37 using namespace opensaml;
38 using namespace xmltooling;
42 # include <saml/saml2/metadata/Metadata.h>
43 # include <saml/saml2/metadata/MetadataProvider.h>
44 using namespace opensaml::saml2md;
49 #if defined (_MSC_VER)
50 #pragma warning( push )
51 #pragma warning( disable : 4250 )
54 class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
57 SAMLDSSessionInitiator(const DOMElement* e, const char* appId);
58 virtual ~SAMLDSSessionInitiator() {}
60 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
63 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
64 // Initial guess at index to use.
65 pair<bool,unsigned int> ix = getUnsignedInt("index");
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);
75 pair<bool,int> val = sub->getIndex();
77 if (ix.second <= val.second)
78 ix.second = val.second + 1;
85 const char* loc = getString("Location").second;
86 string hurl(handlerURL);
90 auto_ptr_XMLCh widen(hurl.c_str());
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();
98 ext = ExtensionsBuilder::buildExtensions();
99 role.setExtensions(ext);
101 ext->getUnknownXMLObjects().push_back(ep);
107 const char* m_returnParam;
108 vector<string> m_preservedOptions;
111 #if defined (_MSC_VER)
112 #pragma warning( pop )
115 SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
117 return new SAMLDSSessionInitiator(p.first, p.second);
122 SAMLDSSessionInitiator::SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
123 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(nullptr), m_returnParam(nullptr)
125 pair<bool,const char*> url = getString("URL");
127 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
129 url = getString("entityIDParam");
131 m_returnParam = url.second;
133 pair<bool,const char*> options = getString("preservedOptions");
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));
143 m_preservedOptions.push_back(opt.substr(j, opt.length()-j));
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");
155 m_supportedOptions.insert("isPassive");
158 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
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);
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);
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");
180 prop = getString("target", request);
182 target = prop.second;
184 recoverRelayState(app, request, request, target, false);
186 pair<bool,bool> passopt = getBool("isPassive", request);
187 isPassive = passopt.first && passopt.second;
189 prop.second = request.getParameter("discoveryURL");
190 if (prop.second && *prop.second)
191 discoveryURL.second = prop.second;
194 // Check for a hardwired target value in the map or handler.
195 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
197 target = prop.second;
199 target = request.getRequestURL();
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");
206 if (!discoveryURL.first)
207 discoveryURL.second = m_url;
208 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
210 // Compute the return URL. We start with a self-referential link.
211 string returnURL = request.getHandlerURL(target.c_str());
212 prop = getString("Location");
214 returnURL += prop.second;
215 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
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;
225 preserveRelayState(app, request, target);
227 preservePostData(app, request, request, target.c_str());
229 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
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();
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;
245 // There's something in the query before target appears, so we have to find it.
246 prop.second = strstr(query, "&target=");
248 // We found it, so first append everything up to it.
250 returnURL.append(query, prop.second - query);
251 query = prop.second + 8; // move up just past the equals sign.
252 prop.second = strchr(query, '&');
254 returnURL += prop.second;
257 // No target in the existing query, so just append it as is.
258 returnURL = returnURL + '&' + query;
263 // Now append the sanitized target as needed.
265 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
268 // For a virtual handler, we append target to the return link.
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());
275 returnURL = returnURL + '&' + (*opt) + '=' + urlenc->encode(prop.second);
279 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
280 "&return=" + urlenc->encode(returnURL.c_str());
282 req = req + "&returnIDParam=" + m_returnParam;
284 req += "&isPassive=true";
286 return make_pair(true, request.sendRedirect(req.c_str()));