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 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataProvider.h>
42 using namespace opensaml::saml2md;
47 #if defined (_MSC_VER)
48 #pragma warning( push )
49 #pragma warning( disable : 4250 )
52 class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
55 SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
56 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL)
58 ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
61 pair<bool,const char*> url = getString("URL");
63 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
65 url = getString("entityIDParam");
67 m_returnParam = url.second;
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);
76 const char* loc = getString("Location").second;
77 string hurl(handlerURL);
81 auto_ptr_XMLCh widen(hurl.c_str());
82 ElementProxy* ep = new AnyElementImpl(m_discoNS.get(), LOCAL_NAME);
83 ep->setAttribute(xmltooling::QName(NULL,EndpointType::LOCATION_ATTRIB_NAME), widen.get());
84 ep->setAttribute(xmltooling::QName(NULL,EndpointType::BINDING_ATTRIB_NAME), m_discoNS.get());
85 pair<bool,const XMLCh*> ix = getXMLString("index");
86 ep->setAttribute(xmltooling::QName(NULL,IndexedEndpointType::INDEX_ATTRIB_NAME), ix.first ? ix.second : xmlconstants::XML_ONE);
88 Extensions* ext = role.getExtensions();
90 ext = ExtensionsBuilder::buildExtensions();
91 role.setExtensions(ext);
93 ext->getUnknownXMLObjects().push_back(ep);
99 const char* m_returnParam;
101 auto_ptr_XMLCh m_discoNS;
105 #if defined (_MSC_VER)
106 #pragma warning( pop )
109 SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
111 return new SAMLDSSessionInitiator(p.first, p.second);
116 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
118 // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
119 // anytime the IdP's metadata was wrong.
120 if (!entityID.empty())
121 return make_pair(false,0L);
125 bool isPassive=false;
126 const Application& app=request.getApplication();
127 pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
130 option = request.getParameter("SAMLDS");
131 if (option && !strcmp(option,"1")) {
132 saml2md::MetadataException ex("No identity provider was selected by user.");
133 ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
134 ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
138 option = request.getParameter("target");
141 recoverRelayState(request.getApplication(), request, request, target, false);
143 option = request.getParameter("isPassive");
145 isPassive = !strcmp(option,"true");
147 option = request.getParameter("discoveryURL");
149 discoveryURL.second = option;
152 // We're running as a "virtual handler" from within the filter.
153 // The target resource is the current one and everything else is
154 // defaulted or set by content policy.
155 target=request.getRequestURL();
156 pair<bool,bool> passopt = getBool("isPassive");
157 isPassive = passopt.first && passopt.second;
158 discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
161 if (!discoveryURL.first)
162 discoveryURL.second = m_url;
163 m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
165 // Compute the return URL. We start with a self-referential link.
166 string returnURL=request.getHandlerURL(target.c_str());
167 pair<bool,const char*> thisloc = getString("Location");
168 if (thisloc.first) returnURL += thisloc.second;
169 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
172 // We may already have RelayState set if we looped back here,
173 // but just in case target is a resource, we reset it back.
174 option = request.getParameter("target");
178 preserveRelayState(request.getApplication(), request, target);
180 preservePostData(request.getApplication(), request, request, target.c_str());
182 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
184 // Now the hard part. The base assumption is to append the entire query string, if any,
185 // to the self-link. But we want to replace target with the RelayState-preserved value
186 // to hide it from the DS.
187 const char* query = request.getQueryString();
189 // See if it starts with target.
190 if (!strncmp(query, "target=", 7)) {
191 // We skip this altogether and advance the query past it to the first separator.
192 query = strchr(query, '&');
193 // If we still have more, just append it.
194 if (query && *(++query))
195 returnURL = returnURL + '&' + query;
198 // There's something in the query before target appears, so we have to find it.
199 thisloc.second = strstr(query,"&target=");
200 if (thisloc.second) {
201 // We found it, so first append everything up to it.
203 returnURL.append(query, thisloc.second - query);
204 query = thisloc.second + 8; // move up just past the equals sign.
205 thisloc.second = strchr(query, '&');
207 returnURL += thisloc.second;
210 // No target in the existing query, so just append it as is.
211 returnURL = returnURL + '&' + query;
216 // Now append the sanitized target as needed.
218 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
220 else if (!target.empty()) {
221 // For a virtual handler, we just append target to the return link.
222 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
225 string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
226 "&return=" + urlenc->encode(returnURL.c_str());
228 req = req + "&returnIDParam=" + m_returnParam;
230 req += "&isPassive=true";
232 return make_pair(true, request.sendRedirect(req.c_str()));