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(NULL), m_returnParam(NULL)
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(NULL,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(NULL,EndpointType::LOCATION_ATTRIB_NAME), widen.get());
115 ep->setAttribute(xmltooling::QName(NULL,EndpointType::BINDING_ATTRIB_NAME), m_discoNS.get());
116 ep->setAttribute(xmltooling::QName(NULL,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);
154 bool isPassive=false;
155 const Application& app=request.getApplication();
156 pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
159 option = request.getParameter("SAMLDS");
160 if (option && !strcmp(option,"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 option = request.getParameter("target");
170 recoverRelayState(request.getApplication(), request, request, target, false);
172 option = request.getParameter("isPassive");
174 isPassive = (*option=='t' || *option=='1');
176 pair<bool,bool> passopt = getBool("isPassive");
177 isPassive = passopt.first && passopt.second;
180 option = request.getParameter("discoveryURL");
182 discoveryURL.second = option;
185 // We're running as a "virtual handler" from within the filter.
186 // The target resource is the current one and everything else is
187 // defaulted or set by content policy.
188 target=request.getRequestURL();
189 pair<bool,bool> passopt = request.getRequestSettings().first->getBool("isPassive");
191 passopt = getBool("isPassive");
192 isPassive = passopt.first && passopt.second;
193 discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
196 if (!discoveryURL.first)
197 discoveryURL.second = m_url;
198 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
200 // Compute the return URL. We start with a self-referential link.
201 string returnURL=request.getHandlerURL(target.c_str());
202 pair<bool,const char*> thisloc = getString("Location");
203 if (thisloc.first) returnURL += thisloc.second;
204 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
207 // We may already have RelayState set if we looped back here,
208 // but just in case target is a resource, we reset it back.
209 option = request.getParameter("target");
213 preserveRelayState(request.getApplication(), request, target);
215 preservePostData(request.getApplication(), request, request, target.c_str());
217 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
219 // Now the hard part. The base assumption is to append the entire query string, if any,
220 // to the self-link. But we want to replace target with the RelayState-preserved value
221 // to hide it from the DS.
222 const char* query = request.getQueryString();
224 // See if it starts with target.
225 if (!strncmp(query, "target=", 7)) {
226 // We skip this altogether and advance the query past it to the first separator.
227 query = strchr(query, '&');
228 // If we still have more, just append it.
229 if (query && *(++query))
230 returnURL = returnURL + '&' + query;
233 // There's something in the query before target appears, so we have to find it.
234 thisloc.second = strstr(query,"&target=");
235 if (thisloc.second) {
236 // We found it, so first append everything up to it.
238 returnURL.append(query, thisloc.second - query);
239 query = thisloc.second + 8; // move up just past the equals sign.
240 thisloc.second = strchr(query, '&');
242 returnURL += thisloc.second;
245 // No target in the existing query, so just append it as is.
246 returnURL = returnURL + '&' + query;
251 // Now append the sanitized target as needed.
253 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
255 else if (!target.empty()) {
256 // For a virtual handler, we just append target to the return link.
257 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
260 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
261 "&return=" + urlenc->encode(returnURL.c_str());
263 req = req + "&returnIDParam=" + m_returnParam;
265 req += "&isPassive=true";
267 return make_pair(true, request.sendRedirect(req.c_str()));