5
#include <netinet/in.h>
13
#include "inet_ntop_cache.h"
19
* mod_extforward.c for lighttpd, by comman.kang <at> gmail <dot> com
20
* extended, modified by Lionel Elie Mamane (LEM), lionel <at> mamane <dot> lu
24
* Trust proxy 10.0.0.232 and 10.0.0.232
25
* extforward.forwarder = ( "10.0.0.232" => "trust",
26
* "10.0.0.233" => "trust" )
28
* Trust all proxies (NOT RECOMMENDED!)
29
* extforward.forwarder = ( "all" => "trust")
31
* Note that "all" has precedence over specific entries,
32
* so "all except" setups will not work.
34
* Note: The effect of this module is variable on $HTTP["remotip"] directives and
35
* other module's remote ip dependent actions.
36
* Things done by modules before we change the remoteip or after we reset it will match on the proxy's IP.
37
* Things done in between these two moments will match on the real client's IP.
38
* The moment things are done by a module depends on in which hook it does things and within the same hook
39
* on whether they are before/after us in the module loading order
40
* (order in the server.modules directive in the config file).
44
* mod_access: Will match on the real client.
47
* In order to see the "real" ip address in access log ,
48
* you'll have to load mod_extforward after mod_accesslog.
58
* seems causing segfault with mod_ssl and $HTTP{"socket"} directives
59
* LEM 2006.05.26: Fixed segfault $SERVER["socket"] directive. Untested with SSL.
62
* 2005.12.19 Initial Version
63
* 2005.12.19 fixed conflict with conditional directives
64
* 2006.05.26 LEM: IPv6 support
65
* 2006.05.26 LEM: Fix a segfault with $SERVER["socket"] directive.
66
* 2006.05.26 LEM: Run at uri_raw time, as we don't need to see the URI
67
* In this manner, we run before mod_access and $HTTP["remoteip"] directives work!
68
* 2006.05.26 LEM: Clean config_cond cache of tests whose result we probably change.
72
/* plugin config for all request/connections */
81
plugin_config **config_storage;
87
/* context , used for restore remote ip */
90
sock_addr saved_remote_addr;
91
buffer *saved_remote_addr_buf;
95
static handler_ctx * handler_ctx_init(sock_addr oldaddr, buffer *oldaddr_buf) {
97
hctx = calloc(1, sizeof(*hctx));
98
hctx->saved_remote_addr = oldaddr;
99
hctx->saved_remote_addr_buf = oldaddr_buf;
103
static void handler_ctx_free(handler_ctx *hctx) {
107
/* init the plugin data */
108
INIT_FUNC(mod_extforward_init) {
110
p = calloc(1, sizeof(*p));
114
/* destroy the plugin data */
115
FREE_FUNC(mod_extforward_free) {
116
plugin_data *p = p_d;
120
if (!p) return HANDLER_GO_ON;
122
if (p->config_storage) {
125
for (i = 0; i < srv->config_context->used; i++) {
126
plugin_config *s = p->config_storage[i];
130
array_free(s->forwarder);
134
free(p->config_storage);
140
return HANDLER_GO_ON;
143
/* handle plugin config and check values */
145
SETDEFAULTS_FUNC(mod_extforward_set_defaults) {
146
plugin_data *p = p_d;
149
config_values_t cv[] = {
150
{ "extforward.forwarder", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
151
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
154
if (!p) return HANDLER_ERROR;
156
p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
158
for (i = 0; i < srv->config_context->used; i++) {
161
s = calloc(1, sizeof(plugin_config));
162
s->forwarder = array_init();
164
cv[0].destination = s->forwarder;
166
p->config_storage[i] = s;
168
if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) {
169
return HANDLER_ERROR;
173
return HANDLER_GO_ON;
178
static int mod_extforward_patch_connection(server *srv, connection *con, plugin_data *p) {
180
plugin_config *s = p->config_storage[0];
184
/* LEM: The purpose of this seems to match extforward configuration
185
stanzas that are not in the global context, but in some sub-context.
186
I fear this will break contexts of the form HTTP['remote'] = .
187
(in the form that they do not work with the real remote, but matching on
190
I'm not sure this this is all thread-safe. Is the p we are passed different
191
for each connection or is it global?
193
mod_fastcgi does the same, so it must be safe.
195
/* skip the first, the global context */
196
for (i = 1; i < srv->config_context->used; i++) {
197
data_config *dc = (data_config *)srv->config_context->data[i];
198
s = p->config_storage[i];
200
/* condition didn't match */
201
if (!config_check_cond(srv, con, dc)) continue;
204
for (j = 0; j < dc->value->used; j++) {
205
data_unset *du = dc->value->data[j];
207
if (buffer_is_equal_string(du->key, CONST_STR_LEN("extforward.forwarder"))) {
218
static void put_string_into_array_len(array *ary, const char *str, int len)
220
data_string *tempdata;
223
tempdata = data_string_init();
224
buffer_copy_string_len(tempdata->value,str,len);
225
array_insert_unique(ary,(data_unset *)tempdata);
228
extract a forward array from the environment
230
static array *extract_forward_array(buffer *pbuffer)
232
array *result = array_init();
233
if (pbuffer->used > 0) {
235
/* state variable, 0 means not in string, 1 means in string */
237
for (base = pbuffer->ptr, curr = pbuffer->ptr; *curr; curr++)
240
if ( (*curr > '9' || *curr < '0') && *curr != '.' && *curr != ':' ) {
241
/* found an separator , insert value into result array */
242
put_string_into_array_len(result, base, curr-base);
243
/* change state to not in string */
247
if (*curr >= '0' && *curr <= '9')
249
/* found leading char of an IP address, move base pointer and change state */
255
/* if breaking out while in str, we got to the end of string, so add it */
258
put_string_into_array_len(result, base, curr-base);
265
#define IP_UNTRUSTED 0
267
check whether ip is trusted, return 1 for trusted , 0 for untrusted
269
static int is_proxy_trusted(const char *ipstr, plugin_data *p)
271
data_string* allds = (data_string *) array_get_element(p->conf.forwarder,"all");
273
if (strcasecmp(allds->value->ptr,"trust") == 0)
278
return (data_string *)array_get_element(p->conf.forwarder,ipstr) ? IP_TRUSTED : IP_UNTRUSTED ;
281
struct addrinfo *ipstr_to_sockaddr(const char *host)
283
struct addrinfo hints, *res0;
286
memset(&hints, 0, sizeof(hints));
287
#ifndef AI_NUMERICSERV
289
* quoting $ man getaddrinfo
292
* AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3.
293
* AI_NUMERICSERV is available since glibc 2.3.4.
295
#define AI_NUMERICSERV 0
297
hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
299
result = getaddrinfo(host, NULL, &hints, &res0);
302
fprintf(stderr,"could not resolve hostname %s because %s\n", host,gai_strerror(result));
303
if (result == EAI_SYSTEM)
304
perror("The system error is ");
309
fprintf(stderr, "Problem in resolving hostname %s: succeeded, but no information returned\n", host);
315
static void clean_cond_cache(server *srv, connection *con)
319
for (i = 0; i < srv->config_context->used; i++) {
320
data_config *dc = (data_config *)srv->config_context->data[i];
322
if (dc->comp == COMP_HTTP_REMOTEIP)
324
con->cond_cache[i].result = COND_RESULT_UNSET;
325
con->cond_cache[i].patterncount = 0;
330
URIHANDLER_FUNC(mod_extforward_uri_handler) {
331
plugin_data *p = p_d;
332
data_string *forwarded = NULL;
334
char b2[INET6_ADDRSTRLEN + 1];
335
struct addrinfo *addrlist = NULL;
337
const char *dst_addr_str = NULL;
339
array *forward_array = NULL;
340
char *real_remote_addr = NULL;
344
if (!con->request.headers) return HANDLER_GO_ON;
346
mod_extforward_patch_connection(srv, con, p);
348
if (con->conf.log_request_handling) {
349
log_error_write(srv, __FILE__, __LINE__, "s",
350
"-- mod_extforward_uri_handler called");
353
if ((NULL == (forwarded = (data_string *) array_get_element(con->request.headers,"X-Forwarded-For")) &&
354
NULL == (forwarded = (data_string *) array_get_element(con->request.headers, "Forwarded-For")))) {
356
if (con->conf.log_request_handling) {
357
log_error_write(srv, __FILE__, __LINE__, "s",
358
"no X-Forwarded-For|Forwarded-For: found, skipping");
361
return HANDLER_GO_ON;
364
/* if the remote ip itself is not trusted , then do nothing */
366
dst_addr_str = inet_ntop(con->dst_addr.plain.sa_family,
367
con->dst_addr.plain.sa_family == AF_INET6 ?
368
(struct sockaddr *)&(con->dst_addr.ipv6.sin6_addr) :
369
(struct sockaddr *)&(con->dst_addr.ipv4.sin_addr),
373
dst_addr_str = inet_ntoa(con->dst_addr.ipv4.sin_addr);
375
if (IP_UNTRUSTED == is_proxy_trusted (dst_addr_str, p) ) {
376
if (con->conf.log_request_handling) {
377
log_error_write(srv, __FILE__, __LINE__, "s",
378
"remote address is NOT a trusted proxy, skipping");
381
return HANDLER_GO_ON;
384
forward_array = extract_forward_array(forwarded->value);
386
/* Testing shows that multiple headers and multiple values in one header
387
come in _reverse_ order. So the first one we get is the last one in the request. */
388
for (i = forward_array->used - 1; i >= 0; i--) {
389
data_string *ds = (data_string *) forward_array->data[i];
391
real_remote_addr = ds->value->ptr;
394
/* bug ? bailing out here */
399
if (real_remote_addr != NULL) { /* parsed */
402
struct addrinfo *addrs_left;
404
if (con->conf.log_request_handling) {
405
log_error_write(srv, __FILE__, __LINE__, "ss",
406
"using address:", real_remote_addr);
409
addrlist = ipstr_to_sockaddr(real_remote_addr);
410
sock.plain.sa_family = AF_UNSPEC;
411
for (addrs_left = addrlist; addrs_left != NULL;
412
addrs_left = addrs_left -> ai_next) {
413
sock.plain.sa_family = addrs_left->ai_family;
414
if ( sock.plain.sa_family == AF_INET ) {
415
sock.ipv4.sin_addr = ((struct sockaddr_in*)addrs_left->ai_addr)->sin_addr;
417
} else if ( sock.plain.sa_family == AF_INET6 ) {
418
sock.ipv6.sin6_addr = ((struct sockaddr_in6*)addrs_left->ai_addr)->sin6_addr;
423
sock.ipv4.sin_addr.s_addr = inet_addr(real_remote_addr);
424
sock.plain.sa_family = (sock.ipv4.sin_addr.s_addr == 0xFFFFFFFF) ? AF_UNSPEC : AF_INET;
426
if (sock.plain.sa_family != AF_UNSPEC) {
427
/* we found the remote address, modify current connection and save the old address */
428
if (con->plugin_ctx[p->id]) {
429
log_error_write(srv, __FILE__, __LINE__, "s",
430
"patching an already patched connection!");
431
handler_ctx_free(con->plugin_ctx[p->id]);
432
con->plugin_ctx[p->id] = NULL;
434
/* save old address */
435
con->plugin_ctx[p->id] = handler_ctx_init(con->dst_addr, con->dst_addr_buf);
436
/* patch connection address */
437
con->dst_addr = sock;
438
con->dst_addr_buf = buffer_init();
439
buffer_copy_string(con->dst_addr_buf, real_remote_addr);
441
if (con->conf.log_request_handling) {
442
log_error_write(srv, __FILE__, __LINE__, "ss",
443
"patching con->dst_addr_buf for the accesslog:", real_remote_addr);
445
/* Now, clean the conf_cond cache, because we may have changed the results of tests */
446
clean_cond_cache(srv, con);
449
if (addrlist != NULL ) freeaddrinfo(addrlist);
452
array_free(forward_array);
455
return HANDLER_GO_ON;
458
CONNECTION_FUNC(mod_extforward_restore) {
459
plugin_data *p = p_d;
462
/* LEM: This seems completely unuseful, as we are not using
463
p->conf in this function. Furthermore, it brings a
464
segfault if one of the conditional configuration
465
blocks is "SERVER['socket'] == foo", because the
466
socket is not known yet in the srv/con structure.
468
/* mod_extforward_patch_connection(srv, con, p); */
470
/* restore this connection's remote ip */
471
if (con->plugin_ctx[p->id]) {
472
handler_ctx *hctx = con->plugin_ctx[p->id];
473
con->dst_addr = hctx->saved_remote_addr;
474
buffer_free(con->dst_addr_buf);
475
con->dst_addr_buf = hctx->saved_remote_addr_buf;
476
/* log_error_write(srv, __FILE__, __LINE__,"s","LEM: Reset dst_addr_buf"); */
477
handler_ctx_free(hctx);
478
con->plugin_ctx[p->id] = NULL;
479
/* Now, clean the conf_cond cache, because we may have changed the results of tests */
480
clean_cond_cache(srv, con);
482
return HANDLER_GO_ON;
486
/* this function is called at dlopen() time and inits the callbacks */
488
int mod_extforward_plugin_init(plugin *p) {
489
p->version = LIGHTTPD_VERSION_ID;
490
p->name = buffer_init_string("extforward");
492
p->init = mod_extforward_init;
493
p->handle_uri_raw = mod_extforward_uri_handler;
494
p->handle_request_done = mod_extforward_restore;
495
p->connection_reset = mod_extforward_restore;
496
p->set_defaults = mod_extforward_set_defaults;
497
p->cleanup = mod_extforward_free;