aboutsummaryrefslogtreecommitdiff
path: root/src/remoteip.c
blob: 2966eca6c216af3d99fdafd05c4e63efc1354c31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/* This file is part of Ping903
   Copyright (C) 2020 Sergey Poznyakoff
  
   Ping903 is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
  
   Ping903 is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with Ping903.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <microhttpd.h>
#include "ping903.h"
#include "json.h"
#include "defs.h"

/* Returns 1 if ADDR is a valid string representation of IPv4 address */
static int
str_is_ipv4(const char *addr)
{
	int dot_count = 0;
	int digit_count = 0;
	
	for (; *addr; addr++) {
		if (!isascii(*addr))
			return 0;
		if (*addr == '.') {
			if (++dot_count > 3)
				break;
			digit_count = 0;
		}
		else if (!(isdigit(*addr) && ++digit_count <= 3))
			return 0;
	}
	return (dot_count == 3);
}

#define PFXSTR_IPV4_MAPPED "::ffff"
#define PFXLEN_IPV4_MAPPED (sizeof PFXSTR_IPV4_MAPPED - 1)

static int
str_is_ipv4mapped(const char *addr)
{
	return strlen(addr) > PFXLEN_IPV4_MAPPED
		&& strncasecmp(PFXSTR_IPV4_MAPPED, addr, PFXLEN_IPV4_MAPPED)
		    == 0
		&& str_is_ipv4(addr + PFXLEN_IPV4_MAPPED);
}		

/* Returns 1 if ADDR is a valid IPv6 address */
static int
str_is_ipv6(const char *addr)
{
	int col_count = 0; /* Number of colons */
	int dcol = 0;      /* Did we encounter a double-colon? */
	int dig_count = 0; /* Number of digits in the last group */

	for (; *addr; addr++) {
		if (!isascii (*addr))
			return 0;
		else if (isxdigit(*addr)) {
			if (++dig_count > 4)
				return 0;
		} else if (*addr == ':') {
			if (col_count && dig_count == 0 && ++dcol > 1)
				return 0;
			if (++col_count > 7)
				return 0;
			dig_count = 0;
		}
		else
			return 0;
	}
	return (col_count == 7 || dcol);
}

/* Max. number of bytes in an IPv6 address */
#define MU_INADDR_BYTES 16

/* CIDR representation */
struct cidr {
	int family;        /* Address family */
	int len;           /* Number of bytes in the address */
	unsigned char address[MU_INADDR_BYTES];
	unsigned char netmask[MU_INADDR_BYTES];
	char *str;         /* String representation */
	struct cidr *next; /* Next CIDR in list */
};

static void
uint32_to_bytes(unsigned char *bytes, uint32_t u)
{
  int i;
  
  for (i = 0; i < 4; i++)
    {
      bytes[i] = u & 0xff;
      u >>= 8;
    }
}

static int
inaddr_to_bytes(int af, void *buf, unsigned char *bytes)
{
	uint32_t u;
  
	switch (af) {
	case AF_INET:
		memcpy(&u, buf, sizeof u);
		uint32_to_bytes (bytes, u);
		return 4;

	case AF_INET6:
		memcpy(bytes, buf, 16);
		return 16;
	}
	
	abort();
}

/* Fill in the BUF (LEN bytes long) with a network mask corresponding to
   the mask length MASKLEN */
static void
masklen_to_netmask(unsigned char *buf, size_t len, size_t masklen)
{
	int i, cnt;

	cnt = masklen / 8;
	for (i = 0; i < cnt; i++)
		buf[i] = 0xff;
	if (i == len)
		return;
	cnt = 8 - masklen % 8;
	buf[i++] = (0xff >> cnt) << cnt;
	for (; i < len; i++)
		buf[i] = 0;
}

/* Convert string STR to CIDR. Return 0 on success and -1 on failure. */
static int
str_to_cidr(char const *str, struct cidr *cidr,
	    char const *file, unsigned line)
{
	int rc;
	char *ipbuf, *ipstart;
	union {
		struct in_addr in;
		struct in6_addr in6;
	} inaddr;
	size_t len;
	char *p;

	cidr->str = estrdup(str);
	p = strrchr(str, '/');
	if (p)
		len = p - str;
	else
		len = strlen (str);

	ipbuf = emalloc(len+1);
	memcpy(ipbuf, str, len);
	ipbuf[len] = 0;
	ipstart = ipbuf;
	
	if (str_is_ipv4(ipstart))
		cidr->family = AF_INET;
	else if (str_is_ipv4mapped(ipstart)) {
		cidr->family = AF_INET;
		ipstart += PFXLEN_IPV4_MAPPED;
	} else if (str_is_ipv6(ipbuf))
		cidr->family = AF_INET6;
	else {
		free(ipbuf);
		error("%s:%d: invalid CIDR: %s", file, line, str);
		return -1;
	}
	
	rc = inet_pton(cidr->family, ipstart, &inaddr);
	free(ipbuf);

	if (rc != 1) {
		if (rc == -1) {
			error("%s:%d: invalid address family", file, line);
			return -1;
		}
		if (rc == 0) {
			error("%s:%d: invalid IPv%s address: %s",
			      file, line,
			      cidr->family == AF_INET ? "4" : "6",
			      str);
			return -1;
		}
	}

	cidr->len = inaddr_to_bytes(cidr->family, &inaddr, cidr->address);

	if (p) {
		char *end;
		unsigned long masklen;
      
		p++;

		masklen = strtoul(p, &end, 10);
		if (*end == 0)
			masklen_to_netmask(cidr->netmask, cidr->len, masklen);
		else if ((cidr->family == AF_INET && str_is_ipv4(p))
			 || (cidr->family == AF_INET6 && str_is_ipv6(p))) {
			rc = inet_pton(cidr->family, p, &inaddr);
			if (rc != 1) {
				error(file, line, "bad netmask: %s",
				      file, line, p);
				return -1;
			}
			inaddr_to_bytes(cidr->family, &inaddr, cidr->netmask);
		} else {
			error("%s:%d: bad CIDR (near %s)", file, line, p);
			return -1;
		}
	} else
		masklen_to_netmask(cidr->netmask, cidr->len, cidr->len * 8);
	return 0;
}

