2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * SAMLDSSessionInitiator.cpp
20 * SAML Discovery Service support.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "handler/AbstractHandler.h"
27 #include "handler/SessionInitiator.h"
29 #include <xmltooling/XMLToolingConfig.h>
30 #include <xmltooling/impl/AnyElement.h>
31 #include <xmltooling/util/URLEncoder.h>
33 using namespace shibsp;
34 using namespace opensaml;
35 using namespace xmltooling;
39 # include <saml/saml2/metadata/Metadata.h>
40 # include <saml/saml2/metadata/MetadataProvider.h>
41 using namespace opensaml::saml2md;
46 #if defined (_MSC_VER)
47 #pragma warning( push )
48 #pragma warning( disable : 4250 )
51 class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
54 SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
55 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(nullptr), m_returnParam(nullptr)
57 ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
60 pair<bool,const char*> url = getString("URL");
62 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
64 url = getString("entityIDParam");
66 m_returnParam = url.second;
67 m_supportedOptions.insert("isPassive");
69 virtual ~SAMLDSSessionInitiator() {}
71 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
74 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
75 static const XMLCh LOCAL_NAME[] = UNICODE_LITERAL_17(D,i,s,c,o,v,e,r,y,R,e,s,p,o,n,s,e);
77 // Initial guess at index to use.
78 pair<bool,unsigned int> ix = getUnsignedInt("index");
82 // Find maximum index in use and go one higher.
83 if (role.getExtensions()) {
84 const vector<XMLObject*>& exts = const_cast<const Extensions*>(role.getExtensions())->getUnknownXMLObjects();
85 for (vector<XMLObject*>::const_reverse_iterator i = exts.rbegin(); i != exts.rend(); ++i) {
86 if (XMLString::equals((*i)->getElementQName().getLocalPart(), LOCAL_NAME) &&
87 XMLString::equals((*i)->getElementQName().getNamespaceURI(), m_discoNS.get())) {
88 const AttributeExtensibleXMLObject* sub = dynamic_cast<const AttributeExtensibleXMLObject*>(*i);
90 const XMLCh* val = sub->getAttribute(xmltooling::QName(nullptr,IndexedEndpointType::INDEX_ATTRIB_NAME));
92 int maxindex = XMLString::parseInt(val);
93 if (ix.second <= maxindex)
94 ix.second = maxindex + 1;
102 const char* loc = getString("Location").second;
103 string hurl(handlerURL);
107 auto_ptr_XMLCh widen(hurl.c_str());
111 auto_ptr_XMLCh widen2(os.str().c_str());
113 ElementProxy* ep = new AnyElementImpl(m_discoNS.get(), LOCAL_NAME);
114 ep->setAttribute(xmltooling::QName(nullptr,EndpointType::LOCATION_ATTRIB_NAME), widen.get());
115 ep->setAttribute(xmltooling::QName(nullptr,EndpointType::BINDING_ATTRIB_NAME), m_discoNS.get());
116 ep->setAttribute(xmltooling::QName(nullptr,IndexedEndpointType::INDEX_ATTRIB_NAME), widen2.get());
117 Extensions* ext = role.getExtensions();
119 ext = ExtensionsBuilder::buildExtensions();
120 role.setExtensions(ext);
122 ext->getUnknownXMLObjects().push_back(ep);
128 const char* m_returnParam;
130 auto_ptr_XMLCh m_discoNS;
134 #if defined (_MSC_VER)
135 #pragma warning( pop )
138 SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
140 return new SAMLDSSessionInitiator(p.first, p.second);
145 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
147 // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
148 // anytime the IdP's metadata was wrong.
149 if (!entityID.empty() || !checkCompatibility(request, isHandler))
150 return make_pair(false,0L);
153 pair<bool,const char*> prop;
154 bool isPassive=false;
155 const Application& app=request.getApplication();
156 pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
159 prop.second = request.getParameter("SAMLDS");
160 if (prop.second && !strcmp(prop.second,"1")) {
161 saml2md::MetadataException ex("No identity provider was selected by user.");
162 ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
163 ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
167 prop = getString("target", request);
169 target = prop.second;
171 recoverRelayState(app, request, request, target, false);
173 pair<bool,bool> passopt = getBool("isPassive", request);
174 isPassive = passopt.first && passopt.second;
176 prop.second = request.getParameter("discoveryURL");
177 if (prop.second && *prop.second)
178 discoveryURL.second = prop.second;
181 // Check for a hardwired target value in the map or handler.
182 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
184 target = prop.second;
186 target = request.getRequestURL();
188 pair<bool,bool> passopt = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
189 isPassive = passopt.first && passopt.second;
190 discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
193 if (!discoveryURL.first)
194 discoveryURL.second = m_url;
195 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
197 // Compute the return URL. We start with a self-referential link.
198 string returnURL = request.getHandlerURL(target.c_str());
199 prop = getString("Location");
201 returnURL += prop.second;
202 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
205 // We may already have RelayState set if we looped back here,
206 // but we've turned it back into a resource by this point, so if there's
207 // a target on the URL, reset to that value.
208 prop.second = request.getParameter("target");
209 if (prop.second && *prop.second)
210 target = prop.second;
212 preserveRelayState(app, request, target);
214 preservePostData(app, request, request, target.c_str());
216 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
218 // Now the hard part. The base assumption is to append the entire query string, if any,
219 // to the self-link. But we want to replace target with the RelayState-preserved value
220 // to hide it from the DS.
221 const char* query = request.getQueryString();
223 // See if it starts with target.
224 if (!strncmp(query, "target=", 7)) {
225 // We skip this altogether and advance the query past it to the first separator.
226 query = strchr(query, '&');
227 // If we still have more, just append it.
228 if (query && *(++query))
229 returnURL = returnURL + '&' + query;
232 // There's something in the query before target appears, so we have to find it.
233 prop.second = strstr(query, "&target=");
235 // We found it, so first append everything up to it.
237 returnURL.append(query, prop.second - query);
238 query = prop.second + 8; // move up just past the equals sign.
239 prop.second = strchr(query, '&');
241 returnURL += prop.second;
244 // No target in the existing query, so just append it as is.
245 returnURL = returnURL + '&' + query;
250 // Now append the sanitized target as needed.
252 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
254 else if (!target.empty()) {
255 // For a virtual handler, we just append target to the return link.
256 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
259 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
260 "&return=" + urlenc->encode(returnURL.c_str());
262 req = req + "&returnIDParam=" + m_returnParam;
264 req += "&isPassive=true";
266 return make_pair(true, request.sendRedirect(req.c_str()));