1c0a7e306af3ecb262cfc26175633202f3c47eb0
[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             const char* loc = getString("Location").second;
77             string hurl(handlerURL);
78             if (*loc != '/')
79                 hurl += '/';
80             hurl += loc;
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);
87
88             Extensions* ext = role.getExtensions();
89             if (!ext) {
90                 ext = ExtensionsBuilder::buildExtensions();
91                 role.setExtensions(ext);
92             }
93             ext->getUnknownXMLObjects().push_back(ep);
94         }
95 #endif
96
97     private:
98         const char* m_url;
99         const char* m_returnParam;
100 #ifndef SHIBSP_LITE
101         auto_ptr_XMLCh m_discoNS;
102 #endif
103     };
104
105 #if defined (_MSC_VER)
106     #pragma warning( pop )
107 #endif
108
109     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
110     {
111         return new SAMLDSSessionInitiator(p.first, p.second);
112     }
113
114 };
115
116 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
117 {
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);
122
123     string target;
124     const char* option;
125     bool isPassive=false;
126     const Application& app=request.getApplication();
127     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
128
129     if (isHandler) {
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");
135             ex.raise();
136         }
137
138         option = request.getParameter("target");
139         if (option)
140             target = option;
141         recoverRelayState(request.getApplication(), request, request, target, false);
142
143         option = request.getParameter("isPassive");
144         if (option)
145             isPassive = !strcmp(option,"true");
146
147         option = request.getParameter("discoveryURL");
148         if (option)
149             discoveryURL.second = option;
150     }
151     else {
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");
159     }
160
161     if (!discoveryURL.first)
162         discoveryURL.second = m_url;
163     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
164
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
170
171     if (isHandler) {
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");
175         if (option)
176             target = option;
177     }
178     preserveRelayState(request.getApplication(), request, target);
179     if (!isHandler)
180         preservePostData(request.getApplication(), request, request, target.c_str());
181
182     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
183     if (isHandler) {
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();
188         if (query) {
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;
196             }
197             else {
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.
202                     returnURL += '&';
203                     returnURL.append(query, thisloc.second - query);
204                     query = thisloc.second + 8; // move up just past the equals sign.
205                     thisloc.second = strchr(query, '&');
206                     if (thisloc.second)
207                         returnURL += thisloc.second;
208                 }
209                 else {
210                     // No target in the existing query, so just append it as is.
211                     returnURL = returnURL + '&' + query;
212                 }
213             }
214         }
215
216         // Now append the sanitized target as needed.
217         if (!target.empty())
218             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
219     }
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());;
223     }
224
225     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
226         "&return=" + urlenc->encode(returnURL.c_str());
227     if (m_returnParam)
228         req = req + "&returnIDParam=" + m_returnParam;
229     if (isPassive)
230         req += "&isPassive=true";
231
232     return make_pair(true, request.sendRedirect(req.c_str()));
233 }