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