1 #include "base.h"
2 #include "log.h"
3 #include "buffer.h"
4 
5 #include "plugin.h"
6 
7 #include "inet_ntop_cache.h"
8 #include "configfile.h"
9 
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13 
14 #include <ctype.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdio.h>
18 #include <netinet/in.h>
19 #include <errno.h>
20 
21 /**
22  * mod_extforward.c for lighttpd, by comman.kang <at> gmail <dot> com
23  *                  extended, modified by Lionel Elie Mamane (LEM), lionel <at> mamane <dot> lu
24  *                  support chained proxies by [email protected], #1528
25  *
26  * Config example:
27  *
28  *       Trust proxy 10.0.0.232 and 10.0.0.232
29  *       extforward.forwarder = ( "10.0.0.232" => "trust",
30  *                                "10.0.0.233" => "trust" )
31  *
32  *       Trust all proxies  (NOT RECOMMENDED!)
33  *       extforward.forwarder = ( "all" => "trust")
34  *
35  *       Note that "all" has precedence over specific entries,
36  *       so "all except" setups will not work.
37  *
38  *       In case you have chained proxies, you can add all their IP's to the
39  *       config. However "all" has effect only on connecting IP, as the
40  *       X-Forwarded-For header can not be trusted.
41  *
42  * Note: The effect of this module is variable on $HTTP["remotip"] directives and
43  *       other module's remote ip dependent actions.
44  *  Things done by modules before we change the remoteip or after we reset it will match on the proxy's IP.
45  *  Things done in between these two moments will match on the real client's IP.
46  *  The moment things are done by a module depends on in which hook it does things and within the same hook
47  *  on whether they are before/after us in the module loading order
48  *  (order in the server.modules directive in the config file).
49  *
50  * Tested behaviours:
51  *
52  *  mod_access: Will match on the real client.
53  *
54  *  mod_accesslog:
55  *   In order to see the "real" ip address in access log ,
56  *   you'll have to load mod_extforward after mod_accesslog.
57  *   like this:
58  *
59  *    server.modules  = (
60  *       .....
61  *       mod_accesslog,
62  *       mod_extforward
63  *    )
64  *
65  * Known issues:
66  *      seems causing segfault with mod_ssl and $HTTP{"socket"} directives
67  *      LEM 2006.05.26: Fixed segfault $SERVER["socket"] directive. Untested with SSL.
68  *
69  * ChangeLog:
70  *     2005.12.19   Initial Version
71  *     2005.12.19   fixed conflict with conditional directives
72  *     2006.05.26   LEM: IPv6 support
73  *     2006.05.26   LEM: Fix a segfault with $SERVER["socket"] directive.
74  *     2006.05.26   LEM: Run at uri_raw time, as we don't need to see the URI
75  *                       In this manner, we run before mod_access and $HTTP["remoteip"] directives work!
76  *     2006.05.26   LEM: Clean config_cond cache of tests whose result we probably change.
77  */
78 
79 
80 /* plugin config for all request/connections */
81 
82 typedef struct {
83 	array *forwarder;
84 	array *headers;
85 } plugin_config;
86 
87 typedef struct {
88 	PLUGIN_DATA;
89 
90 	plugin_config **config_storage;
91 
92 	plugin_config conf;
93 } plugin_data;
94 
95 
96 /* context , used for restore remote ip */
97 
98 typedef struct {
99 	sock_addr saved_remote_addr;
100 	buffer *saved_remote_addr_buf;
101 } handler_ctx;
102 
103 
handler_ctx_init(sock_addr oldaddr,buffer * oldaddr_buf)104 static handler_ctx * handler_ctx_init(sock_addr oldaddr, buffer *oldaddr_buf) {
105 	handler_ctx * hctx;
106 	hctx = calloc(1, sizeof(*hctx));
107 	hctx->saved_remote_addr = oldaddr;
108 	hctx->saved_remote_addr_buf = oldaddr_buf;
109 	return hctx;
110 }
111 
handler_ctx_free(handler_ctx * hctx)112 static void handler_ctx_free(handler_ctx *hctx) {
113 	free(hctx);
114 }
115 
116 /* init the plugin data */
INIT_FUNC(mod_extforward_init)117 INIT_FUNC(mod_extforward_init) {
118 	plugin_data *p;
119 	p = calloc(1, sizeof(*p));
120 	return p;
121 }
122 
123 /* destroy the plugin data */
FREE_FUNC(mod_extforward_free)124 FREE_FUNC(mod_extforward_free) {
125 	plugin_data *p = p_d;
126 
127 	UNUSED(srv);
128 
129 	if (!p) return HANDLER_GO_ON;
130 
131 	if (p->config_storage) {
132 		size_t i;
133 
134 		for (i = 0; i < srv->config_context->used; i++) {
135 			plugin_config *s = p->config_storage[i];
136 
137 			if (!s) continue;
138 
139 			array_free(s->forwarder);
140 			array_free(s->headers);
141 
142 			free(s);
143 		}
144 		free(p->config_storage);
145 	}
146 
147 
148 	free(p);
149 
150 	return HANDLER_GO_ON;
151 }
152 
153 /* handle plugin config and check values */
154 
SETDEFAULTS_FUNC(mod_extforward_set_defaults)155 SETDEFAULTS_FUNC(mod_extforward_set_defaults) {
156 	plugin_data *p = p_d;
157 	size_t i = 0;
158 
159 	config_values_t cv[] = {
160 		{ "extforward.forwarder",       NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
161 		{ "extforward.headers",         NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },       /* 1 */
162 		{ NULL,                         NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
163 	};
164 
165 	if (!p) return HANDLER_ERROR;
166 
167 	p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
168 
169 	for (i = 0; i < srv->config_context->used; i++) {
170 		plugin_config *s;
171 
172 		s = calloc(1, sizeof(plugin_config));
173 		s->forwarder    = array_init();
174 		s->headers      = array_init();
175 
176 		cv[0].destination = s->forwarder;
177 		cv[1].destination = s->headers;
178 
179 		p->config_storage[i] = s;
180 
181 		if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) {
182 			return HANDLER_ERROR;
183 		}
184 	}
185 
186 	return HANDLER_GO_ON;
187 }
188 
189 #define PATCH(x) \
190 	p->conf.x = s->x;
mod_extforward_patch_connection(server * srv,connection * con,plugin_data * p)191 static int mod_extforward_patch_connection(server *srv, connection *con, plugin_data *p) {
192 	size_t i, j;
193 	plugin_config *s = p->config_storage[0];
194 
195 	PATCH(forwarder);
196 	PATCH(headers);
197 
198 	/* skip the first, the global context */
199 	for (i = 1; i < srv->config_context->used; i++) {
200 		data_config *dc = (data_config *)srv->config_context->data[i];
201 		s = p->config_storage[i];
202 
203 		/* condition didn't match */
204 		if (!config_check_cond(srv, con, dc)) continue;
205 
206 		/* merge config */
207 		for (j = 0; j < dc->value->used; j++) {
208 			data_unset *du = dc->value->data[j];
209 
210 			if (buffer_is_equal_string(du->key, CONST_STR_LEN("extforward.forwarder"))) {
211 				PATCH(forwarder);
212 			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("extforward.headers"))) {
213 				PATCH(headers);
214 			}
215 		}
216 	}
217 
218 	return 0;
219 }
220 #undef PATCH
221 
222 
put_string_into_array_len(array * ary,const char * str,int len)223 static void put_string_into_array_len(array *ary, const char *str, int len)
224 {
225 	data_string *tempdata;
226 	if (len == 0)
227 		return;
228 	tempdata = data_string_init();
229 	buffer_copy_string_len(tempdata->value,str,len);
230 	array_insert_unique(ary,(data_unset *)tempdata);
231 }
232 /*
233    extract a forward array from the environment
234 */
extract_forward_array(buffer * pbuffer)235 static array *extract_forward_array(buffer *pbuffer)
236 {
237 	array *result = array_init();
238 	if (pbuffer->used > 0) {
239 		char *base, *curr;
240 		/* state variable, 0 means not in string, 1 means in string */
241 		int in_str = 0;
242 		for (base = pbuffer->ptr, curr = pbuffer->ptr; *curr; curr++) {
243 			if (in_str) {
244 				if ((*curr > '9' || *curr < '0') && *curr != '.' && *curr != ':' && (*curr < 'a' || *curr > 'f') && (*curr < 'A' || *curr > 'F')) {
245 					/* found an separator , insert value into result array */
246 					put_string_into_array_len(result, base, curr - base);
247 					/* change state to not in string */
248 					in_str = 0;
249 				}
250 			} else {
251 				if ((*curr >= '0' && *curr <= '9') || *curr == ':' || (*curr >= 'a' && *curr <= 'f') || (*curr >= 'A' && *curr <= 'F')) {
252 					/* found leading char of an IP address, move base pointer and change state */
253 					base = curr;
254 					in_str = 1;
255 				}
256 			}
257 		}
258 		/* if breaking out while in str, we got to the end of string, so add it */
259 		if (in_str) {
260 			put_string_into_array_len(result, base, curr - base);
261 		}
262 	}
263 	return result;
264 }
265 
266 #define IP_TRUSTED 1
267 #define IP_UNTRUSTED 0
268 /*
269  * check whether ip is trusted, return 1 for trusted , 0 for untrusted
270  */
is_proxy_trusted(const char * ipstr,plugin_data * p)271 static int is_proxy_trusted(const char *ipstr, plugin_data *p)
272 {
273 	data_string* allds = (data_string *)array_get_element(p->conf.forwarder, "all");
274 
275 	if (allds) {
276 		if (strcasecmp(allds->value->ptr, "trust") == 0) {
277 			return IP_TRUSTED;
278 		} else {
279 			return IP_UNTRUSTED;
280 		}
281 	}
282 
283 	return (data_string *)array_get_element(p->conf.forwarder, ipstr) ? IP_TRUSTED : IP_UNTRUSTED;
284 }
285 
286 /*
287  * Return char *ip of last address of proxy that is not trusted.
288  * Do not accept "all" keyword here.
289  */
last_not_in_array(array * a,plugin_data * p)290 static const char *last_not_in_array(array *a, plugin_data *p)
291 {
292 	array *forwarder = p->conf.forwarder;
293 	int i;
294 
295 	for (i = a->used - 1; i >= 0; i--) {
296 		data_string *ds = (data_string *)a->data[i];
297 		const char *ip = ds->value->ptr;
298 
299 		if (!array_get_element(forwarder, ip)) {
300 			return ip;
301 		}
302 	}
303 	return NULL;
304 }
305 
ipstr_to_sockaddr(server * srv,const char * host)306 static struct addrinfo *ipstr_to_sockaddr(server *srv, const char *host) {
307 	struct addrinfo hints, *res0;
308 	int result;
309 
310 	memset(&hints, 0, sizeof(hints));
311 #ifndef AI_NUMERICSERV
312 	/**
313 	  * quoting $ man getaddrinfo
314 	  *
315 	  * NOTES
316 	  *        AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3.
317 	  *        AI_NUMERICSERV is available since glibc 2.3.4.
318 	  */
319 #define AI_NUMERICSERV 0
320 #endif
321 	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
322 
323 	errno = 0;
324 	result = getaddrinfo(host, NULL, &hints, &res0);
325 
326 	if (result != 0) {
327 		log_error_write(srv, __FILE__, __LINE__, "SSSs(S)",
328 			"could not resolve hostname ", host, " because ", gai_strerror(result), strerror(errno));
329 
330 		return NULL;
331 	} else if (res0 == NULL) {
332 		log_error_write(srv, __FILE__, __LINE__, "SSS",
333 			"Problem in resolving hostname ", host, ": succeeded, but no information returned");
334 	}
335 
336 	return res0;
337 }
338 
339 
340 
clean_cond_cache(server * srv,connection * con)341 static void clean_cond_cache(server *srv, connection *con) {
342 	config_cond_cache_reset_item(srv, con, COMP_HTTP_REMOTE_IP);
343 }
344 
URIHANDLER_FUNC(mod_extforward_uri_handler)345 URIHANDLER_FUNC(mod_extforward_uri_handler) {
346 	plugin_data *p = p_d;
347 	data_string *forwarded = NULL;
348 #ifdef HAVE_IPV6
349 	char b2[INET6_ADDRSTRLEN + 1];
350 	struct addrinfo *addrlist = NULL;
351 #endif
352 	const char *dst_addr_str = NULL;
353 	array *forward_array = NULL;
354 	const char *real_remote_addr = NULL;
355 #ifdef HAVE_IPV6
356 #endif
357 
358 	if (!con->request.headers) return HANDLER_GO_ON;
359 
360 	mod_extforward_patch_connection(srv, con, p);
361 
362 	if (con->conf.log_request_handling) {
363 		log_error_write(srv, __FILE__, __LINE__, "s",
364 			"-- mod_extforward_uri_handler called");
365 	}
366 
367 	if (p->conf.headers->used) {
368 		data_string *ds;
369 		size_t k;
370 
371 		for(k = 0; k < p->conf.headers->used; k++) {
372 			ds = (data_string *) p->conf.headers->data[k];
373 			if (NULL != (forwarded = (data_string*) array_get_element(con->request.headers, ds->value->ptr))) break;
374 		}
375 	} else {
376 		forwarded = (data_string *) array_get_element(con->request.headers,"X-Forwarded-For");
377 		if (NULL == forwarded) forwarded = (data_string *) array_get_element(con->request.headers,  "Forwarded-For");
378 	}
379 
380 	if (NULL == forwarded) {
381 		if (con->conf.log_request_handling) {
382 			log_error_write(srv, __FILE__, __LINE__, "s", "no forward header found, skipping");
383 		}
384 
385 		return HANDLER_GO_ON;
386 	}
387 
388 #ifdef HAVE_IPV6
389 	dst_addr_str = inet_ntop(con->dst_addr.plain.sa_family,
390 		con->dst_addr.plain.sa_family == AF_INET6 ?
391 			(struct sockaddr *)&(con->dst_addr.ipv6.sin6_addr) :
392 			(struct sockaddr *)&(con->dst_addr.ipv4.sin_addr),
393 		b2, (sizeof b2) - 1);
394 #else
395 	dst_addr_str = inet_ntoa(con->dst_addr.ipv4.sin_addr);
396 #endif
397 
398 	/* if the remote ip itself is not trusted, then do nothing */
399 	if (IP_UNTRUSTED == is_proxy_trusted(dst_addr_str, p)) {
400 		if (con->conf.log_request_handling) {
401 			log_error_write(srv, __FILE__, __LINE__, "sss",
402 					"remote address", dst_addr_str, "is NOT a trusted proxy, skipping");
403 		}
404 
405 		return HANDLER_GO_ON;
406 	}
407 
408 	/* build forward_array from forwarded data_string */
409 	forward_array = extract_forward_array(forwarded->value);
410 	real_remote_addr = last_not_in_array(forward_array, p);
411 
412 	if (real_remote_addr != NULL) { /* parsed */
413 		sock_addr sock;
414 		struct addrinfo *addrs_left;
415 		server_socket *srv_sock = con->srv_socket;
416 		data_string *forwarded_proto = (data_string *)array_get_element(con->request.headers, "X-Forwarded-Proto");
417 
418 		if (forwarded_proto && !strcmp(forwarded_proto->value->ptr, "https")) {
419 			srv_sock->is_proxy_ssl = 1;
420 		} else {
421 			srv_sock->is_proxy_ssl = 0;
422 		}
423 
424 		if (con->conf.log_request_handling) {
425  			log_error_write(srv, __FILE__, __LINE__, "ss", "using address:", real_remote_addr);
426 		}
427 #ifdef HAVE_IPV6
428 		addrlist = ipstr_to_sockaddr(srv, real_remote_addr);
429 		sock.plain.sa_family = AF_UNSPEC;
430 		for (addrs_left = addrlist; addrs_left != NULL; addrs_left = addrs_left -> ai_next) {
431 			sock.plain.sa_family = addrs_left->ai_family;
432 			if (sock.plain.sa_family == AF_INET) {
433 				sock.ipv4.sin_addr = ((struct sockaddr_in*)addrs_left->ai_addr)->sin_addr;
434 				break;
435 			} else if (sock.plain.sa_family == AF_INET6) {
436 				sock.ipv6.sin6_addr = ((struct sockaddr_in6*)addrs_left->ai_addr)->sin6_addr;
437 				break;
438 			}
439 		}
440 #else
441 		UNUSED(addrs_left);
442 		sock.ipv4.sin_addr.s_addr = inet_addr(real_remote_addr);
443 		sock.plain.sa_family = (sock.ipv4.sin_addr.s_addr == 0xFFFFFFFF) ? AF_UNSPEC : AF_INET;
444 #endif
445 		if (sock.plain.sa_family != AF_UNSPEC) {
446 			/* we found the remote address, modify current connection and save the old address */
447 			if (con->plugin_ctx[p->id]) {
448 				log_error_write(srv, __FILE__, __LINE__, "s",
449 						"patching an already patched connection!");
450 				handler_ctx_free(con->plugin_ctx[p->id]);
451 				con->plugin_ctx[p->id] = NULL;
452 			}
453 			/* save old address */
454 			con->plugin_ctx[p->id] = handler_ctx_init(con->dst_addr, con->dst_addr_buf);
455 			/* patch connection address */
456 			con->dst_addr = sock;
457 			con->dst_addr_buf = buffer_init();
458 			buffer_copy_string(con->dst_addr_buf, real_remote_addr);
459 
460 			if (con->conf.log_request_handling) {
461 				log_error_write(srv, __FILE__, __LINE__, "ss",
462 						"patching con->dst_addr_buf for the accesslog:", real_remote_addr);
463 			}
464 			/* Now, clean the conf_cond cache, because we may have changed the results of tests */
465 			clean_cond_cache(srv, con);
466 		}
467 #ifdef HAVE_IPV6
468 		if (addrlist != NULL ) freeaddrinfo(addrlist);
469 #endif
470 	}
471 	array_free(forward_array);
472 
473 	/* not found */
474 	return HANDLER_GO_ON;
475 }
476 
CONNECTION_FUNC(mod_extforward_restore)477 CONNECTION_FUNC(mod_extforward_restore) {
478 	plugin_data *p = p_d;
479 	handler_ctx *hctx = con->plugin_ctx[p->id];
480 
481 	if (!hctx) return HANDLER_GO_ON;
482 
483 	con->dst_addr = hctx->saved_remote_addr;
484 	buffer_free(con->dst_addr_buf);
485 
486 	con->dst_addr_buf = hctx->saved_remote_addr_buf;
487 
488 	handler_ctx_free(hctx);
489 
490 	con->plugin_ctx[p->id] = NULL;
491 
492 	/* Now, clean the conf_cond cache, because we may have changed the results of tests */
493 	clean_cond_cache(srv, con);
494 
495 	return HANDLER_GO_ON;
496 }
497 
498 
499 /* this function is called at dlopen() time and inits the callbacks */
500 
501 int mod_extforward_plugin_init(plugin *p);
mod_extforward_plugin_init(plugin * p)502 int mod_extforward_plugin_init(plugin *p) {
503 	p->version     = LIGHTTPD_VERSION_ID;
504 	p->name        = buffer_init_string("extforward");
505 
506 	p->init        = mod_extforward_init;
507 	p->handle_uri_raw = mod_extforward_uri_handler;
508 	p->handle_request_done = mod_extforward_restore;
509 	p->connection_reset = mod_extforward_restore;
510 	p->set_defaults  = mod_extforward_set_defaults;
511 	p->cleanup     = mod_extforward_free;
512 
513 	p->data        = NULL;
514 
515 	return 0;
516 }
517 
518