Merged revisions 99643 via svnmerge from
[asterisk/asterisk.git] / main / acl.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Various sorts of access control
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/network.h"
31
32 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__Darwin__)
33 #include <fcntl.h>
34 #include <net/route.h>
35 #endif
36
37 #if defined(SOLARIS)
38 #include <sys/sockio.h>
39 #endif
40
41 #if defined(__Darwin__) || defined(__linux__)
42 #include <ifaddrs.h>
43 #endif
44
45 #include "asterisk/acl.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/utils.h"
48 #include "asterisk/lock.h"
49 #include "asterisk/srv.h"
50
51 static void score_address(const struct sockaddr_in *sin, struct in_addr *best_addr, int *best_score)
52 {
53         const char *address;
54         int score;
55
56         address = ast_inet_ntoa(sin->sin_addr);
57
58         /* RFC 1700 alias for the local network */
59         if (address[0] == '0')
60                 score = -25;
61         /* RFC 1700 localnet */
62         else if (strncmp(address, "127", 3) == 0)
63                 score = -20;
64         /* RFC 1918 non-public address space */
65         else if (strncmp(address, "10.", 3) == 0)
66                 score = -5;
67         /* RFC 1918 non-public address space */
68         else if (strncmp(address, "172", 3) == 0) {
69                 /* 172.16.0.0 - 172.19.255.255, but not 172.160.0.0 - 172.169.255.255 */
70                 if (address[4] == '1' && address[5] >= '6' && address[6] == '.')
71                         score = -5;
72                 /* 172.20.0.0 - 172.29.255.255, but not 172.200.0.0 - 172.255.255.255 nor 172.2.0.0 - 172.2.255.255 */
73                 else if (address[4] == '2' && address[6] == '.')
74                         score = -5;
75                 /* 172.30.0.0 - 172.31.255.255 */
76                 else if (address[4] == '3' && address[5] <= '1')
77                         score = -5;
78                 /* All other 172 addresses are public */
79                 else
80                         score = 0;
81         /* RFC 2544 Benchmark test range */
82         } else if (strncmp(address, "198.1", 5) == 0 && address[5] >= '8' && address[6] == '.')
83                 score = -10;
84         /* RFC 1918 non-public address space */
85         else if (strncmp(address, "192.168", 7) == 0)
86                 score = -5;
87         /* RFC 3330 Zeroconf network */
88         else if (strncmp(address, "169.254", 7) == 0)
89                 /*!\note Better score than a test network, but not quite as good as RFC 1918
90                  * address space.  The reason is that some Linux distributions automatically
91                  * configure a Zeroconf address before trying DHCP, so we want to prefer a
92                  * DHCP lease to a Zeroconf address.
93                  */
94                 score = -10;
95         /* RFC 3330 Test network */
96         else if (strncmp(address, "192.0.2.", 8) == 0)
97                 score = -15;
98         /* Every other address should be publically routable */
99         else
100                 score = 0;
101
102         if (score > *best_score) {
103                 *best_score = score;
104                 memcpy(best_addr, &sin->sin_addr, sizeof(*best_addr));
105         }
106 }
107
108 static int get_local_address(struct in_addr *ourip)
109 {
110         int s, res = -1;
111 #ifdef SOLARIS
112         struct lifreq *ifr = NULL;
113         struct lifnum ifn;
114         struct lifconf ifc;
115         struct sockaddr_in *sa;
116         char *buf = NULL;
117         int bufsz, x;
118 #endif /* SOLARIS */
119 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
120         struct ifaddrs *ifap, *ifaphead;
121         int rtnerr;
122         const struct sockaddr_in *sin;
123 #endif /* BSD_OR_LINUX */
124         struct in_addr best_addr = { 0, };
125         int best_score = -100;
126
127 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
128         rtnerr = getifaddrs(&ifaphead);
129         if (rtnerr) {
130                 perror(NULL);
131                 return -1;
132         }
133 #endif /* BSD_OR_LINUX */
134
135         s = socket(AF_INET, SOCK_STREAM, 0);
136
137         if (s > 0) {
138 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
139                 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
140
141                         if (ifap->ifa_addr->sa_family == AF_INET) {
142                                 sin = (const struct sockaddr_in *) ifap->ifa_addr;
143                                 score_address(sin, &best_addr, &best_score);
144                                 res = 0;
145
146                                 if (best_score == 0)
147                                         break;
148                         }
149                 }
150 #endif /* BSD_OR_LINUX */
151
152                 /* There is no reason whatsoever that this shouldn't work on Linux or BSD also. */
153 #ifdef SOLARIS
154                 /* Get a count of interfaces on the machine */
155                 ifn.lifn_family = AF_INET;
156                 ifn.lifn_flags = 0;
157                 ifn.lifn_count = 0;
158                 if (ioctl(s, SIOCGLIFNUM, &ifn) < 0) {
159                         close(s);
160                         return -1;
161                 }
162
163                 bufsz = ifn.lifn_count * sizeof(struct lifreq);
164                 if (!(buf = malloc(bufsz))) {
165                         close(s);
166                         return -1;
167                 }
168                 memset(buf, 0, bufsz);
169
170                 /* Get a list of interfaces on the machine */
171                 ifc.lifc_len = bufsz;
172                 ifc.lifc_buf = buf;
173                 ifc.lifc_family = AF_INET;
174                 ifc.lifc_flags = 0;
175                 if (ioctl(s, SIOCGLIFCONF, &ifc) < 0) {
176                         close(s);
177                         free(buf);
178                         return -1;
179                 }
180
181                 for (ifr = (struct lifreq *)buf, x = 0; x < ifn.lifn_count; ifr++, x++) {
182                         sa = (struct sockaddr_in *)&(ifr->lifr_addr);
183                         score_address(sin, &best_addr, &best_score);
184                         res = 0;
185
186                         if (best_score == 0)
187                                 break;
188                 }
189
190                 free(buf);
191 #endif /* SOLARIS */
192                 
193                 close(s);
194         }
195 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
196         freeifaddrs(ifaphead);
197 #endif /* BSD_OR_LINUX */
198
199         if (res == 0 && ourip)
200                 memcpy(ourip, &best_addr, sizeof(*ourip));
201         return res;
202 }
203 /* Free HA structure */
204 void ast_free_ha(struct ast_ha *ha)
205 {
206         struct ast_ha *hal;
207         while (ha) {
208                 hal = ha;
209                 ha = ha->next;
210                 ast_free(hal);
211         }
212 }
213
214 /* Copy HA structure */
215 static void ast_copy_ha(struct ast_ha *from, struct ast_ha *to)
216 {
217         memcpy(&to->netaddr, &from->netaddr, sizeof(from->netaddr));
218         memcpy(&to->netmask, &from->netmask, sizeof(from->netmask));
219         to->sense = from->sense;
220 }
221
222 /* Create duplicate of ha structure */
223 static struct ast_ha *ast_duplicate_ha(struct ast_ha *original)
224 {
225         struct ast_ha *new_ha;
226
227         if ((new_ha = ast_malloc(sizeof(*new_ha)))) {
228                 /* Copy from original to new object */
229                 ast_copy_ha(original, new_ha);
230         }
231
232         return new_ha;
233 }
234
235 /* Create duplicate HA link list */
236 /*  Used in chan_sip2 templates */
237 struct ast_ha *ast_duplicate_ha_list(struct ast_ha *original)
238 {
239         struct ast_ha *start = original;
240         struct ast_ha *ret = NULL;
241         struct ast_ha *link, *prev = NULL;
242
243         while (start) {
244                 link = ast_duplicate_ha(start);  /* Create copy of this object */
245                 if (prev)
246                         prev->next = link;              /* Link previous to this object */
247
248                 if (!ret)
249                         ret = link;             /* Save starting point */
250
251                 start = start->next;            /* Go to next object */
252                 prev = link;                    /* Save pointer to this object */
253         }
254         return ret;                     /* Return start of list */
255 }
256
257 struct ast_ha *ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
258 {
259         struct ast_ha *ha;
260         char *nm;
261         struct ast_ha *prev = NULL;
262         struct ast_ha *ret;
263         int x;
264         char *tmp = ast_strdupa(stuff);
265
266         ret = path;
267         while (path) {
268                 prev = path;
269                 path = path->next;
270         }
271
272         ha = ast_malloc(sizeof(*ha));
273         if (!ha)
274                 return ret;
275
276         nm = strchr(tmp, '/');
277         if (!nm) {
278                 /* assume /32. Yes, htonl does not do anything for this particular mask
279                    but we better use it to show we remember about byte order */
280                 ha->netmask.s_addr = htonl(0xFFFFFFFF);
281         } else {
282                 *nm = '\0';
283                 nm++;
284
285                 if (!strchr(nm, '.')) {
286                         if ((sscanf(nm, "%d", &x) == 1) && (x >= 0) && (x <= 32))
287                                 ha->netmask.s_addr = htonl(0xFFFFFFFF << (32 - x));
288                         else {
289                                 ast_log(LOG_WARNING, "Invalid CIDR in %s\n", stuff);
290                                 ast_free(ha);
291                                 if (error)
292                                         *error = 1;
293                                 return ret;
294                         }
295                 } else if (!inet_aton(nm, &ha->netmask)) {
296                         ast_log(LOG_WARNING, "Invalid mask in %s\n", stuff);
297                         ast_free(ha);
298                         if (error)
299                                 *error = 1;
300                         return ret;
301                 }
302         }
303
304         if (!inet_aton(tmp, &ha->netaddr)) {
305                 ast_log(LOG_WARNING, "Invalid IP address in %s\n", stuff);
306                 ast_free(ha);
307                 if (error)
308                         *error = 1;
309                 return ret;
310         }
311
312         ha->netaddr.s_addr &= ha->netmask.s_addr;
313
314         ha->sense = strncasecmp(sense, "p", 1) ? AST_SENSE_DENY : AST_SENSE_ALLOW;
315
316         ha->next = NULL;
317         if (prev) {
318                 prev->next = ha;
319         } else {
320                 ret = ha;
321         }
322
323         ast_debug(1, "%s/%s sense %d appended to acl for peer\n", ast_strdupa(ast_inet_ntoa(ha->netaddr)), ast_strdupa(ast_inet_ntoa(ha->netmask)), ha->sense);
324
325         return ret;
326 }
327
328 int ast_apply_ha(struct ast_ha *ha, struct sockaddr_in *sin)
329 {
330         /* Start optimistic */
331         int res = AST_SENSE_ALLOW;
332         while (ha) {
333 #if 0   /* debugging code */
334                 char iabuf[INET_ADDRSTRLEN];
335                 char iabuf2[INET_ADDRSTRLEN];
336                 /* DEBUG */
337                 ast_copy_string(iabuf, ast_inet_ntoa(sin->sin_addr), sizeof(iabuf));
338                 ast_copy_string(iabuf2, ast_inet_ntoa(ha->netaddr), sizeof(iabuf2));
339                 ast_debug(1, "##### Testing %s with %s\n", iabuf, iabuf2);
340 #endif
341                 /* For each rule, if this address and the netmask = the net address
342                    apply the current rule */
343                 if ((sin->sin_addr.s_addr & ha->netmask.s_addr) == ha->netaddr.s_addr)
344                         res = ha->sense;
345                 ha = ha->next;
346         }
347         return res;
348 }
349
350 int ast_get_ip_or_srv(struct sockaddr_in *sin, const char *value, const char *service)
351 {
352         struct hostent *hp;
353         struct ast_hostent ahp;
354         char srv[256];
355         char host[256];
356         int tportno = ntohs(sin->sin_port);
357         if (service) {
358                 snprintf(srv, sizeof(srv), "%s.%s", service, value);
359                 if (ast_get_srv(NULL, host, sizeof(host), &tportno, srv) > 0) {
360                         sin->sin_port = htons(tportno);
361                         value = host;
362                 }
363         }
364         hp = ast_gethostbyname(value, &ahp);
365         if (hp) {
366                 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
367         } else {
368                 ast_log(LOG_WARNING, "Unable to lookup '%s'\n", value);
369                 return -1;
370         }
371         return 0;
372 }
373
374 struct dscp_codepoint {
375         char *name;
376         unsigned int space;
377 };
378
379 /* IANA registered DSCP codepoints */
380
381 static const struct dscp_codepoint dscp_pool1[] = {
382         { "CS0", 0x00 },
383         { "CS1", 0x08 },
384         { "CS2", 0x10 },
385         { "CS3", 0x18 },
386         { "CS4", 0x20 },
387         { "CS5", 0x28 },
388         { "CS6", 0x30 },
389         { "CS7", 0x38 },
390         { "AF11", 0x0A },
391         { "AF12", 0x0C },
392         { "AF13", 0x0E },
393         { "AF21", 0x12 },
394         { "AF22", 0x14 },
395         { "AF23", 0x16 },
396         { "AF31", 0x1A },
397         { "AF32", 0x1C },
398         { "AF33", 0x1E },
399         { "AF41", 0x22 },
400         { "AF42", 0x24 },
401         { "AF43", 0x26 },
402         { "EF", 0x2E },
403 };
404
405 int ast_str2cos(const char *value, unsigned int *cos) 
406 {
407         int fval;
408         
409         if (sscanf(value, "%d", &fval) == 1) {
410                 if (fval < 8) {
411                     *cos = fval;
412                     return 0;
413                 }
414         }
415         
416         return -1;
417 }
418
419 int ast_str2tos(const char *value, unsigned int *tos)
420 {
421         int fval;
422         unsigned int x;
423
424         if (sscanf(value, "%i", &fval) == 1) {
425                 *tos = fval & 0xFF;
426                 return 0;
427         }
428
429         for (x = 0; x < sizeof(dscp_pool1) / sizeof(dscp_pool1[0]); x++) {
430                 if (!strcasecmp(value, dscp_pool1[x].name)) {
431                         *tos = dscp_pool1[x].space << 2;
432                         return 0;
433                 }
434         }
435
436         return -1;
437 }
438
439 const char *ast_tos2str(unsigned int tos)
440 {
441         unsigned int x;
442
443         for (x = 0; x < sizeof(dscp_pool1) / sizeof(dscp_pool1[0]); x++) {
444                 if (dscp_pool1[x].space == (tos >> 2))
445                         return dscp_pool1[x].name;
446         }
447
448         return "unknown";
449 }
450
451 int ast_get_ip(struct sockaddr_in *sin, const char *value)
452 {
453         return ast_get_ip_or_srv(sin, value, NULL);
454 }
455
456 int ast_ouraddrfor(struct in_addr *them, struct in_addr *us)
457 {
458         int s;
459         struct sockaddr_in sin;
460         socklen_t slen;
461
462         s = socket(PF_INET, SOCK_DGRAM, 0);
463         if (s < 0) {
464                 ast_log(LOG_ERROR, "Cannot create socket\n");
465                 return -1;
466         }
467         sin.sin_family = AF_INET;
468         sin.sin_port = 5060;
469         sin.sin_addr = *them;
470         if (connect(s, (struct sockaddr *)&sin, sizeof(sin))) {
471                 ast_log(LOG_WARNING, "Cannot connect\n");
472                 close(s);
473                 return -1;
474         }
475         slen = sizeof(sin);
476         if (getsockname(s, (struct sockaddr *)&sin, &slen)) {
477                 ast_log(LOG_WARNING, "Cannot get socket name\n");
478                 close(s);
479                 return -1;
480         }
481         close(s);
482         ast_debug(3, "Found IP address for this socket\n");
483         *us = sin.sin_addr;
484         return 0;
485 }
486
487 int ast_find_ourip(struct in_addr *ourip, struct sockaddr_in bindaddr)
488 {
489         char ourhost[MAXHOSTNAMELEN] = "";
490         struct ast_hostent ahp;
491         struct hostent *hp;
492         struct in_addr saddr;
493
494         /* just use the bind address if it is nonzero */
495         if (ntohl(bindaddr.sin_addr.s_addr)) {
496                 memcpy(ourip, &bindaddr.sin_addr, sizeof(*ourip));
497                 ast_debug(3, "Attached to given IP address\n");
498                 return 0;
499         }
500         /* try to use our hostname */
501         if (gethostname(ourhost, sizeof(ourhost) - 1)) {
502                 ast_log(LOG_WARNING, "Unable to get hostname\n");
503         } else {
504                 hp = ast_gethostbyname(ourhost, &ahp);
505                 if (hp) {
506                         memcpy(ourip, hp->h_addr, sizeof(*ourip));
507                         ast_debug(3, "Found one IP address based on local hostname %s.\n", ourhost);
508                         return 0;
509                 }
510         }
511         ast_debug(3, "Trying to check A.ROOT-SERVERS.NET and get our IP address for that connection\n");
512         /* A.ROOT-SERVERS.NET. */
513         if (inet_aton("198.41.0.4", &saddr) && !ast_ouraddrfor(&saddr, ourip))
514                 return 0;
515         return get_local_address(ourip);
516 }
517