10de535da37b2367aa2a076f8b3f09784609f819
[shibboleth/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     pair<bool,const char*> prop;
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         prop.second = request.getParameter("SAMLDS");
160         if (prop.second && !strcmp(prop.second,"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         prop = getString("target", request);
168         if (prop.first)
169             target = prop.second;
170
171         recoverRelayState(app, request, request, target, false);
172
173         pair<bool,bool> passopt = getBool("isPassive", request);
174         isPassive = passopt.first && passopt.second;
175
176         prop.second = request.getParameter("discoveryURL");
177         if (prop.second && *prop.second)
178             discoveryURL.second = prop.second;
179     }
180     else {
181         // Check for a hardwired target value in the map or handler.
182         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
183         if (prop.first)
184             target = prop.second;
185         else
186             target = request.getRequestURL();
187
188         pair<bool,bool> passopt = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
189         isPassive = passopt.first && passopt.second;
190         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
191     }
192
193     if (!discoveryURL.first)
194         discoveryURL.second = m_url;
195     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
196
197     // Compute the return URL. We start with a self-referential link.
198     string returnURL = request.getHandlerURL(target.c_str());
199     prop = getString("Location");
200     if (prop.first)
201         returnURL += prop.second;
202     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
203
204     if (isHandler) {
205         // We may already have RelayState set if we looped back here,
206         // but we've turned it back into a resource by this point, so if there's
207         // a target on the URL, reset to that value.
208         prop.second = request.getParameter("target");
209         if (prop.second && *prop.second)
210             target = prop.second;
211     }
212     preserveRelayState(app, request, target);
213     if (!isHandler)
214         preservePostData(app, request, request, target.c_str());
215
216     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
217     if (isHandler) {
218         // Now the hard part. The base assumption is to append the entire query string, if any,
219         // to the self-link. But we want to replace target with the RelayState-preserved value
220         // to hide it from the DS.
221         const char* query = request.getQueryString();
222         if (query) {
223             // See if it starts with target.
224             if (!strncmp(query, "target=", 7)) {
225                 // We skip this altogether and advance the query past it to the first separator.
226                 query = strchr(query, '&');
227                 // If we still have more, just append it.
228                 if (query && *(++query))
229                     returnURL = returnURL + '&' + query;
230             }
231             else {
232                 // There's something in the query before target appears, so we have to find it.
233                 prop.second = strstr(query, "&target=");
234                 if (prop.second) {
235                     // We found it, so first append everything up to it.
236                     returnURL += '&';
237                     returnURL.append(query, prop.second - query);
238                     query = prop.second + 8; // move up just past the equals sign.
239                     prop.second = strchr(query, '&');
240                     if (prop.second)
241                         returnURL += prop.second;
242                 }
243                 else {
244                     // No target in the existing query, so just append it as is.
245                     returnURL = returnURL + '&' + query;
246                 }
247             }
248         }
249
250         // Now append the sanitized target as needed.
251         if (!target.empty())
252             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
253     }
254     else if (!target.empty()) {
255         // For a virtual handler, we just append target to the return link.
256         returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
257     }
258
259     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
260         "&return=" + urlenc->encode(returnURL.c_str());
261     if (m_returnParam)
262         req = req + "&returnIDParam=" + m_returnParam;
263     if (isPassive)
264         req += "&isPassive=true";
265
266     return make_pair(true, request.sendRedirect(req.c_str()));
267 }