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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 /* shibauthorizer.cpp - Shibboleth FastCGI Authorizer
27 #include "config_win32.h"
29 #define _CRT_NONSTDC_NO_DEPRECATE 1
30 #define _CRT_SECURE_NO_DEPRECATE 1
31 #define _SCL_SECURE_NO_WARNINGS 1
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>
47 # include <sys/mman.h>
51 using namespace shibsp;
52 using namespace xmltooling;
53 using namespace xercesc;
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);
65 class ShibTargetFCGIAuth : public AbstractSPRequest
69 string m_scheme,m_hostname;
70 multimap<string,string> m_response_headers;
72 map<string,string> m_request_headers;
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;
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.");
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;
96 setRequestURI(FCGX_GetParam("REQUEST_URI", m_req->envp));
99 ~ShibTargetFCGIAuth() { }
101 const char* getScheme() const {
102 return m_scheme.c_str();
104 const char* getHostname() const {
105 return m_hostname.c_str();
107 int getPort() const {
110 const char* getMethod() const {
111 return FCGX_GetParam("REQUEST_METHOD", m_req->envp);
113 string getContentType() const {
114 const char* s = FCGX_GetParam("CONTENT_TYPE", m_req->envp);
117 long getContentLength() const {
118 const char* s = FCGX_GetParam("CONTENT_LENGTH", m_req->envp);
119 return s ? atol(s) : 0;
121 string getRemoteAddr() const {
122 string ret = AbstractSPRequest::getRemoteAddr();
125 const char* s = FCGX_GetParam("REMOTE_ADDR", m_req->envp);
128 void log(SPLogLevel level, const string& msg) const {
129 AbstractSPRequest::log(level,msg);
130 if (level >= SPError)
131 cerr << "shib: " << msg;
133 void clearHeader(const char* rawname, const char* cginame) {
134 // No need, since we use environment variables.
136 void setHeader(const char* name, const char* value) {
138 m_request_headers[name] = value;
140 m_request_headers.erase(name);
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())
147 // Nothing set locally and this isn't a "secure" call, so check the request.
149 for (; *name; ++name) {
153 hdr += toupper(*name);
155 char* s = FCGX_GetParam(hdr.c_str(), m_req->envp);
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())
165 void setRemoteUser(const char* user) {
167 m_request_headers["REMOTE_USER"] = user;
169 m_request_headers.erase("REMOTE_USER");
171 string getRemoteUser() const {
172 map<string,string>::const_iterator i = m_request_headers.find("REMOTE_USER");
173 if (i != m_request_headers.end())
176 char* remote_user = FCGX_GetParam("REMOTE_USER", m_req->envp);
182 void setAuthType(const char* authtype) {
184 m_request_headers["AUTH_TYPE"] = authtype;
186 m_request_headers.erase("AUTH_TYPE");
188 string getAuthType() const {
189 map<string,string>::const_iterator i = m_request_headers.find("AUTH_TYPE");
190 if (i != m_request_headers.end())
193 char* auth_type = FCGX_GetParam("AUTH_TYPE", m_req->envp);
199 void setResponseHeader(const char* name, const char* value) {
200 HTTPResponse::setResponseHeader(name, value);
203 m_response_headers.insert(make_pair(name,value));
205 m_response_headers.erase(name);
207 const char* getQueryString() const {
208 return FCGX_GetParam("QUERY_STRING", m_req->envp);
210 const char* getRequestBody() const {
211 throw runtime_error("getRequestBody not implemented by FastCGI authorizer.");
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";
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";
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;
228 cout << codestr << "\r\n" << hdr << "\r\n";
232 cout.write(buf, in.gcount());
234 return SHIB_RETURN_DONE;
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";
248 cout << hdr << "<HTML><BODY>Redirecting...</BODY></HTML>";
249 return SHIB_RETURN_DONE;
252 long returnDecline() {
253 return SHIB_RETURN_KO;
257 return SHIB_RETURN_OK;
260 const vector<string>& getClientCertificates() const {
261 static vector<string> g_NoCerts;
266 static void print_ok(const map<string,string>& headers)
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";
275 static void print_error(const char* msg)
277 cout << "Status: 500 Server Error" << "\r\n\r\n" << msg;
282 SPConfig* g_Config=&SPConfig::getConfig();
283 g_Config->setFeatures(
286 SPConfig::RequestMapping |
287 SPConfig::InProcess |
291 if (!g_Config->init()) {
292 cerr << "failed to initialize Shibboleth libraries" << endl;
297 if (!g_Config->instantiate(nullptr, true))
298 throw runtime_error("unknown error");
300 catch (exception& ex) {
302 cerr << "exception while initializing Shibboleth configuration: " << ex.what() << endl;
306 string g_ServerScheme;
310 // Load "authoritative" URL fields.
311 char* var = getenv("SHIBSP_SERVER_NAME");
314 var = getenv("SHIBSP_SERVER_SCHEME");
316 g_ServerScheme = var;
317 var = getenv("SHIBSP_SERVER_PORT");
319 g_ServerPort = atoi(var);
321 streambuf* cout_streambuf = cout.rdbuf();
322 streambuf* cerr_streambuf = cerr.rdbuf();
324 FCGX_Request request;
327 FCGX_InitRequest(&request, 0, 0);
329 cout << "Shibboleth initialization complete. Starting request loop." << endl;
330 while (FCGX_Accept_r(&request) == 0)
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);
338 cout.rdbuf(&cout_fcgi_streambuf);
339 cerr.rdbuf(&cerr_fcgi_streambuf);
342 xmltooling::NDC ndc("FastCGI shibauthorizer");
343 ShibTargetFCGIAuth sta(&request, g_ServerScheme.c_str(), g_ServerName.c_str(), g_ServerPort);
345 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta);
347 sta.log(SPRequest::SPDebug, "shib: doAuthentication handled the request");
350 print_ok(sta.m_request_headers);
354 print_ok(sta.m_request_headers);
357 case SHIB_RETURN_DONE:
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>");
367 res = sta.getServiceProvider().doExport(sta);
369 sta.log(SPRequest::SPDebug, "shib: doExport handled request");
372 print_ok(sta.m_request_headers);
376 print_ok(sta.m_request_headers);
379 case SHIB_RETURN_DONE:
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>");
389 res = sta.getServiceProvider().doAuthorization(sta);
391 sta.log(SPRequest::SPDebug, "shib: doAuthorization handled request");
394 print_ok(sta.m_request_headers);
398 print_ok(sta.m_request_headers);
401 case SHIB_RETURN_DONE:
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>");
411 print_ok(sta.m_request_headers);
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>");
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.
424 cout << "Request loop ended." << endl;
426 cout.rdbuf(cout_streambuf);
427 cerr.rdbuf(cerr_streambuf);