85b65bba42bc89217ee6142d47e198a1ccabbaff
[shibboleth/sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.cpp
1 /*
2  *  Copyright 2001-2009 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 "SPRequest.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/SessionInitiator.h"
29
30 #include <xmltooling/XMLToolingConfig.h>
31 #include <xmltooling/impl/AnyElement.h>
32 #include <xmltooling/util/URLEncoder.h>
33
34 using namespace shibsp;
35 using namespace opensaml;
36 using namespace xmltooling;
37 using namespace std;
38
39 #ifndef SHIBSP_LITE
40 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataProvider.h>
42 using namespace opensaml::saml2md;
43 #endif
44
45 namespace shibsp {
46
47 #if defined (_MSC_VER)
48     #pragma warning( push )
49     #pragma warning( disable : 4250 )
50 #endif
51
52     class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
53     {
54     public:
55         SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
56                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL)
57 #ifndef SHIBSP_LITE
58                     ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
59 #endif
60         {
61             pair<bool,const char*> url = getString("URL");
62             if (!url.first)
63                 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
64             m_url = url.second;
65             url = getString("entityIDParam");
66             if (url.first)
67                 m_returnParam = url.second;
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())
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 = !strcmp(option,"true");
175
176         option = request.getParameter("discoveryURL");
177         if (option)
178             discoveryURL.second = option;
179     }
180     else {
181         // We're running as a "virtual handler" from within the filter.
182         // The target resource is the current one and everything else is
183         // defaulted or set by content policy.
184         target=request.getRequestURL();
185         pair<bool,bool> passopt = getBool("isPassive");
186         isPassive = passopt.first && passopt.second;
187         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
188     }
189
190     if (!discoveryURL.first)
191         discoveryURL.second = m_url;
192     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
193
194     // Compute the return URL. We start with a self-referential link.
195     string returnURL=request.getHandlerURL(target.c_str());
196     pair<bool,const char*> thisloc = getString("Location");
197     if (thisloc.first) returnURL += thisloc.second;
198     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
199
200     if (isHandler) {
201         // We may already have RelayState set if we looped back here,
202         // but just in case target is a resource, we reset it back.
203         option = request.getParameter("target");
204         if (option)
205             target = option;
206     }
207     preserveRelayState(request.getApplication(), request, target);
208     if (!isHandler)
209         preservePostData(request.getApplication(), request, request, target.c_str());
210
211     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
212     if (isHandler) {
213         // Now the hard part. The base assumption is to append the entire query string, if any,
214         // to the self-link. But we want to replace target with the RelayState-preserved value
215         // to hide it from the DS.
216         const char* query = request.getQueryString();
217         if (query) {
218             // See if it starts with target.
219             if (!strncmp(query, "target=", 7)) {
220                 // We skip this altogether and advance the query past it to the first separator.
221                 query = strchr(query, '&');
222                 // If we still have more, just append it.
223                 if (query && *(++query))
224                     returnURL = returnURL + '&' + query;
225             }
226             else {
227                 // There's something in the query before target appears, so we have to find it.
228                 thisloc.second = strstr(query,"&target=");
229                 if (thisloc.second) {
230                     // We found it, so first append everything up to it.
231                     returnURL += '&';
232                     returnURL.append(query, thisloc.second - query);
233                     query = thisloc.second + 8; // move up just past the equals sign.
234                     thisloc.second = strchr(query, '&');
235                     if (thisloc.second)
236                         returnURL += thisloc.second;
237                 }
238                 else {
239                     // No target in the existing query, so just append it as is.
240                     returnURL = returnURL + '&' + query;
241                 }
242             }
243         }
244
245         // Now append the sanitized target as needed.
246         if (!target.empty())
247             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
248     }
249     else if (!target.empty()) {
250         // For a virtual handler, we just append target to the return link.
251         returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
252     }
253
254     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
255         "&return=" + urlenc->encode(returnURL.c_str());
256     if (m_returnParam)
257         req = req + "&returnIDParam=" + m_returnParam;
258     if (isPassive)
259         req += "&isPassive=true";
260
261     return make_pair(true, request.sendRedirect(req.c_str()));
262 }