/* A is a valid CIDR, and B is a valid IP address represented as CIDR.
   Return 0 if B falls within A */
static int
cidr_match(struct cidr *a, struct cidr *b)
{
	int i;

	if (a->family != b->family)
		return 1;
	for (i = 0; i < a->len; i++) {
		if (a->address[i] != (b->address[i] & a->netmask[i]))
			return 1;
	}
	return 0;
}

struct cidr *trusted_ip_list;

int
cf_trusted_ip(int mode, union cf_callback_arg *arg, void *data)
{
	if (mode == CF_PARSE) {
		struct cidr *cidr = emalloc(sizeof(cidr[0]));
		
		if (str_to_cidr(arg->input.val, cidr,
				arg->input.file, arg->input.line)) {
			free(cidr);
			return CF_RET_FAIL;
		}
		cidr->next = trusted_ip_list;
		trusted_ip_list = cidr;
	} else {
		struct cidr *cidr;		
		struct json_value *ar = json_new_array();

		for (cidr = trusted_ip_list; cidr; cidr = cidr->next) {
			struct json_value *v;

			if (!(v = json_new_string(cidr->str)))
				goto err;
			if (json_array_append(ar, v)) {
				json_value_free(v);
				goto err;
			}
		}				
		
		arg->output = ar;
		return CF_RET_OK;
	  err:
		json_value_free(ar);
		return CF_RET_FAIL;
	}
	return CF_RET_OK;
}

int
cf_trusted_ip_heredoc(int mode, union cf_callback_arg *arg, void *data)
{
	struct cidr *cidr;
	
	if (mode == CF_SERIALIZE)
		return CF_RET_IGNORE;
	
	cidr = emalloc(sizeof(cidr[0]));
		
	if (str_to_cidr(arg->heredoc.val, cidr,
			arg->heredoc.file, arg->heredoc.line)) {
		free(cidr);
		return CF_RET_FAIL;
	}
	cidr->next = trusted_ip_list;
	trusted_ip_list = cidr;

	return CF_RET_OK;
}

static int
is_trusted_ip(char const *ipstr)
{
	struct cidr cidr;
	struct cidr *p;
	
	if (str_to_cidr(ipstr, &cidr, __FILE__, __LINE__))
		return 0;
	for (p = trusted_ip_list; p; p = p->next) {
		if (cidr_match(p, &cidr) == 0)
			return 1;
	}
	return 0;
}	

static char *
scan_forwarded_header(char const *hdr)
{
	char const *end;
	char *buf = NULL;
	size_t bufsize = 0;
	
	end = hdr + strlen(hdr);
	while (end > hdr) {
		char const *p;
		size_t len, i, j;
		
		for (p = end - 1; p > hdr && *p != ','; p--)
			;
		len = end - p;
		if (len + 1 > bufsize) {
			char *newbuf = realloc(buf, len + 1);
			if (newbuf) {
				buf = newbuf;
				bufsize = len + 1;
			} else {
				free(buf);
				return NULL;
			}
		}

		i = 0;
		j = 0;
		if (*p == ',')
			j++;
		while (j < len && isspace(p[j]))
			j++;
		while (j < len) {
			if (isspace(p[j]))
				break;
			buf[i++] = p[j++];
		}
		buf[i] = 0;

		if (!is_trusted_ip(buf))
			return buf;

		end = p;
	}
	free(buf);		
	return 0;
}

char *
get_remote_ip(struct MHD_Connection *conn)
{
	union MHD_ConnectionInfo const *ci;
        char ipstr[NI_MAXHOST];
	char const *hdr;
	char *ret;
	
	hdr = MHD_lookup_connection_value(conn,
					  MHD_HEADER_KIND,
					  "x-forwarded-from");
	if (hdr && (ret = scan_forwarded_header(hdr)) != NULL)
		return ret;
	
	ci = MHD_get_connection_info(conn,
				     MHD_CONNECTION_INFO_CLIENT_ADDRESS,
				     NULL);
	if (!ci)
		return NULL;

	if (getnameinfo(ci->client_addr, sizeof(struct sockaddr),
			ipstr, sizeof(ipstr), NULL, 0,
			NI_NUMERICHOST))
		return NULL;
	return strdup(ipstr);
}

Return to:

Send suggestions and report system problems to the System administrator.