2 * Copyright 2001-2007 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();
127 option = request.getParameter("SAMLDS");
128 if (option && !strcmp(option,"1")) {
129 saml2md::MetadataException ex("No identity provider was selected by user.");
130 ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
131 ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
135 option = request.getParameter("target");
138 recoverRelayState(request.getApplication(), request, request, target, false);
140 option = request.getParameter("isPassive");
142 isPassive = !strcmp(option,"true");
145 // We're running as a "virtual handler" from within the filter.
146 // The target resource is the current one and everything else is
147 // defaulted or set by content policy.
148 target=request.getRequestURL();
149 pair<bool,bool> passopt = getBool("isPassive");
150 isPassive = passopt.first && passopt.second;
153 m_log.debug("sending request to SAMLDS (%s)", m_url);
155 // Compute the return URL. We start with a self-referential link.
156 string returnURL=request.getHandlerURL(target.c_str());
157 pair<bool,const char*> thisloc = getString("Location");
158 if (thisloc.first) returnURL += thisloc.second;
159 returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
162 // We may already have RelayState set if we looped back here,
163 // but just in case target is a resource, we reset it back.
164 option = request.getParameter("target");
168 preserveRelayState(request.getApplication(), request, target);
170 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
172 // Now the hard part. The base assumption is to append the entire query string, if any,
173 // to the self-link. But we want to replace target with the RelayState-preserved value
174 // to hide it from the DS.
175 const char* query = request.getQueryString();
177 // See if it starts with target.
178 if (!strncmp(query, "target=", 7)) {
179 // We skip this altogether and advance the query past it to the first separator.
180 query = strchr(query, '&');
181 // If we still have more, just append it.
182 if (query && *(++query))
183 returnURL = returnURL + '&' + query;
186 // There's something in the query before target appears, so we have to find it.
187 thisloc.second = strstr(query,"&target=");
188 if (thisloc.second) {
189 // We found it, so first append everything up to it.
191 returnURL.append(query, thisloc.second - query);
192 query = thisloc.second + 8; // move up just past the equals sign.
193 thisloc.second = strchr(query, '&');
195 returnURL += thisloc.second;
198 // No target in the existing query, so just append it as is.
199 returnURL = returnURL + '&' + query;
204 // Now append the sanitized target as needed.
206 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
208 else if (!target.empty()) {
209 // For a virtual handler, we just append target to the return link.
210 returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
213 string req=string(m_url) + (strchr(m_url,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
214 "&return=" + urlenc->encode(returnURL.c_str());
216 req = req + "&returnIDParam=" + m_returnParam;
218 req += "&isPassive=true";
220 return make_pair(true, request.sendRedirect(req.c_str()));