https://issues.shibboleth.net/jira/browse/SSPCPP-274
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * SAMLDSSessionInitiator.cpp
19  *
20  * SAML Discovery Service support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "handler/AbstractHandler.h"
27 #include "handler/SessionInitiator.h"
28
29 #include <xmltooling/XMLToolingConfig.h>
30 #include <xmltooling/impl/AnyElement.h>
31 #include <xmltooling/util/URLEncoder.h>
32
33 using namespace shibsp;
34 using namespace opensaml;
35 using namespace xmltooling;
36 using namespace std;
37
38 #ifndef SHIBSP_LITE
39 # include <saml/saml2/metadata/Metadata.h>
40 # include <saml/saml2/metadata/MetadataProvider.h>
41 using namespace opensaml::saml2md;
42 #endif
43
44 namespace shibsp {
45
46 #if defined (_MSC_VER)
47     #pragma warning( push )
48     #pragma warning( disable : 4250 )
49 #endif
50
51     class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
52     {
53     public:
54         SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
55                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL)
56 #ifndef SHIBSP_LITE
57                     ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
58 #endif
59         {
60             pair<bool,const char*> url = getString("URL");
61             if (!url.first)
62                 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
63             m_url = url.second;
64             url = getString("entityIDParam");
65             if (url.first)
66                 m_returnParam = url.second;
67             m_supportedOptions.insert("isPassive");
68         }
69         virtual ~SAMLDSSessionInitiator() {}
70
71         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
72
73 #ifndef SHIBSP_LITE
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
77             // Initial guess at index to use.
78             pair<bool,unsigned int> ix = getUnsignedInt("index");
79             if (!ix.first)
80                 ix.second = 1;
81
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);
89                         if (sub) {
90                             const XMLCh* val = sub->getAttribute(xmltooling::QName(NULL,IndexedEndpointType::INDEX_ATTRIB_NAME));
91                             if (val) {
92                                 int maxindex = XMLString::parseInt(val);
93                                 if (ix.second <= maxindex)
94                                     ix.second = maxindex + 1;
95                                 break;
96                             }
97                         }
98                     }
99                 }
100             }
101
102             const char* loc = getString("Location").second;
103             string hurl(handlerURL);
104             if (*loc != '/')
105                 hurl += '/';
106             hurl += loc;
107             auto_ptr_XMLCh widen(hurl.c_str());
108
109             ostringstream os;
110             os << ix.second;
111             auto_ptr_XMLCh widen2(os.str().c_str());
112
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();
118             if (!ext) {
119                 ext = ExtensionsBuilder::buildExtensions();
120                 role.setExtensions(ext);
121             }
122             ext->getUnknownXMLObjects().push_back(ep);
123         }
124 #endif
125
126     private:
127         const char* m_url;
128         const char* m_returnParam;
129 #ifndef SHIBSP_LITE
130         auto_ptr_XMLCh m_discoNS;
131 #endif
132     };
133
134 #if defined (_MSC_VER)
135     #pragma warning( pop )
136 #endif
137
138     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
139     {
140         return new SAMLDSSessionInitiator(p.first, p.second);
141     }
142
143 };
144
145 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
146 {
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);
151
152     string target;
153     const char* option;
154     bool isPassive=false;
155     const Application& app=request.getApplication();
156     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
157
158     if (isHandler) {
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");
164             ex.raise();
165         }
166
167         option = request.getParameter("target");
168         if (option)
169             target = option;
170         recoverRelayState(request.getApplication(), request, request, target, false);
171
172         option = request.getParameter("isPassive");
173         if (option)
174             isPassive = (*option=='t' || *option=='1');
175         else {
176             pair<bool,bool> passopt = getBool("isPassive");
177             isPassive = passopt.first && passopt.second;
178         }
179
180         option = request.getParameter("discoveryURL");
181         if (option)
182             discoveryURL.second = option;
183     }
184     else {
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");
190         if (!passopt.first)
191             passopt = getBool("isPassive");
192         isPassive = passopt.first && passopt.second;
193         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
194     }
195
196     if (!discoveryURL.first)
197         discoveryURL.second = m_url;
198     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
199
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
205
206     if (isHandler) {
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");
210         if (option)
211             target = option;
212     }
213     preserveRelayState(request.getApplication(), request, target);
214     if (!isHandler)
215         preservePostData(request.getApplication(), request, request, target.c_str());
216
217     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
218     if (isHandler) {
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();
223         if (query) {
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;
231             }
232             else {
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.
237                     returnURL += '&';
238                     returnURL.append(query, thisloc.second - query);
239                     query = thisloc.second + 8; // move up just past the equals sign.
240                     thisloc.second = strchr(query, '&');
241                     if (thisloc.second)
242                         returnURL += thisloc.second;
243                 }
244                 else {
245                     // No target in the existing query, so just append it as is.
246                     returnURL = returnURL + '&' + query;
247                 }
248             }
249         }
250
251         // Now append the sanitized target as needed.
252         if (!target.empty())
253             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
254     }
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());;
258     }
259
260     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
261         "&return=" + urlenc->encode(returnURL.c_str());
262     if (m_returnParam)
263         req = req + "&returnIDParam=" + m_returnParam;
264     if (isPassive)
265         req += "&isPassive=true";
266
267     return make_pair(true, request.sendRedirect(req.c_str()));
268 }