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