https://issues.shibboleth.net/jira/browse/SSPCPP-244
[shibboleth/cpp-sp.git] / shibsp / handler / impl / WAYFSessionInitiator.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  * WAYFSessionInitiator.cpp
19  * 
20  * Shibboleth WAYF 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 #ifndef SHIBSP_LITE
31 # include <saml/util/SAMLConstants.h>
32 #else
33 # include "lite/SAMLConstants.h"
34 #endif
35
36 #include <ctime>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/URLEncoder.h>
39
40 using namespace shibsp;
41 using namespace opensaml;
42 using namespace xmltooling;
43 using namespace std;
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 WAYFSessionInitiator : public SessionInitiator, public AbstractHandler
53     {
54     public:
55         WAYFSessionInitiator(const DOMElement* e, const char* appId)
56                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.WAYF"), NULL, &m_remapper), m_url(NULL) {
57             pair<bool,const char*> url = getString("URL");
58             if (!url.first)
59                 throw ConfigurationException("WAYF SessionInitiator requires a URL property.");
60             m_url = url.second;
61         }
62         virtual ~WAYFSessionInitiator() {}
63         
64         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
65
66     private:
67         const char* m_url;
68     };
69
70 #if defined (_MSC_VER)
71     #pragma warning( pop )
72 #endif
73
74     SessionInitiator* SHIBSP_DLLLOCAL WAYFSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
75     {
76         return new WAYFSessionInitiator(p.first, p.second);
77     }
78
79 };
80
81 pair<bool,long> WAYFSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
82 {
83     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a WAYF
84     // anytime the IdP's metadata was wrong.
85     if (!entityID.empty())
86         return make_pair(false,0L);
87
88     string target;
89     string postData;
90     const char* option;
91     const Handler* ACS=NULL;
92     const Application& app=request.getApplication();
93     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
94
95     if (isHandler) {
96         option=request.getParameter("acsIndex");
97         if (option) {
98             ACS=app.getAssertionConsumerServiceByIndex(atoi(option));
99             if (!ACS)
100                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
101         }
102
103         option = request.getParameter("target");
104         if (option)
105             target = option;
106         recoverRelayState(request.getApplication(), request, request, target, false);
107
108         option = request.getParameter("discoveryURL");
109         if (option)
110             discoveryURL.second = option;
111     }
112     else {
113         // We're running as a "virtual handler" from within the filter.
114         // The target resource is the current one and everything else is defaulted.
115         target=request.getRequestURL();
116         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
117     }
118     
119     // Since we're not passing by index, we need to fully compute the return URL.
120     if (!ACS) {
121         pair<bool,unsigned int> index = getUnsignedInt("acsIndex");
122         if (index.first) {
123             ACS = app.getAssertionConsumerServiceByIndex(index.second);
124             if (!ACS)
125                 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
126         }
127         if (!ACS)
128             ACS = app.getDefaultAssertionConsumerService();
129     }
130
131     // Validate the ACS for use with this protocol.
132     pair<bool,const char*> ACSbinding = ACS ? ACS->getString("Binding") : pair<bool,const char*>(false,NULL);
133     if (ACSbinding.first) {
134         pair<bool,const char*> compatibleBindings = getString("compatibleBindings");
135         if (compatibleBindings.first && strstr(compatibleBindings.second, ACSbinding.second) == NULL) {
136             m_log.error("configured or requested ACS has non-SAML 1.x binding");
137             throw ConfigurationException("Configured or requested ACS has non-SAML 1.x binding ($1).", params(1, ACSbinding.second));
138         }
139         else if (strcmp(ACSbinding.second, samlconstants::SAML1_PROFILE_BROWSER_POST) &&
140                  strcmp(ACSbinding.second, samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT)) {
141             m_log.error("configured or requested ACS has non-SAML 1.x binding");
142             throw ConfigurationException("Configured or requested ACS has non-SAML 1.x binding ($1).", params(1, ACSbinding.second));
143         }
144     }
145
146     if (!discoveryURL.first)
147         discoveryURL.second = m_url;
148     m_log.debug("sending request to WAYF (%s)", discoveryURL.second);
149
150     // Compute the ACS URL. We add the ACS location to the base handlerURL.
151     string ACSloc=request.getHandlerURL(target.c_str());
152     pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
153     if (loc.first) ACSloc+=loc.second;
154
155     if (isHandler) {
156         // We may already have RelayState set if we looped back here,
157         // but just in case target is a resource, we reset it back.
158         option = request.getParameter("target");
159         if (option)
160             target = option;
161     }
162     preserveRelayState(request.getApplication(), request, target);
163     if (!isHandler)
164         preservePostData(request.getApplication(), request, request, target.c_str());
165
166     // WAYF requires a target value.
167     if (target.empty())
168         target = "default";
169
170     char timebuf[16];
171     sprintf(timebuf,"%lu",time(NULL));
172     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
173     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "shire=" + urlenc->encode(ACSloc.c_str()) +
174         "&time=" + timebuf + "&target=" + urlenc->encode(target.c_str()) +
175         "&providerId=" + urlenc->encode(app.getString("entityID").second);
176
177     return make_pair(true, request.sendRedirect(req.c_str()));
178 }