https://issues.shibboleth.net/jira/browse/SSPCPP-584
[shibboleth/cpp-sp.git] / fastcgi / shibauthorizer.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /* shibauthorizer.cpp - Shibboleth FastCGI Authorizer
22
23    Andre Cruz
24 */
25
26 #define SHIBSP_LITE
27 #include "config_win32.h"
28
29 #define _CRT_NONSTDC_NO_DEPRECATE 1
30 #define _CRT_SECURE_NO_DEPRECATE 1
31 #define _SCL_SECURE_NO_WARNINGS 1
32
33 #include <shibsp/AbstractSPRequest.h>
34 #include <shibsp/SPConfig.h>
35 #include <shibsp/ServiceProvider.h>
36 #include <xmltooling/unicode.h>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/XMLConstants.h>
40 #include <xmltooling/util/XMLHelper.h>
41 #include <xercesc/util/XMLUniDefs.hpp>
42
43 #include <stdexcept>
44 #include <stdlib.h>
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 # include <sys/mman.h>
48 #endif
49 #include <fcgio.h>
50
51 using namespace shibsp;
52 using namespace xmltooling;
53 using namespace xercesc;
54 using namespace std;
55
56 static const XMLCh path[] =     UNICODE_LITERAL_4(p,a,t,h);
57 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
58
59 typedef enum {
60     SHIB_RETURN_OK,
61     SHIB_RETURN_KO,
62     SHIB_RETURN_DONE
63 } shib_return_t;
64
65 class ShibTargetFCGIAuth : public AbstractSPRequest
66 {
67     FCGX_Request* m_req;
68     int m_port;
69     string m_scheme,m_hostname;
70     multimap<string,string> m_response_headers;
71 public:
72     map<string,string> m_request_headers;
73
74     ShibTargetFCGIAuth(FCGX_Request* req, const char* scheme=nullptr, const char* hostname=nullptr, int port=0)
75             : AbstractSPRequest(SHIBSP_LOGCAT".FastCGI"), m_req(req) {
76         const char* server_name_str = hostname;
77         if (!server_name_str || !*server_name_str)
78             server_name_str = FCGX_GetParam("SERVER_NAME", req->envp);
79         m_hostname = server_name_str;
80
81         m_port = port;
82         if (!m_port) {
83             char* server_port_str = FCGX_GetParam("SERVER_PORT", req->envp);
84             m_port = strtol(server_port_str, &server_port_str, 10);
85             if (*server_port_str) {
86                 cerr << "can't parse SERVER_PORT (" << FCGX_GetParam("SERVER_PORT", req->envp) << ")" << endl;
87                 throw runtime_error("Unable to determine server port.");
88             }
89         }
90
91         const char* server_scheme_str = scheme;
92         if (!server_scheme_str || !*server_scheme_str)
93             server_scheme_str = (m_port == 443 || m_port == 8443) ? "https" : "http";
94         m_scheme = server_scheme_str;
95
96         setRequestURI(FCGX_GetParam("REQUEST_URI", m_req->envp));
97     }
98
99     ~ShibTargetFCGIAuth() { }
100
101     const char* getScheme() const {
102         return m_scheme.c_str();
103     }
104     const char* getHostname() const {
105         return m_hostname.c_str();
106     }
107     int getPort() const {
108         return m_port;
109     }
110     const char* getMethod() const {
111         return FCGX_GetParam("REQUEST_METHOD", m_req->envp);
112     }
113     string getContentType() const {
114         const char* s = FCGX_GetParam("CONTENT_TYPE", m_req->envp);
115         return s ? s : "";
116     }
117     long getContentLength() const {
118         const char* s = FCGX_GetParam("CONTENT_LENGTH", m_req->envp);
119         return s ? atol(s) : 0;
120     }
121     string getRemoteAddr() const {
122         string ret = AbstractSPRequest::getRemoteAddr();
123         if (!ret.empty())
124             return ret;
125         const char* s = FCGX_GetParam("REMOTE_ADDR", m_req->envp);
126         return s ? s : "";
127     }
128     void log(SPLogLevel level, const string& msg) const {
129         AbstractSPRequest::log(level,msg);
130         if (level >= SPError)
131             cerr << "shib: " << msg;
132     }
133     void clearHeader(const char* rawname, const char* cginame) {
134         // No need, since we use environment variables.
135     }
136     void setHeader(const char* name, const char* value) {
137         if (value)
138             m_request_headers[name] = value;
139         else
140             m_request_headers.erase(name);
141     }
142     string getHeader(const char* name) const {
143         // Look in the local map first.
144         map<string,string>::const_iterator i = m_request_headers.find(name);
145         if (i != m_request_headers.end())
146             return i->second;
147         // Nothing set locally and this isn't a "secure" call, so check the request.
148         string hdr("HTTP_");
149         for (; *name; ++name) {
150             if (*name=='-')
151                 hdr += '_';
152             else
153                 hdr += toupper(*name);
154         }
155         char* s = FCGX_GetParam(hdr.c_str(), m_req->envp);
156         return s ? s : "";
157     }
158     string getSecureHeader(const char* name) const {
159         // Look in the local map only.
160         map<string,string>::const_iterator i = m_request_headers.find(name);
161         if (i != m_request_headers.end())
162             return i->second;
163         return "";
164     }
165     void setRemoteUser(const char* user) {
166         if (user)
167             m_request_headers["REMOTE_USER"] = user;
168         else
169             m_request_headers.erase("REMOTE_USER");
170     }
171     string getRemoteUser() const {
172         map<string,string>::const_iterator i = m_request_headers.find("REMOTE_USER");
173         if (i != m_request_headers.end())
174             return i->second;
175         else {
176             char* remote_user = FCGX_GetParam("REMOTE_USER", m_req->envp);
177             if (remote_user)
178                 return remote_user;
179         }
180         return "";
181     }
182     void setAuthType(const char* authtype) {
183         if (authtype)
184             m_request_headers["AUTH_TYPE"] = authtype;
185         else
186             m_request_headers.erase("AUTH_TYPE");
187     }
188     string getAuthType() const {
189         map<string,string>::const_iterator i = m_request_headers.find("AUTH_TYPE");
190         if (i != m_request_headers.end())
191             return i->second;
192         else {
193             char* auth_type = FCGX_GetParam("AUTH_TYPE", m_req->envp);
194             if (auth_type)
195                 return auth_type;
196         }
197         return "";
198     }
199     void setResponseHeader(const char* name, const char* value) {
200         HTTPResponse::setResponseHeader(name, value);
201         // Set for later.
202         if (value)
203             m_response_headers.insert(make_pair(name,value));
204         else
205             m_response_headers.erase(name);
206     }
207     const char* getQueryString() const {
208         return FCGX_GetParam("QUERY_STRING", m_req->envp);
209     }
210     const char* getRequestBody() const {
211         throw runtime_error("getRequestBody not implemented by FastCGI authorizer.");
212     }
213
214     long sendResponse(istream& in, long status) {
215         string hdr = string("Connection: close\r\n");
216         for (multimap<string,string>::const_iterator i=m_response_headers.begin(); i!=m_response_headers.end(); ++i)
217             hdr += i->first + ": " + i->second + "\r\n";
218
219         // We can't return 200 OK here or else the filter is bypassed
220         // so custom Shib errors will get turned into a generic page.
221         const char* codestr="Status: 500 Server Error";
222         switch (status) {
223             case XMLTOOLING_HTTP_STATUS_NOTMODIFIED:    codestr="Status: 304 Not Modified"; break;
224             case XMLTOOLING_HTTP_STATUS_UNAUTHORIZED:   codestr="Status: 401 Authorization Required"; break;
225             case XMLTOOLING_HTTP_STATUS_FORBIDDEN:      codestr="Status: 403 Forbidden"; break;
226             case XMLTOOLING_HTTP_STATUS_NOTFOUND:       codestr="Status: 404 Not Found"; break;
227         }
228         cout << codestr << "\r\n" << hdr << "\r\n";
229         char buf[1024];
230         while (in) {
231             in.read(buf,1024);
232             cout.write(buf, in.gcount());
233         }
234         return SHIB_RETURN_DONE;
235     }
236
237     long sendRedirect(const char* url) {
238         HTTPResponse::sendRedirect(url);
239         string hdr=string("Status: 302 Please Wait\r\nLocation: ") + url + "\r\n"
240           "Content-Type: text/html\r\n"
241           "Content-Length: 40\r\n"
242           "Expires: Wed, 01 Jan 1997 12:00:00 GMT\r\n"
243           "Cache-Control: private,no-store,no-cache,max-age=0\r\n";
244         for (multimap<string,string>::const_iterator i=m_response_headers.begin(); i!=m_response_headers.end(); ++i)
245             hdr += i->first + ": " + i->second + "\r\n";
246         hdr += "\r\n";
247
248         cout << hdr << "<HTML><BODY>Redirecting...</BODY></HTML>";
249         return SHIB_RETURN_DONE;
250     }
251
252     long returnDecline() {
253         return SHIB_RETURN_KO;
254     }
255
256     long returnOK() {
257         return SHIB_RETURN_OK;
258     }
259
260     const vector<string>& getClientCertificates() const {
261         static vector<string> g_NoCerts;
262         return g_NoCerts;
263     }
264 };
265
266 static void print_ok(const map<string,string>& headers)
267 {
268     cout << "Status: 200 OK" << "\r\n";
269     for (map<string,string>::const_iterator iter = headers.begin(); iter != headers.end(); iter++) {
270         cout << "Variable-" << iter->first << ": " << iter->second << "\r\n";
271     }
272     cout << "\r\n";
273 }
274
275 static void print_error(const char* msg)
276 {
277     cout << "Status: 500 Server Error" << "\r\n\r\n" << msg;
278 }
279
280 int main(void)
281 {
282     SPConfig* g_Config=&SPConfig::getConfig();
283     g_Config->setFeatures(
284         SPConfig::Listener |
285         SPConfig::Caching |
286         SPConfig::RequestMapping |
287         SPConfig::InProcess |
288         SPConfig::Logging |
289         SPConfig::Handlers
290         );
291     if (!g_Config->init()) {
292         cerr << "failed to initialize Shibboleth libraries" << endl;
293         exit(1);
294     }
295
296     try {
297         if (!g_Config->instantiate(nullptr, true))
298             throw runtime_error("unknown error");
299     }
300     catch (exception& ex) {
301         g_Config->term();
302         cerr << "exception while initializing Shibboleth configuration: " << ex.what() << endl;
303         exit(1);
304     }
305
306     string g_ServerScheme;
307     string g_ServerName;
308     int g_ServerPort=0;
309
310     // Load "authoritative" URL fields.
311     char* var = getenv("SHIBSP_SERVER_NAME");
312     if (var)
313         g_ServerName = var;
314     var = getenv("SHIBSP_SERVER_SCHEME");
315     if (var)
316         g_ServerScheme = var;
317     var = getenv("SHIBSP_SERVER_PORT");
318     if (var)
319         g_ServerPort = atoi(var);
320
321     streambuf* cout_streambuf = cout.rdbuf();
322     streambuf* cerr_streambuf = cerr.rdbuf();
323
324     FCGX_Request request;
325
326     FCGX_Init();
327     FCGX_InitRequest(&request, 0, 0);
328
329     cout << "Shibboleth initialization complete. Starting request loop." << endl;
330     while (FCGX_Accept_r(&request) == 0)
331     {
332         // Note that the default bufsize (0) will cause the use of iostream
333         // methods that require positioning (such as peek(), seek(),
334         // unget() and putback()) to fail (in favour of more efficient IO).
335         fcgi_streambuf cout_fcgi_streambuf(request.out);
336         fcgi_streambuf cerr_fcgi_streambuf(request.err);
337
338         cout.rdbuf(&cout_fcgi_streambuf);
339         cerr.rdbuf(&cerr_fcgi_streambuf);
340
341         try {
342             xmltooling::NDC ndc("FastCGI shibauthorizer");
343             ShibTargetFCGIAuth sta(&request, g_ServerScheme.c_str(), g_ServerName.c_str(), g_ServerPort);
344
345             pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta);
346             if (res.first) {
347                 sta.log(SPRequest::SPDebug, "shib: doAuthentication handled the request");
348                 switch(res.second) {
349                     case SHIB_RETURN_OK:
350                         print_ok(sta.m_request_headers);
351                         continue;
352
353                     case SHIB_RETURN_KO:
354                         print_ok(sta.m_request_headers);
355                         continue;
356
357                     case SHIB_RETURN_DONE:
358                         continue;
359
360                     default:
361                         cerr << "shib: doAuthentication returned an unexpected result: " << res.second << endl;
362                         print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
363                         continue;
364                 }
365             }
366
367             res = sta.getServiceProvider().doExport(sta);
368             if (res.first) {
369                 sta.log(SPRequest::SPDebug, "shib: doExport handled request");
370                 switch(res.second) {
371                     case SHIB_RETURN_OK:
372                         print_ok(sta.m_request_headers);
373                         continue;
374
375                     case SHIB_RETURN_KO:
376                         print_ok(sta.m_request_headers);
377                         continue;
378
379                     case SHIB_RETURN_DONE:
380                         continue;
381
382                     default:
383                         cerr << "shib: doExport returned an unexpected result: " << res.second << endl;
384                         print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
385                         continue;
386                 }
387             }
388
389             res = sta.getServiceProvider().doAuthorization(sta);
390             if (res.first) {
391                 sta.log(SPRequest::SPDebug, "shib: doAuthorization handled request");
392                 switch(res.second) {
393                     case SHIB_RETURN_OK:
394                         print_ok(sta.m_request_headers);
395                         continue;
396
397                     case SHIB_RETURN_KO:
398                         print_ok(sta.m_request_headers);
399                         continue;
400
401                     case SHIB_RETURN_DONE:
402                         continue;
403
404                     default:
405                         cerr << "shib: doAuthorization returned an unexpected result: " << res.second << endl;
406                         print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
407                         continue;
408                 }
409             }
410
411             print_ok(sta.m_request_headers);
412
413         }
414         catch (exception& e) {
415             cerr << "shib: FastCGI authorizer caught an exception: " << e.what() << endl;
416             print_error("<html><body>FastCGI Shibboleth authorizer caught an exception, check log for details.</body></html>");
417         }
418
419         // If the output streambufs had non-zero bufsizes and
420         // were constructed outside of the accept loop (i.e.
421         // their destructor won't be called here), they would
422         // have to be flushed here.
423     }
424     cout << "Request loop ended." << endl;
425
426     cout.rdbuf(cout_streambuf);
427     cerr.rdbuf(cerr_streambuf);
428
429     if (g_Config)
430         g_Config->term();
431
432     return 0;
433 }