1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "apr_strings.h"
21 #include "ap_provider.h"
23 #include "http_config.h"
24 #include "http_core.h"
25 #include "http_protocol.h"
26 #include "http_request.h"
28 #include "util_script.h"
29 #include "ap_provider.h"
31 #include "util_fcgi.h"
34 module AP_MODULE_DECLARE_DATA authnz_fcgi_module;
37 const char *name; /* provider name */
38 const char *backend; /* backend address, as configured */
41 apr_sockaddr_t *backend_addrs;
47 const char *name; /* provider name */
48 const char *default_user; /* this is user if authorizer returns
49 * success and a user expression yields
52 ap_expr_info_t *user_expr; /* expr to evaluate to set r->user */
53 char authoritative; /* fail request if user is rejected? */
54 char require_basic_auth; /* fail if client didn't send credentials? */
58 /* If an "authnz" provider successfully authenticates, record
59 * the provider name here for checking during authz.
61 const char *successful_authnz_provider;
64 static apr_hash_t *fcgi_authn_providers, *fcgi_authz_providers;
66 #define FCGI_IO_TIMEOUT apr_time_from_sec(30)
68 #ifndef NON200_RESPONSE_BUF_LEN
69 #define NON200_RESPONSE_BUF_LEN 8192
72 /* fcgi://{hostname|IPv4|IPv6}:port[/] */
73 #define FCGI_BACKEND_REGEX_STR "m%^fcgi://(.*):(\\d{1,5})/?$%"
76 * utility function to connect to a peer; generally useful, but
77 * wait for AF_UNIX support in this mod before thinking about how
78 * to make it available to other modules
80 static apr_status_t connect_to_peer(apr_socket_t **newsock,
83 apr_sockaddr_t *backend_addrs,
84 const char *backend_name,
85 apr_interval_time_t timeout)
87 #define FN_LOG_MARK __FILE__,__LINE__,module_index
88 apr_status_t rv = APR_EINVAL; /* returned if no backend addr was provided
91 apr_sockaddr_t *addr = backend_addrs;
93 while (addr && !connected) {
94 int loglevel = addr->next ? APLOG_DEBUG : APLOG_ERR;
95 rv = apr_socket_create(newsock, addr->family,
96 SOCK_STREAM, 0, r->pool);
97 if (rv != APR_SUCCESS) {
98 ap_log_rerror(FN_LOG_MARK, loglevel, rv, r,
99 APLOGNO(02494) "error creating family %d socket "
101 addr->family, backend_name);
106 apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
107 apr_socket_timeout_set(*newsock,
108 timeout ? timeout : r->server->timeout);
110 rv = apr_socket_connect(*newsock, addr);
111 if (rv != APR_SUCCESS) {
112 apr_socket_close(*newsock);
113 ap_log_rerror(FN_LOG_MARK, loglevel, rv, r,
114 APLOGNO(02495) "attempt to connect to %pI (%s) "
115 "failed", addr, backend_name);
127 static void log_provider_info(const fcgi_provider_conf *conf, request_rec *r)
129 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
130 APLOGNO(02496) "name %s, backend %s, host %s, port %d, "
131 "first address %pI, %c%c",
137 conf->is_authn ? 'N' : '_',
138 conf->is_authz ? 'Z' : '_');
141 static void setupenv(request_rec *r, const char *password, const char *apache_role)
143 ap_add_common_vars(r);
145 apr_table_setn(r->subprocess_env, "FCGI_ROLE", AP_FCGI_AUTHORIZER_STR);
147 apr_table_setn(r->subprocess_env, "FCGI_APACHE_ROLE", apache_role);
150 apr_table_setn(r->subprocess_env, "REMOTE_PASSWD", password);
152 /* Drop the variables CONTENT_LENGTH, PATH_INFO, PATH_TRANSLATED,
153 * SCRIPT_NAME and most Hop-By-Hop headers - EXCEPT we will pass
154 * PROXY_AUTH to allow CGI to perform proxy auth for httpd
156 apr_table_unset(r->subprocess_env, "CONTENT_LENGTH");
157 apr_table_unset(r->subprocess_env, "PATH_INFO");
158 apr_table_unset(r->subprocess_env, "PATH_TRANSLATED");
159 apr_table_unset(r->subprocess_env, "SCRIPT_NAME");
160 apr_table_unset(r->subprocess_env, "HTTP_KEEP_ALIVE");
161 apr_table_unset(r->subprocess_env, "HTTP_TE");
162 apr_table_unset(r->subprocess_env, "HTTP_TRAILER");
163 apr_table_unset(r->subprocess_env, "HTTP_TRANSFER_ENCODING");
164 apr_table_unset(r->subprocess_env, "HTTP_UPGRADE");
166 /* Connection hop-by-hop header to prevent the CGI from hanging */
167 apr_table_set(r->subprocess_env, "HTTP_CONNECTION", "close");
170 static apr_status_t recv_data(const fcgi_provider_conf *conf,
178 rv = apr_socket_recv(s, buf, buflen);
179 if (rv != APR_SUCCESS) {
180 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
181 APLOGNO(02497) "Couldn't read from backend %s",
186 #if AP_MODULE_MAGIC_AT_LEAST(20130702,2)
187 ap_log_rdata(APLOG_MARK, APLOG_TRACE5, r, "FastCGI data received",
188 buf, *buflen, AP_LOG_DATA_SHOW_OFFSET);
193 static apr_status_t recv_data_full(const fcgi_provider_conf *conf,
200 apr_size_t cumulative_len = 0;
204 readlen = buflen - cumulative_len;
205 rv = recv_data(conf, r, s, buf + cumulative_len, &readlen);
206 if (rv != APR_SUCCESS) {
209 cumulative_len += readlen;
210 } while (cumulative_len < buflen);
215 static apr_status_t sendv_data(const fcgi_provider_conf *conf,
222 apr_size_t to_write = 0, written = 0;
223 apr_status_t rv = APR_SUCCESS;
226 for (i = 0; i < nvec; i++) {
227 to_write += vec[i].iov_len;
228 #if AP_MODULE_MAGIC_AT_LEAST(20130702,2)
229 ap_log_rdata(APLOG_MARK, APLOG_TRACE5, r, "FastCGI data sent",
230 vec[i].iov_base, vec[i].iov_len, AP_LOG_DATA_SHOW_OFFSET);
237 rv = apr_socket_sendv(s, vec + offset, nvec - offset, &n);
238 if (rv != APR_SUCCESS) {
239 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
240 APLOGNO(02498) "Sending data to %s failed",
246 if (written >= to_write)
247 break; /* short circuit out */
248 for (i = offset; i < nvec; ) {
249 if (n >= vec[i].iov_len) {
251 n -= vec[i++].iov_len;
254 vec[i].iov_base = (char *) vec[i].iov_base + n;
266 static apr_status_t send_begin_request(request_rec *r,
267 const fcgi_provider_conf *conf,
268 apr_socket_t *s, int role,
269 apr_uint16_t request_id)
272 ap_fcgi_header header;
273 unsigned char farray[AP_FCGI_HEADER_LEN];
274 ap_fcgi_begin_request_body brb;
275 unsigned char abrb[AP_FCGI_HEADER_LEN];
278 ap_fcgi_fill_in_header(&header, AP_FCGI_BEGIN_REQUEST, request_id,
280 ap_fcgi_fill_in_request_body(&brb, role, 0 /* *NOT* AP_FCGI_KEEP_CONN */);
282 ap_fcgi_header_to_array(&header, farray);
283 ap_fcgi_begin_request_body_to_array(&brb, abrb);
285 vec[0].iov_base = (void *)farray;
286 vec[0].iov_len = sizeof(farray);
287 vec[1].iov_base = (void *)abrb;
288 vec[1].iov_len = sizeof(abrb);
290 return sendv_data(conf, r, s, vec, 2, &len);
293 static apr_status_t send_environment(apr_socket_t *s,
294 const fcgi_provider_conf *conf,
295 request_rec *r, apr_uint16_t request_id,
296 apr_pool_t *temp_pool)
298 const char *fn = "send_environment";
299 const apr_array_header_t *envarr;
300 const apr_table_entry_t *elts;
302 ap_fcgi_header header;
303 unsigned char farray[AP_FCGI_HEADER_LEN];
306 apr_size_t avail_len, len, required_len;
307 int i, next_elem, starting_elem;
309 envarr = apr_table_elts(r->subprocess_env);
310 elts = (const apr_table_entry_t *) envarr->elts;
312 if (APLOG_R_IS_LEVEL(r, APLOG_TRACE2)) {
314 for (i = 0; i < envarr->nelts; ++i) {
318 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
321 !strcmp(elts[i].key, "REMOTE_PASSWD") ?
322 "XXXXXXXX" : elts[i].val);
326 /* Send envvars over in as many FastCGI records as it takes, */
327 next_elem = 0; /* starting with the first one */
329 avail_len = 16 * 1024; /* our limit per record, which could have been up
330 * to AP_FCGI_MAX_CONTENT_LEN
333 while (next_elem < envarr->nelts) {
334 starting_elem = next_elem;
335 required_len = ap_fcgi_encoded_env_len(r->subprocess_env,
340 if (next_elem < envarr->nelts) {
341 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
342 APLOGNO(02499) "couldn't encode envvar '%s' in %"
343 APR_SIZE_T_FMT " bytes",
344 elts[next_elem].key, avail_len);
345 /* skip this envvar and continue */
349 /* only an unused element at the end of the array */
353 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
354 APLOGNO(02500) "required len for encoding envvars: %"
355 APR_SIZE_T_FMT ", %d/%d elems processed so far",
356 required_len, next_elem, envarr->nelts);
358 body = apr_palloc(temp_pool, required_len);
359 rv = ap_fcgi_encode_env(r, r->subprocess_env, body, required_len,
361 /* we pre-compute, so we can't run out of space */
362 ap_assert(rv == APR_SUCCESS);
363 /* compute and encode must be in sync */
364 ap_assert(starting_elem == next_elem);
366 ap_fcgi_fill_in_header(&header, AP_FCGI_PARAMS, request_id,
367 (apr_uint16_t)required_len, 0);
368 ap_fcgi_header_to_array(&header, farray);
370 vec[0].iov_base = (void *)farray;
371 vec[0].iov_len = sizeof(farray);
372 vec[1].iov_base = body;
373 vec[1].iov_len = required_len;
375 rv = sendv_data(conf, r, s, vec, 2, &len);
376 apr_pool_clear(temp_pool);
383 /* Envvars sent, so say we're done */
384 ap_fcgi_fill_in_header(&header, AP_FCGI_PARAMS, request_id, 0, 0);
385 ap_fcgi_header_to_array(&header, farray);
387 vec[0].iov_base = (void *)farray;
388 vec[0].iov_len = sizeof(farray);
390 return sendv_data(conf, r, s, vec, 1, &len);
394 * This header-state logic is from mod_proxy_fcgi.
397 HDR_STATE_READING_HEADERS,
400 HDR_STATE_GOT_CRLFCR,
402 HDR_STATE_DONE_WITH_HEADERS
405 /* Try to find the end of the script headers in the response from the back
406 * end fastcgi server. STATE holds the current header parsing state for this
409 * Returns 0 if it can't find the end of the headers, and 1 if it found the
410 * end of the headers. */
411 static int handle_headers(request_rec *r,
415 const char *itr = readbuf;
420 case HDR_STATE_GOT_CRLF:
421 *state = HDR_STATE_GOT_CRLFCR;
425 *state = HDR_STATE_GOT_CR;
429 else if (*itr == '\n') {
431 case HDR_STATE_GOT_LF:
432 *state = HDR_STATE_DONE_WITH_HEADERS;
435 case HDR_STATE_GOT_CR:
436 *state = HDR_STATE_GOT_CRLF;
439 case HDR_STATE_GOT_CRLFCR:
440 *state = HDR_STATE_DONE_WITH_HEADERS;
444 *state = HDR_STATE_GOT_LF;
449 *state = HDR_STATE_READING_HEADERS;
452 if (*state == HDR_STATE_DONE_WITH_HEADERS)
458 if (*state == HDR_STATE_DONE_WITH_HEADERS) {
466 * handle_response() is based on mod_proxy_fcgi's dispatch()
468 static apr_status_t handle_response(const fcgi_provider_conf *conf,
469 request_rec *r, apr_socket_t *s,
470 apr_pool_t *temp_pool,
471 apr_uint16_t request_id,
473 apr_size_t *rspbuflen)
476 apr_bucket_brigade *ob;
477 apr_size_t orspbuflen;
478 apr_status_t rv = APR_SUCCESS;
479 const char *fn = "handle_response";
480 int header_state = HDR_STATE_READING_HEADERS;
481 int seen_end_of_headers = 0, done = 0;
484 orspbuflen = *rspbuflen;
485 *rspbuflen = 0; /* unless we actually read something */
488 ob = apr_brigade_create(r->pool, r->connection->bucket_alloc);
490 while (!done && rv == APR_SUCCESS) { /* Keep reading FastCGI records until
491 * we get AP_FCGI_END_REQUEST (done)
492 * or an error occurs.
494 apr_size_t readbuflen;
497 char readbuf[AP_IOBUFSIZE + 1];
498 unsigned char farray[AP_FCGI_HEADER_LEN];
501 unsigned char version;
503 rv = recv_data_full(conf, r, s, (char *)farray, AP_FCGI_HEADER_LEN);
504 if (rv != APR_SUCCESS) {
505 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
506 APLOGNO(02501) "%s: Error occurred before reading "
507 "entire header", fn);
511 ap_fcgi_header_fields_from_array(&version, &type, &rid, &clen, &plen,
514 if (version != AP_FCGI_VERSION_1) {
515 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
516 APLOGNO(02502) "%s: Got bogus FastCGI header "
517 "version %d", fn, (int)version);
522 if (rid != request_id) {
523 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
524 APLOGNO(02503) "%s: Got bogus FastCGI header "
525 "request id %d, expected %d",
526 fn, rid, request_id);
531 recv_again: /* if we need to keep reading more of a record's content */
533 if (clen > sizeof(readbuf) - 1) {
534 readbuflen = sizeof(readbuf) - 1;
540 * Now get the actual content of the record.
542 if (readbuflen != 0) {
543 rv = recv_data(conf, r, s, readbuf, &readbuflen);
544 if (rv != APR_SUCCESS) {
547 readbuf[readbuflen] = '\0';
551 case AP_FCGI_STDOUT: /* Response headers and optional body */
553 b = apr_bucket_transient_create(readbuf,
555 r->connection->bucket_alloc);
557 APR_BRIGADE_INSERT_TAIL(ob, b);
559 if (!seen_end_of_headers) {
560 int st = handle_headers(r, &header_state, readbuf);
565 seen_end_of_headers = 1;
568 ap_scan_script_header_err_brigade_ex(r, ob,
571 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
572 APLOGNO(02504) "%s: script header "
574 fn, status, r->status);
576 if (rspbuf) { /* caller wants to see response body,
582 *rspbuflen = orspbuflen;
584 tmprv = apr_brigade_flatten(ob, rspbuf, rspbuflen);
585 if (tmprv != APR_SUCCESS) {
586 /* should not occur for these bucket types;
587 * does not indicate overflow
589 ap_log_rerror(APLOG_MARK, APLOG_ERR, tmprv, r,
590 APLOGNO(02505) "%s: error "
591 "flattening response body",
598 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
599 APLOGNO(02506) "%s: Error parsing "
600 "script headers from %s",
605 apr_pool_clear(temp_pool);
608 /* We're still looking for the end of the
609 * headers, so this part of the data will need
611 apr_bucket_setaside(b, temp_pool);
615 /* If we didn't read all the data go back and get the
617 if (clen > readbuflen) {
624 case AP_FCGI_STDERR: /* Text to log */
626 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
627 APLOGNO(02507) "%s: Logged from %s: '%s'",
628 fn, conf->backend, readbuf);
631 if (clen > readbuflen) {
633 goto recv_again; /* continue reading this record */
637 case AP_FCGI_END_REQUEST:
642 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
643 APLOGNO(02508) "%s: Got bogus FastCGI record type "
649 * Read/discard any trailing padding.
652 rv = recv_data_full(conf, r, s, readbuf, plen);
653 if (rv != APR_SUCCESS) {
654 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
655 APLOGNO(02509) "%s: Error occurred reading "
663 apr_brigade_cleanup(ob);
665 if (rv == APR_SUCCESS && !seen_end_of_headers) {
667 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
668 APLOGNO(02510) "%s: Never reached end of script headers",
675 /* almost from mod_fcgid */
676 static int mod_fcgid_modify_auth_header(void *vars,
677 const char *key, const char *val)
679 /* When the application gives a 200 response, the server ignores response
680 headers whose names aren't prefixed with Variable- prefix, and ignores
681 any response content */
682 if (strncasecmp(key, "Variable-", 9) == 0)
683 apr_table_setn(vars, key, val);
687 static int fix_auth_header(void *vr, const char *key, const char *val)
691 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "moving %s->%s", key, val);
692 apr_table_unset(r->err_headers_out, key);
693 apr_table_setn(r->subprocess_env, key + 9, val);
697 static void req_rsp(request_rec *r, const fcgi_provider_conf *conf,
698 const char *password, const char *apache_role,
699 char *rspbuf, apr_size_t *rspbuflen)
701 const char *fn = "req_rsp";
702 apr_pool_t *temp_pool;
703 apr_size_t orspbuflen;
706 apr_table_t *saved_subprocess_env =
707 apr_table_copy(r->pool, r->subprocess_env);
710 orspbuflen = *rspbuflen;
711 *rspbuflen = 0; /* unless we actually read something */
714 apr_pool_create(&temp_pool, r->pool);
716 setupenv(r, password, apache_role);
718 rv = connect_to_peer(&s, r, APLOG_MODULE_INDEX, conf->backend_addrs,
719 conf->backend, FCGI_IO_TIMEOUT);
720 if (rv == APR_SUCCESS) {
721 apr_uint16_t request_id = 1;
723 rv = send_begin_request(r, conf, s, AP_FCGI_AUTHORIZER, request_id);
724 if (rv != APR_SUCCESS) {
725 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
726 APLOGNO(02511) "%s: Failed writing request to %s",
730 if (rv == APR_SUCCESS) {
731 rv = send_environment(s, conf, r, request_id, temp_pool);
732 if (rv != APR_SUCCESS) {
733 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
734 APLOGNO(02512) "%s: Failed writing environment "
735 "to %s", fn, conf->backend);
739 /* The responder owns the request body, not the authorizer.
740 * Don't even send an empty AP_FCGI_STDIN block. libfcgi doesn't care,
741 * but it wasn't sent to authorizers by mod_fastcgi or mod_fcgi and
742 * may be unhandled by the app. Additionally, the FastCGI spec does
743 * not mention FCGI_STDIN in the Authorizer description, though it
744 * does describe FCGI_STDIN elsewhere in more general terms than
745 * simply a wrapper for the client's request body.
748 if (rv == APR_SUCCESS) {
750 *rspbuflen = orspbuflen;
752 rv = handle_response(conf, r, s, temp_pool, request_id, rspbuf,
754 if (rv != APR_SUCCESS) {
755 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
756 APLOGNO(02514) "%s: Failed handling response "
757 "from %s", fn, conf->backend);
764 apr_pool_destroy(temp_pool);
766 if (rv != APR_SUCCESS) {
767 /* some sort of mechanical problem */
768 r->status = HTTP_INTERNAL_SERVER_ERROR;
771 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
772 APLOGNO(02515) "%s: Received HTTP status %d",
776 r->subprocess_env = saved_subprocess_env;
778 if (r->status == HTTP_OK) {
779 /* An Authorizer application's 200 response may include headers
780 * whose names are prefixed with Variable-, and they should be
781 * available to subsequent phases via subprocess_env (and yanked
782 * from the client response).
784 apr_table_t *vars = apr_table_make(r->pool, 10);
785 apr_table_do(mod_fcgid_modify_auth_header, vars,
786 r->err_headers_out, NULL);
787 apr_table_do(fix_auth_header, r, vars, NULL);
791 static int fcgi_check_authn(request_rec *r)
793 const char *fn = "fcgi_check_authn";
794 fcgi_dir_conf *dconf = ap_get_module_config(r->per_dir_config,
795 &authnz_fcgi_module);
796 const char *password = NULL;
797 const fcgi_provider_conf *conf;
799 const char *auth_type;
800 char rspbuf[NON200_RESPONSE_BUF_LEN + 1]; /* extra byte for '\0' */
801 apr_size_t rspbuflen = sizeof rspbuf - 1;
804 prov = dconf && dconf->name ? dconf->name : NULL;
806 if (!prov || !strcasecmp(prov, "None")) {
810 auth_type = ap_auth_type(r);
812 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
813 APLOGNO(02516) "%s, prov %s, authoritative %s, "
814 "require-basic %s, user expr? %s type %s",
816 dconf->authoritative ? "yes" : "no",
817 dconf->require_basic_auth ? "yes" : "no",
818 dconf->user_expr ? "yes" : "no",
821 if (auth_type && !strcasecmp(auth_type, "Basic")) {
822 if ((res = ap_get_basic_auth_pw(r, &password))) {
823 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
824 APLOGNO(02517) "%s: couldn't retrieve basic auth "
826 if (dconf->require_basic_auth) {
833 conf = apr_hash_get(fcgi_authn_providers, prov, APR_HASH_KEY_STRING);
835 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
836 APLOGNO(02518) "%s: can't find config for provider %s",
838 return HTTP_INTERNAL_SERVER_ERROR;
841 if (APLOGrdebug(r)) {
842 log_provider_info(conf, r);
845 req_rsp(r, conf, password, AP_FCGI_APACHE_ROLE_AUTHENTICATOR_STR,
848 if (r->status == HTTP_OK) {
849 if (dconf->user_expr) {
851 const char *user = ap_expr_str_exec(r, dconf->user_expr,
853 if (user && strlen(user)) {
854 r->user = apr_pstrdup(r->pool, user);
855 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
856 APLOGNO(02519) "%s: Setting user to '%s'",
859 else if (user && dconf->default_user) {
860 r->user = apr_pstrdup(r->pool, dconf->default_user);
863 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
864 APLOGNO(02520) "%s: Failure extracting user "
865 "after calling authorizer: user expression "
866 "yielded empty string (variable not set?)",
868 r->status = HTTP_INTERNAL_SERVER_ERROR;
871 /* unexpected error, not even an empty string was returned */
872 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
873 APLOGNO(02521) "%s: Failure extracting user "
874 "after calling authorizer: %s",
876 r->status = HTTP_INTERNAL_SERVER_ERROR;
879 if (conf->is_authz) {
880 /* combined authn/authz phase, so app won't be invoked for authz
882 * Remember that the request was successfully authorized by this
885 fcgi_request_notes *rnotes = apr_palloc(r->pool, sizeof(*rnotes));
886 rnotes->successful_authnz_provider = conf->name;
887 ap_set_module_config(r->request_config, &authnz_fcgi_module,
893 * For Authorizer response status values other than "200" (OK), the
894 * Web server denies access and sends the response status, headers,
895 * and content back to the HTTP client.
897 * This only makes sense if this authorizer is authoritative.
899 if (rspbuflen > 0 && !dconf->authoritative) {
900 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
901 APLOGNO(02522) "%s: Ignoring response body from non-"
902 "authoritative authorizer", fn);
904 else if (rspbuflen > 0) {
905 if (rspbuflen == sizeof rspbuf - 1) {
906 /* apr_brigade_flatten() interface :( */
907 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
908 APLOGNO(02523) "%s: possible overflow handling "
909 "response body", fn);
911 rspbuf[rspbuflen] = '\0'; /* we reserved an extra byte for '\0' */
912 ap_custom_response(r, r->status, rspbuf); /* API makes a copy */
916 return r->status == HTTP_OK ?
917 OK : dconf->authoritative ? r->status : DECLINED;
920 static authn_status fcgi_check_password(request_rec *r, const char *user,
921 const char *password)
923 const char *fn = "fcgi_check_password";
924 const char *prov = apr_table_get(r->notes, AUTHN_PROVIDER_NAME_NOTE);
925 const fcgi_provider_conf *conf;
927 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
928 APLOGNO(02524) "%s(%s, XXX): provider %s",
932 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
933 APLOGNO(02525) "%s: provider note isn't set", fn);
934 return AUTH_GENERAL_ERROR;
937 conf = apr_hash_get(fcgi_authn_providers, prov, APR_HASH_KEY_STRING);
939 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
940 APLOGNO(02526) "%s: can't find config for provider %s",
942 return AUTH_GENERAL_ERROR;
945 if (APLOGrdebug(r)) {
946 log_provider_info(conf, r);
949 req_rsp(r, conf, password,
950 /* combined authn and authz: FCGI_APACHE_ROLE not set */
951 conf->is_authz ? NULL : AP_FCGI_APACHE_ROLE_AUTHENTICATOR_STR,
954 if (r->status == HTTP_OK) {
955 if (conf->is_authz) {
956 /* combined authn/authz phase, so app won't be invoked for authz
958 * Remember that the request was successfully authorized by this
961 fcgi_request_notes *rnotes = apr_palloc(r->pool, sizeof(*rnotes));
962 rnotes->successful_authnz_provider = conf->name;
963 ap_set_module_config(r->request_config, &authnz_fcgi_module,
968 else if (r->status == HTTP_INTERNAL_SERVER_ERROR) {
969 return AUTH_GENERAL_ERROR;
976 static const authn_provider fcgi_authn_provider = {
977 &fcgi_check_password,
978 NULL /* get-realm-hash not supported */
981 static authz_status fcgi_authz_check(request_rec *r,
982 const char *require_line,
983 const void *parsed_require_line)
985 const char *fn = "fcgi_authz_check";
986 const char *prov = apr_table_get(r->notes, AUTHZ_PROVIDER_NAME_NOTE);
987 const fcgi_provider_conf *conf;
989 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
990 APLOGNO(02527) "%s(%s)", fn, require_line);
993 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
994 APLOGNO(02528) "%s: provider note isn't set", fn);
995 return AUTHZ_GENERAL_ERROR;
998 conf = apr_hash_get(fcgi_authz_providers, prov, APR_HASH_KEY_STRING);
1000 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
1001 APLOGNO(02529) "%s: can't find config for provider %s",
1003 return AUTHZ_GENERAL_ERROR;
1006 if (APLOGrdebug(r)) {
1007 log_provider_info(conf, r);
1011 return AUTHZ_DENIED_NO_USER;
1014 if (conf->is_authn) {
1015 /* combined authn/authz phase, so app won't be invoked for authz
1017 * If the provider already successfully authorized this request,
1020 fcgi_request_notes *rnotes = ap_get_module_config(r->request_config,
1021 &authnz_fcgi_module);
1023 && rnotes->successful_authnz_provider
1024 && !strcmp(rnotes->successful_authnz_provider, conf->name)) {
1025 return AUTHZ_GRANTED;
1028 return AUTHZ_DENIED;
1032 req_rsp(r, conf, NULL, AP_FCGI_APACHE_ROLE_AUTHORIZER_STR, NULL, NULL);
1034 if (r->status == HTTP_OK) {
1035 return AUTHZ_GRANTED;
1037 else if (r->status == HTTP_INTERNAL_SERVER_ERROR) {
1038 return AUTHZ_GENERAL_ERROR;
1041 return AUTHZ_DENIED;
1046 static const char *fcgi_authz_parse(cmd_parms *cmd, const char *require_line,
1047 const void **parsed_require_line)
1049 /* Allowed form: Require [not] registered-provider-name<EOS>
1051 if (strcmp(require_line, "")) {
1052 return "mod_authnz_fcgi doesn't support restrictions on providers "
1053 "(i.e., multiple require args)";
1059 static const authz_provider fcgi_authz_provider = {
1064 static const char *fcgi_check_authn_provider(cmd_parms *cmd,
1069 const char *dname = "AuthnzFcgiCheckAuthnProvider";
1070 fcgi_dir_conf *dc = d;
1074 return apr_pstrcat(cmd->pool, dname, ": No provider given", NULL);
1077 dc->name = argv[ca];
1080 if (!strcasecmp(dc->name, "None")) {
1082 return "Options aren't supported with \"None\"";
1087 const char *var = argv[ca], *val;
1092 /* at present, everything needs an argument */
1094 return apr_pstrcat(cmd->pool, dname, ": ", var,
1095 "needs an argument", NULL);
1101 if (!strcasecmp(var, "Authoritative")) {
1102 if (!strcasecmp(val, "On")) {
1103 dc->authoritative = 1;
1105 else if (!strcasecmp(val, "Off")) {
1106 dc->authoritative = 0;
1112 else if (!strcasecmp(var, "DefaultUser")) {
1113 dc->default_user = val;
1115 else if (!strcasecmp(var, "RequireBasicAuth")) {
1116 if (!strcasecmp(val, "On")) {
1117 dc->require_basic_auth = 1;
1119 else if (!strcasecmp(val, "Off")) {
1120 dc->require_basic_auth = 0;
1126 else if (!strcasecmp(var, "UserExpr")) {
1128 int flags = AP_EXPR_FLAG_DONT_VARY | AP_EXPR_FLAG_RESTRICTED
1129 | AP_EXPR_FLAG_STRING_RESULT;
1131 dc->user_expr = ap_expr_parse_cmd(cmd, val,
1134 return apr_psprintf(cmd->pool, "%s: Error parsing '%s': '%s'",
1139 return apr_pstrcat(cmd->pool, dname, ": Unexpected option '",
1143 return apr_pstrcat(cmd->pool, dname, ": Bad argument '",
1144 val, "' to option '", var, "'", NULL);
1151 /* AuthnzFcgiAuthDefineProvider {authn|authz|authnz} provider-name \
1152 * fcgi://backendhost:backendport/
1154 static const char *fcgi_define_provider(cmd_parms *cmd,
1159 const char *dname = "AuthnzFcgiDefineProvider";
1160 ap_rxplus_t *fcgi_backend_regex;
1163 const char *err, *stype;
1164 fcgi_provider_conf *conf = apr_pcalloc(cmd->pool, sizeof(*conf));
1167 fcgi_backend_regex = ap_rxplus_compile(cmd->pool, FCGI_BACKEND_REGEX_STR);
1168 if (!fcgi_backend_regex) {
1169 return apr_psprintf(cmd->pool,
1170 "%s: failed to compile regexec '%s'",
1171 dname, FCGI_BACKEND_REGEX_STR);
1174 err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1179 return apr_pstrcat(cmd->pool, dname, ": No type given", NULL);
1185 if (!strcasecmp(stype, "authn")) {
1188 else if (!strcasecmp(stype, "authz")) {
1191 else if (!strcasecmp(stype, "authnz")) {
1192 conf->is_authn = conf->is_authz = 1;
1195 return apr_pstrcat(cmd->pool,
1197 ": Invalid provider type ",
1203 return apr_pstrcat(cmd->pool, dname, ": No provider name given", NULL);
1205 conf->name = argv[ca];
1209 return apr_pstrcat(cmd->pool, dname, ": No backend-address given",
1213 rc = ap_rxplus_exec(cmd->pool, fcgi_backend_regex, argv[ca], NULL);
1214 if (!rc || ap_rxplus_nmatch(fcgi_backend_regex) != 3) {
1215 return apr_pstrcat(cmd->pool,
1216 dname, ": backend-address '",
1218 "' has invalid form",
1222 host = ap_rxplus_pmatch(cmd->pool, fcgi_backend_regex, 1);
1223 if (host[0] == '[' && host[strlen(host) - 1] == ']') {
1225 host[strlen(host) - 1] = '\0';
1228 conf->port = atoi(ap_rxplus_pmatch(cmd->pool, fcgi_backend_regex, 2));
1229 if (conf->port > 65535) {
1230 return apr_pstrcat(cmd->pool,
1231 dname, ": backend-address '",
1233 "' has invalid port",
1237 conf->backend = argv[ca];
1241 rv = apr_sockaddr_info_get(&conf->backend_addrs, conf->host,
1242 APR_UNSPEC, conf->port, 0, cmd->pool);
1243 if (rv != APR_SUCCESS) {
1244 ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, rv, NULL,
1245 APLOGNO(02530) "Address %s could not be resolved",
1247 return apr_pstrcat(cmd->pool,
1249 ": Error resolving backend address",
1254 return apr_pstrcat(cmd->pool,
1256 ": Unexpected parameter ",
1261 if (conf->is_authn) {
1262 apr_hash_set(fcgi_authn_providers, conf->name, APR_HASH_KEY_STRING,
1264 ap_register_auth_provider(cmd->pool, AUTHN_PROVIDER_GROUP,
1266 AUTHN_PROVIDER_VERSION,
1267 &fcgi_authn_provider,
1268 AP_AUTH_INTERNAL_PER_CONF);
1271 if (conf->is_authz) {
1272 apr_hash_set(fcgi_authz_providers, conf->name, APR_HASH_KEY_STRING,
1274 ap_register_auth_provider(cmd->pool, AUTHZ_PROVIDER_GROUP,
1276 AUTHZ_PROVIDER_VERSION,
1277 &fcgi_authz_provider,
1278 AP_AUTH_INTERNAL_PER_CONF);
1284 static const command_rec fcgi_cmds[] = {
1285 AP_INIT_TAKE_ARGV("AuthnzFcgiDefineProvider",
1286 fcgi_define_provider,
1289 "Define a FastCGI authn and/or authz provider"),
1291 AP_INIT_TAKE_ARGV("AuthnzFcgiCheckAuthnProvider",
1292 fcgi_check_authn_provider,
1295 "Enable/disable a FastCGI authorizer to handle "
1296 "check_authn phase"),
1301 static int fcgi_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
1304 fcgi_authn_providers = apr_hash_make(pconf);
1305 fcgi_authz_providers = apr_hash_make(pconf);
1310 static void fcgi_register_hooks(apr_pool_t *p)
1312 static const char * const auth_basic_runs_after_me[] =
1313 {"mod_auth_basic.c", NULL}; /* to allow for custom response */
1315 ap_hook_pre_config(fcgi_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1316 ap_hook_check_authn(fcgi_check_authn, NULL, auth_basic_runs_after_me,
1317 APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_CONF);
1320 static void *create_dir_conf(apr_pool_t *p, char *dummy)
1322 fcgi_dir_conf *dconf = apr_pcalloc(p, sizeof(fcgi_dir_conf));
1324 dconf->authoritative = 1;
1328 static void *merge_dir_conf(apr_pool_t *p, void *basev, void *overridesv)
1330 fcgi_dir_conf *a = (fcgi_dir_conf *)apr_pcalloc(p, sizeof(*a));
1331 fcgi_dir_conf *base = (fcgi_dir_conf *)basev,
1332 *over = (fcgi_dir_conf *)overridesv;
1334 /* currently we just have a single directive applicable to a
1335 * directory, so if it is set then grab all fields from fcgi_dir_conf
1338 memcpy(a, over, sizeof(*a));
1341 memcpy(a, base, sizeof(*a));
1347 AP_DECLARE_MODULE(authnz_fcgi) =
1349 STANDARD20_MODULE_STUFF,
1350 create_dir_conf, /* dir config creater */
1351 merge_dir_conf, /* dir merger */
1352 NULL, /* server config */
1353 NULL, /* merge server config */
1354 fcgi_cmds, /* command apr_table_t */
1355 fcgi_register_hooks /* register hooks */