2 * Copyright 2001-2007 Internet2
\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
8 * http://www.apache.org/licenses/LICENSE-2.0
\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
17 /* shibauthorizer.cpp - Shibboleth FastCGI Authorizer
\r
23 #include "config_win32.h"
\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
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
39 #include <stdexcept>
\r
41 #ifdef HAVE_UNISTD_H
\r
42 # include <unistd.h>
\r
43 # include <sys/mman.h>
\r
47 using namespace shibsp;
\r
48 using namespace xmltooling;
\r
49 using namespace xercesc;
\r
50 using namespace std;
\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
61 class ShibTargetFCGIAuth : public AbstractSPRequest
\r
63 FCGX_Request* m_req;
\r
65 string m_scheme,m_hostname;
\r
66 multimap<string,string> m_response_headers;
\r
68 map<string,string> m_request_headers;
\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
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
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
92 setRequestURI(FCGX_GetParam("REQUEST_URI", m_req->envp));
\r
95 ~ShibTargetFCGIAuth() { }
\r
97 const char* getScheme() const {
\r
98 return m_scheme.c_str();
\r
100 const char* getHostname() const {
\r
101 return m_hostname.c_str();
\r
103 int getPort() const {
\r
106 const char* getMethod() const {
\r
107 return FCGX_GetParam("REQUEST_METHOD", m_req->envp);
\r
109 string getContentType() const {
\r
110 const char* s = FCGX_GetParam("CONTENT_TYPE", m_req->envp);
\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
117 string getRemoteAddr() const {
\r
118 const char* s = FCGX_GetParam("REMOTE_ADDR", m_req->envp);
\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
126 void clearHeader(const char* rawname, const char* cginame) {
\r
127 // No need, since we use environment variables.
\r
129 void setHeader(const char* name, const char* value) {
\r
131 m_request_headers[name] = value;
\r
133 m_request_headers.erase(name);
\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
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
146 hdr += toupper(*name);
\r
148 char* s = FCGX_GetParam(hdr.c_str(), m_req->envp);
\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
158 void setRemoteUser(const char* user) {
\r
160 m_request_headers["REMOTE_USER"] = user;
\r
162 m_request_headers.erase("REMOTE_USER");
\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
169 char* remote_user = FCGX_GetParam("REMOTE_USER", m_req->envp);
\r
171 return remote_user;
\r
175 void setResponseHeader(const char* name, const char* value) {
\r
178 m_response_headers.insert(make_pair(name,value));
\r
180 m_response_headers.erase(name);
\r
182 const char* getQueryString() const {
\r
183 return FCGX_GetParam("QUERY_STRING", m_req->envp);
\r
185 const char* getRequestBody() const {
\r
186 throw runtime_error("getRequestBody not implemented by FastCGI authorizer.");
\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
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
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
202 cout << codestr << "\r\n" << hdr << "\r\n";
\r
206 cout.write(buf, in.gcount());
\r
208 return SHIB_RETURN_DONE;
\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
221 cout << hdr << "<HTML><BODY>Redirecting...</BODY></HTML>";
\r
222 return SHIB_RETURN_DONE;
\r
225 long returnDecline() {
\r
226 return SHIB_RETURN_KO;
\r
230 return SHIB_RETURN_OK;
\r
233 const vector<string>& getClientCertificates() const {
\r
234 static vector<string> g_NoCerts;
\r
239 static void print_ok(const map<string,string>& headers)
\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
248 static void print_error(const char* msg)
\r
250 cout << "Status: 500 Server Error" << "\r\n\r\n" << msg;
\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
264 if (!g_Config->init()) {
\r
265 cerr << "failed to initialize Shibboleth libraries" << endl;
\r
270 if (!g_Config->instantiate(NULL, true))
\r
271 throw runtime_error("unknown error");
\r
273 catch (exception& ex) {
\r
275 cerr << "exception while initializing Shibboleth configuration: " << ex.what() << endl;
\r
279 string g_ServerScheme;
\r
280 string g_ServerName;
\r
281 int g_ServerPort=0;
\r
283 // Load "authoritative" URL fields.
\r
284 char* var = getenv("SHIBSP_SERVER_NAME");
\r
286 g_ServerName = var;
\r
287 var = getenv("SHIBSP_SERVER_SCHEME");
\r
289 g_ServerScheme = var;
\r
290 var = getenv("SHIBSP_SERVER_PORT");
\r
292 g_ServerPort = atoi(var);
\r
294 streambuf* cout_streambuf = cout.rdbuf();
\r
295 streambuf* cerr_streambuf = cerr.rdbuf();
\r
297 FCGX_Request request;
\r
300 FCGX_InitRequest(&request, 0, 0);
\r
302 cout << "Shibboleth initialization complete. Starting request loop." << endl;
\r
303 while (FCGX_Accept_r(&request) == 0)
\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
311 cout.rdbuf(&cout_fcgi_streambuf);
\r
312 cerr.rdbuf(&cerr_fcgi_streambuf);
\r
315 xmltooling::NDC ndc("FastCGI shibauthorizer");
\r
316 ShibTargetFCGIAuth sta(&request, g_ServerScheme.c_str(), g_ServerName.c_str(), g_ServerPort);
\r
318 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta);
\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
326 case SHIB_RETURN_KO:
\r
327 print_ok(sta.m_request_headers);
\r
330 case SHIB_RETURN_DONE:
\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
340 res = sta.getServiceProvider().doExport(sta);
\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
348 case SHIB_RETURN_KO:
\r
349 print_ok(sta.m_request_headers);
\r
352 case SHIB_RETURN_DONE:
\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
362 res = sta.getServiceProvider().doAuthorization(sta);
\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
370 case SHIB_RETURN_KO:
\r
371 print_ok(sta.m_request_headers);
\r
374 case SHIB_RETURN_DONE:
\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
384 print_ok(sta.m_request_headers);
\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
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
397 cout << "Request loop ended." << endl;
\r
399 cout.rdbuf(cout_streambuf);
\r
400 cerr.rdbuf(cerr_streambuf);
\r