2 * Copyright 2001-2009 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 "SPRequest.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/SessionInitiator.h"
30 #include <xmltooling/XMLToolingConfig.h>
31 #include <xmltooling/impl/AnyElement.h>
32 #include <xmltooling/util/URLEncoder.h>
34 using namespace shibsp;
35 using namespace opensaml;
36 using namespace xmltooling;
40 using namespace opensaml::saml2md;
45 #if defined (_MSC_VER)
46 #pragma warning( push )
47 #pragma warning( disable : 4250 )
50 class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
53 SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
54 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL)
56 ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
59 pair<bool,const char*> url = getString("URL");
61 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
63 url = getString("entityIDParam");
65 m_returnParam = url.second;
67 virtual ~SAMLDSSessionInitiator() {}
69 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
72 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
73 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);
74 const char* loc = getString("Location").second;
75 string hurl(handlerURL);
79 auto_ptr_XMLCh widen(hurl.c_str());
80 ElementProxy* ep = new AnyElementImpl(m_discoNS.get(), LOCAL_NAME);
81 ep->setAttribute(xmltooling::QName(NULL,EndpointType::LOCATION_ATTRIB_NAME), widen.get());
82 ep->setAttribute(xmltooling::QName(NULL,EndpointType::BINDING_ATTRIB_NAME), m_discoNS.get());
83 pair<bool,const XMLCh*> ix = getXMLString("index");
84 ep->setAttribute(xmltooling::QName(NULL,IndexedEndpointType::INDEX_ATTRIB_NAME), ix.first ? ix.second : xmlconstants::XML_ONE);
86 Extensions* ext = role.getExtensions();
88 ext = ExtensionsBuilder::buildExtensions();
89 role.setExtensions(ext);
91 ext->getUnknownXMLObjects().push_back(ep);
97 const char* m_returnParam;
99 auto_ptr_XMLCh m_discoNS;
103 #if defined (_MSC_VER)
104 #pragma warning( pop )
107 SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
109 return new SAMLDSSessionInitiator(p.first, p.second);
114 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
116 // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
117 // anytime the IdP's metadata was wrong.
118 if (!entityID.empty())
119 return make_pair(false,0L);
123 bool isPassive=false;
124 const Application& app=request.getApplication();
125 pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
128 option = request.getParameter("SAMLDS");
129 if (option && !strcmp(option,"1")) {
130 saml2md::MetadataException ex("No identity provider was selected by user.");
131 ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
132 ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
136 option = request.getParameter("target");
139 recoverRelayState(request.getApplication(), request, request, target, false);
141 option = request.getParameter("isPassive");
143 isPassive = !strcmp(option,"true");
145 option = request.getParameter("discoveryURL");
147 discoveryURL.second = option;
150 // We're running as a "virtual handler" from within the filter.
151 // The target resource is the current one and everything else is
152 // defaulted or set by content policy.
153 target=request.getRequestURL();
154 pair<bool,bool> passopt = getBool("isPassive");
155 isPassive = passopt.first && passopt.second;
156 discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
159 if (!discoveryURL.first)
160 discoveryURL.second = m_url;
161 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
163 // Compute the return URL. We start with a self-referential link.
164 string returnURL=request.getHandlerURL(target.c_str());
165 pair<bool,const char*> thisloc = getString("Location");
166 if (thisloc.first) returnURL += thisloc.second;
167 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
170 // We may already have RelayState set if we looped back here,
171 // but just in case target is a resource, we reset it back.
172 option = request.getParameter("target");
176 preserveRelayState(request.getApplication(), request, target);
178 preservePostData(request.getApplication(), request, request, target.c_str());
180 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
182 // Now the hard part. The base assumption is to append the entire query string, if any,
183 // to the self-link. But we want to replace target with the RelayState-preserved value
184 // to hide it from the DS.
185 const char* query = request.getQueryString();
187 // See if it starts with target.
188 if (!strncmp(query, "target=", 7)) {
189 // We skip this altogether and advance the query past it to the first separator.
190 query = strchr(query, '&');
191 // If we still have more, just append it.
192 if (query && *(++query))
193 returnURL = returnURL + '&' + query;
196 // There's something in the query before target appears, so we have to find it.
197 thisloc.second = strstr(query,"&target=");
198 if (thisloc.second) {
199 // We found it, so first append everything up to it.
201 returnURL.append(query, thisloc.second - query);
202 query = thisloc.second + 8; // move up just past the equals sign.
203 thisloc.second = strchr(query, '&');
205 returnURL += thisloc.second;
208 // No target in the existing query, so just append it as is.
209 returnURL = returnURL + '&' + query;
214 // Now append the sanitized target as needed.
216 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
218 else if (!target.empty()) {
219 // For a virtual handler, we just append target to the return link.
220 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
223 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
224 "&return=" + urlenc->encode(returnURL.c_str());
226 req = req + "&returnIDParam=" + m_returnParam;
228 req += "&isPassive=true";
230 return make_pair(true, request.sendRedirect(req.c_str()));