2 * Copyright 2001-2009 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 <saml/saml.h>
\r
24 #include <shib-target/shib-target.h>
\r
26 #include <stdexcept>
\r
28 #ifdef HAVE_UNISTD_H
\r
29 # include <unistd.h>
\r
30 # include <sys/mman.h>
\r
34 using namespace shibtarget;
\r
35 using namespace saml;
\r
36 using namespace std;
\r
44 set<string> g_allowedSchemes;
\r
46 class ShibTargetFCGIAuth : public ShibTarget
\r
48 FCGX_Request* m_req;
\r
51 void checkString(const string& s, const char* msg) {
\r
52 string::const_iterator e = s.end();
\r
53 for (string::const_iterator i=s.begin(); i!=e; ++i) {
\r
55 throw runtime_error(msg);
\r
60 map<string,string> m_headers;
\r
62 ShibTargetFCGIAuth(FCGX_Request* req, const char* scheme=NULL, const char* hostname=NULL, int port=0) : m_req(req) {
\r
63 const char* server_name_str = hostname;
\r
64 if (!server_name_str || !*server_name_str)
\r
65 server_name_str = FCGX_GetParam("SERVER_NAME", req->envp);
\r
67 int server_port = port;
\r
69 char* server_port_str = FCGX_GetParam("SERVER_PORT", req->envp);
\r
70 server_port = strtol(server_port_str, &server_port_str, 10);
\r
71 if (*server_port_str) {
\r
72 cerr << "can't parse SERVER_PORT (" << FCGX_GetParam("SERVER_PORT", req->envp) << ")" << endl;
\r
73 throw runtime_error("Unable to determine server port.");
\r
77 const char* server_scheme_str = scheme;
\r
78 if (!server_scheme_str || !*server_scheme_str)
\r
79 server_scheme_str = (server_port == 443 || server_port == 8443) ? "https" : "http";
\r
81 const char* request_uri_str = FCGX_GetParam("REQUEST_URI", req->envp);
\r
82 const char* content_type_str = FCGX_GetParam("CONTENT_TYPE", req->envp);
\r
83 const char* remote_addr_str = FCGX_GetParam("REMOTE_ADDR", req->envp);
\r
84 const char* request_method_str = FCGX_GetParam("REQUEST_METHOD", req->envp);
\r
86 init(server_scheme_str,
\r
90 content_type_str ? content_type_str : "",
\r
96 ~ShibTargetFCGIAuth() { }
\r
98 virtual void log(ShibLogLevel level, const string& msg) {
\r
99 ShibTarget::log(level,msg);
\r
100 if (level == LogLevelError)
\r
101 cerr << "shib: " << msg;
\r
104 virtual string getCookies(void) const {
\r
105 char* cookie = FCGX_GetParam("HTTP_COOKIE", m_req->envp);
\r
106 return cookie ? cookie : "";
\r
109 virtual void setCookie(const string &name, const string &value) {
\r
110 m_cookie += "Set-Cookie: " + name + "=" + value + "\r\n";
\r
113 virtual string getArgs(void) {
\r
114 char* args = FCGX_GetParam("QUERY_STRING", m_req->envp);
\r
115 return args ? args : "";
\r
118 virtual string getPostData(void) {
\r
119 throw runtime_error("getPostData not implemented by FastCGI authorizer.");
\r
122 virtual void clearHeader(const string& name) {
\r
123 // no need, since request headers turn into actual environment variables
\r
126 virtual void setHeader(const string& name, const string &value) {
\r
127 m_headers[name] = value;
\r
130 virtual string getHeader(const string& name) {
\r
131 if (m_headers.find(name) != m_headers.end())
\r
132 return m_headers[name];
\r
137 virtual void setRemoteUser(const string& user) {
\r
138 m_headers["REMOTE_USER"] = user;
\r
141 virtual string getRemoteUser(void) {
\r
142 if (m_headers.find("REMOTE_USER") != m_headers.end())
\r
143 return m_headers["REMOTE_USER"];
\r
145 char* remote_user = FCGX_GetParam("REMOTE_USER", m_req->envp);
\r
147 return remote_user;
\r
152 virtual void* sendPage(
\r
155 const string& content_type="text/html",
\r
156 const saml::Iterator<header_t>& headers=EMPTY(header_t)) {
\r
158 checkString(content_type, "Detected control character in a response header.");
\r
159 string hdr = m_cookie + "Connection: close\r\nContent-type: " + content_type + "\r\n";
\r
160 while (headers.hasNext()) {
\r
161 const header_t& h=headers.next();
\r
162 checkString(h.first, "Detected control character in a response header.");
\r
163 checkString(h.second, "Detected control character in a response header.");
\r
164 hdr += h.first + ": " + h.second + "\r\n";
\r
167 // We can't return 200 OK here or else the filter is bypassed
\r
168 // so custom Shib errors will get turned into a generic page.
\r
169 const char* codestr="Status: 500 Server Error";
\r
171 case 403: codestr="Status: 403 Forbidden"; break;
\r
172 case 404: codestr="Status: 404 Not Found"; break;
\r
175 cout << codestr << "\r\n" << hdr << "\r\n" << msg;
\r
176 return (void*)SHIB_RETURN_DONE;
\r
179 virtual void* sendRedirect(const string& url) {
\r
180 checkString(url, "Detected control character in an attempted redirect.");
\r
181 if (g_allowedSchemes.find(url.substr(0, url.find(':'))) == g_allowedSchemes.end())
\r
182 throw runtime_error("Invalid scheme in attempted redirect.");
\r
183 cout << "Status: 302 Please Wait" << "\r\n"
\r
184 << "Location: " << url << "\r\n"
\r
185 << m_cookie << "\r\n"
\r
186 << "<HTML><BODY>Redirecting...</BODY></HTML>";
\r
187 return (void*)SHIB_RETURN_DONE;
\r
190 virtual void* returnDecline(void) {
\r
191 return (void*)SHIB_RETURN_KO;
\r
194 virtual void* returnOK(void) {
\r
195 return (void*)SHIB_RETURN_OK;
\r
199 static void print_ok(const map<string,string>& headers)
\r
201 cout << "Status: 200 OK" << "\r\n";
\r
202 for (map<string,string>::const_iterator iter = headers.begin(); iter != headers.end(); iter++) {
\r
203 cout << "Variable-" << iter->first << ": " << iter->second << "\r\n";
\r
208 static void print_error(const char* msg)
\r
210 cout << "Status: 500 Server Error" << "\r\n\r\n" << msg;
\r
215 char* shib_config = getenv("SHIB_CONFIG");
\r
216 char* shib_schema = getenv("SHIB_SCHEMA");
\r
217 if ((shib_config == NULL) || (shib_schema == NULL)) {
\r
218 cerr << "SHIB_CONFIG or SHIB_SCHEMA not initialized!" << endl;
\r
221 cerr << "SHIB_CONFIG = " << shib_config << endl
\r
222 << "SHIB_SCHEMA = " << shib_schema << endl;
\r
224 string g_ServerScheme;
\r
225 string g_ServerName;
\r
226 int g_ServerPort = 0;
\r
227 ShibTargetConfig* g_Config;
\r
230 g_Config = &ShibTargetConfig::getConfig();
\r
231 g_Config->setFeatures(
\r
232 ShibTargetConfig::Listener |
\r
233 ShibTargetConfig::Metadata |
\r
234 ShibTargetConfig::AAP |
\r
235 ShibTargetConfig::RequestMapper |
\r
236 ShibTargetConfig::LocalExtensions |
\r
237 ShibTargetConfig::Logging
\r
239 if (!g_Config->init(shib_schema)) {
\r
240 cerr << "failed to initialize Shibboleth libraries" << endl;
\r
244 if (!g_Config->load(shib_config)) {
\r
245 cerr << "failed to load Shibboleth configuration" << endl;
\r
249 IConfig* conf=g_Config->getINI();
\r
250 Locker locker(conf);
\r
251 const IPropertySet* props=conf->getPropertySet("Local");
\r
253 pair<bool,const char*> str=props->getString("allowedSchemes");
\r
255 string schemes=str.second;
\r
257 for (unsigned int i=0; i < schemes.length(); i++) {
\r
258 if (schemes.at(i)==' ') {
\r
259 g_allowedSchemes.insert(schemes.substr(j, i-j));
\r
263 g_allowedSchemes.insert(schemes.substr(j, schemes.length()-j));
\r
266 if (g_allowedSchemes.empty()) {
\r
267 g_allowedSchemes.insert("https");
\r
268 g_allowedSchemes.insert("http");
\r
271 catch (exception& e) {
\r
272 cerr << "exception while initializing Shibboleth configuration: " << e.what() << endl;
\r
278 // Load "authoritative" URL fields.
\r
279 char* var = getenv("SHIBSP_SERVER_NAME");
\r
281 g_ServerName = var;
\r
282 var = getenv("SHIBSP_SERVER_SCHEME");
\r
284 g_ServerScheme = var;
\r
285 var = getenv("SHIBSP_SERVER_PORT");
\r
287 g_ServerPort = atoi(var);
\r
289 streambuf* cout_streambuf = cout.rdbuf();
\r
290 streambuf* cerr_streambuf = cerr.rdbuf();
\r
292 FCGX_Request request;
\r
295 FCGX_InitRequest(&request, 0, 0);
\r
297 cout << "Shibboleth initialization complete. Starting request loop." << endl;
\r
298 while (FCGX_Accept_r(&request) == 0)
\r
300 // Note that the default bufsize (0) will cause the use of iostream
\r
301 // methods that require positioning (such as peek(), seek(),
\r
302 // unget() and putback()) to fail (in favour of more efficient IO).
\r
303 fcgi_streambuf cout_fcgi_streambuf(request.out);
\r
304 fcgi_streambuf cerr_fcgi_streambuf(request.err);
\r
306 cout.rdbuf(&cout_fcgi_streambuf);
\r
307 cerr.rdbuf(&cerr_fcgi_streambuf);
\r
310 saml::NDC ndc("FastCGI shibauthorizer");
\r
311 ShibTargetFCGIAuth sta(&request, g_ServerScheme.c_str(), g_ServerName.c_str(), g_ServerPort);
\r
313 pair<bool,void*> res = sta.doCheckAuthN();
\r
316 cerr << "shib: doCheckAuthN handled the request" << endl;
\r
318 switch((long)res.second) {
\r
319 case SHIB_RETURN_OK:
\r
320 print_ok(sta.m_headers);
\r
323 case SHIB_RETURN_KO:
\r
324 print_ok(sta.m_headers);
\r
327 case SHIB_RETURN_DONE:
\r
331 cerr << "shib: doCheckAuthN returned an unexpected result: " << (long)res.second << endl;
\r
332 print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
\r
337 res = sta.doExportAssertions();
\r
340 cerr << "shib: doExportAssertions handled request" << endl;
\r
342 switch((long)res.second) {
\r
343 case SHIB_RETURN_OK:
\r
344 print_ok(sta.m_headers);
\r
347 case SHIB_RETURN_KO:
\r
348 print_ok(sta.m_headers);
\r
351 case SHIB_RETURN_DONE:
\r
355 cerr << "shib: doExportAssertions returned an unexpected result: " << (long)res.second << endl;
\r
356 print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
\r
361 res = sta.doCheckAuthZ();
\r
364 cerr << "shib: doCheckAuthZ handled request" << endl;
\r
366 switch((long)res.second) {
\r
367 case SHIB_RETURN_OK:
\r
368 print_ok(sta.m_headers);
\r
371 case SHIB_RETURN_KO:
\r
372 print_ok(sta.m_headers);
\r
375 case SHIB_RETURN_DONE:
\r
379 cerr << "shib: doCheckAuthZ returned an unexpected result: " << (long)res.second << endl;
\r
380 print_error("<html><body>FastCGI Shibboleth authorizer returned an unexpected result.</body></html>");
\r
385 print_ok(sta.m_headers);
\r
388 catch (exception& e) {
\r
389 cerr << "shib: FastCGI authorizer caught an exception: " << e.what() << endl;
\r
390 print_error("<html><body>FastCGI Shibboleth authorizer caught an exception, check log for details.</body></html>");
\r
393 // If the output streambufs had non-zero bufsizes and
\r
394 // were constructed outside of the accept loop (i.e.
\r
395 // their destructor won't be called here), they would
\r
396 // have to be flushed here.
\r
398 cout << "Request loop ended." << endl;
\r
400 cout.rdbuf(cout_streambuf);
\r
401 cerr.rdbuf(cerr_streambuf);
\r
404 g_Config->shutdown();
\r