2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Various sorts of access control
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include "asterisk/network.h"
32 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__Darwin__)
34 #include <net/route.h>
38 #include <sys/sockio.h>
40 #elif defined(HAVE_GETIFADDRS)
44 #include "asterisk/acl.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/srv.h"
50 #if (!defined(SOLARIS) && !defined(HAVE_GETIFADDRS))
51 static int get_local_address(struct ast_sockaddr *ourip)
56 static void score_address(const struct sockaddr_in *sin, struct in_addr *best_addr, int *best_score)
61 address = ast_inet_ntoa(sin->sin_addr);
63 /* RFC 1700 alias for the local network */
64 if (address[0] == '0') {
66 /* RFC 1700 localnet */
67 } else if (strncmp(address, "127", 3) == 0) {
69 /* RFC 1918 non-public address space */
70 } else if (strncmp(address, "10.", 3) == 0) {
72 /* RFC 1918 non-public address space */
73 } else if (strncmp(address, "172", 3) == 0) {
74 /* 172.16.0.0 - 172.19.255.255, but not 172.160.0.0 - 172.169.255.255 */
75 if (address[4] == '1' && address[5] >= '6' && address[6] == '.') {
77 /* 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 */
78 } else if (address[4] == '2' && address[6] == '.') {
80 /* 172.30.0.0 - 172.31.255.255, but not 172.3.0.0 - 172.3.255.255 */
81 } else if (address[4] == '3' && (address[5] == '0' || address[5] == '1')) {
83 /* All other 172 addresses are public */
87 /* RFC 2544 Benchmark test range (198.18.0.0 - 198.19.255.255, but not 198.180.0.0 - 198.199.255.255) */
88 } else if (strncmp(address, "198.1", 5) == 0 && address[5] >= '8' && address[6] == '.') {
90 /* RFC 1918 non-public address space */
91 } else if (strncmp(address, "192.168", 7) == 0) {
93 /* RFC 3330 Zeroconf network */
94 } else if (strncmp(address, "169.254", 7) == 0) {
95 /*!\note Better score than a test network, but not quite as good as RFC 1918
96 * address space. The reason is that some Linux distributions automatically
97 * configure a Zeroconf address before trying DHCP, so we want to prefer a
98 * DHCP lease to a Zeroconf address.
101 /* RFC 3330 Test network */
102 } else if (strncmp(address, "192.0.2.", 8) == 0) {
104 /* Every other address should be publically routable */
109 if (score > *best_score) {
111 memcpy(best_addr, &sin->sin_addr, sizeof(*best_addr));
115 static int get_local_address(struct ast_sockaddr *ourip)
119 struct lifreq *ifr = NULL;
122 struct sockaddr_in *sa;
126 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
127 struct ifaddrs *ifap, *ifaphead;
129 const struct sockaddr_in *sin;
130 #endif /* BSD_OR_LINUX */
131 struct in_addr best_addr;
132 int best_score = -100;
133 memset(&best_addr, 0, sizeof(best_addr));
135 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
136 rtnerr = getifaddrs(&ifaphead);
141 #endif /* BSD_OR_LINUX */
143 s = socket(AF_INET, SOCK_STREAM, 0);
146 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
147 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
149 if (ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_INET) {
150 sin = (const struct sockaddr_in *) ifap->ifa_addr;
151 score_address(sin, &best_addr, &best_score);
154 if (best_score == 0) {
159 #endif /* BSD_OR_LINUX */
161 /* There is no reason whatsoever that this shouldn't work on Linux or BSD also. */
163 /* Get a count of interfaces on the machine */
164 ifn.lifn_family = AF_INET;
167 if (ioctl(s, SIOCGLIFNUM, &ifn) < 0) {
172 bufsz = ifn.lifn_count * sizeof(struct lifreq);
173 if (!(buf = malloc(bufsz))) {
177 memset(buf, 0, bufsz);
179 /* Get a list of interfaces on the machine */
180 ifc.lifc_len = bufsz;
182 ifc.lifc_family = AF_INET;
184 if (ioctl(s, SIOCGLIFCONF, &ifc) < 0) {
190 for (ifr = ifc.lifc_req, x = 0; x < ifn.lifn_count; ifr++, x++) {
191 sa = (struct sockaddr_in *)&(ifr->lifr_addr);
192 score_address(sa, &best_addr, &best_score);
195 if (best_score == 0) {
205 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
206 freeifaddrs(ifaphead);
207 #endif /* BSD_OR_LINUX */
209 if (res == 0 && ourip) {
210 ast_sockaddr_setnull(ourip);
211 ourip->ss.ss_family = AF_INET;
212 ((struct sockaddr_in *)&ourip->ss)->sin_addr = best_addr;
216 #endif /* HAVE_GETIFADDRS */
218 /* Free HA structure */
219 void ast_free_ha(struct ast_ha *ha)
229 /* Copy HA structure */
230 void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
232 ast_sockaddr_copy(&to->addr, &from->addr);
233 ast_sockaddr_copy(&to->netmask, &from->netmask);
234 to->sense = from->sense;
237 /* Create duplicate of ha structure */
238 static struct ast_ha *ast_duplicate_ha(struct ast_ha *original)
240 struct ast_ha *new_ha;
242 if ((new_ha = ast_calloc(1, sizeof(*new_ha)))) {
243 /* Copy from original to new object */
244 ast_copy_ha(original, new_ha);
250 /* Create duplicate HA link list */
251 /* Used in chan_sip2 templates */
252 struct ast_ha *ast_duplicate_ha_list(struct ast_ha *original)
254 struct ast_ha *start = original;
255 struct ast_ha *ret = NULL;
256 struct ast_ha *current, *prev = NULL;
259 current = ast_duplicate_ha(start); /* Create copy of this object */
261 prev->next = current; /* Link previous to this object */
265 ret = current; /* Save starting point */
268 start = start->next; /* Go to next object */
269 prev = current; /* Save pointer to this object */
271 return ret; /* Return start of list */
276 * Isolate a 32-bit section of an IPv6 address
278 * An IPv6 address can be divided into 4 32-bit chunks. This gives
279 * easy access to one of these chunks.
281 * \param sin6 A pointer to a struct sockaddr_in6
282 * \param index Which 32-bit chunk to operate on. Must be in the range 0-3.
284 #define V6_WORD(sin6, index) ((uint32_t *)&((sin6)->sin6_addr))[(index)]
288 * Apply a netmask to an address and store the result in a separate structure.
290 * When dealing with IPv6 addresses, one cannot apply a netmask with a simple
291 * logical and operation. Furthermore, the incoming address may be an IPv4 address
292 * and need to be mapped properly before attempting to apply a rule.
294 * \param addr The IP address to apply the mask to.
295 * \param netmask The netmask configured in the host access rule.
296 * \param result The resultant address after applying the netmask to the given address
297 * \retval 0 Successfully applied netmask
298 * \reval -1 Failed to apply netmask
300 static int apply_netmask(const struct ast_sockaddr *addr, const struct ast_sockaddr *netmask,
301 struct ast_sockaddr *result)
305 if (ast_sockaddr_is_ipv4(addr)) {
306 struct sockaddr_in result4 = { 0, };
307 struct sockaddr_in *addr4 = (struct sockaddr_in *) &addr->ss;
308 struct sockaddr_in *mask4 = (struct sockaddr_in *) &netmask->ss;
309 result4.sin_family = AF_INET;
310 result4.sin_addr.s_addr = addr4->sin_addr.s_addr & mask4->sin_addr.s_addr;
311 ast_sockaddr_from_sin(result, &result4);
312 } else if (ast_sockaddr_is_ipv6(addr)) {
313 struct sockaddr_in6 result6 = { 0, };
314 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &addr->ss;
315 struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *) &netmask->ss;
317 result6.sin6_family = AF_INET6;
318 for (i = 0; i < 4; ++i) {
319 V6_WORD(&result6, i) = V6_WORD(addr6, i) & V6_WORD(mask6, i);
321 memcpy(&result->ss, &result6, sizeof(result6));
322 result->len = sizeof(result6);
324 /* Unsupported address scheme */
333 * Parse a netmask in CIDR notation
336 * For a mask of an IPv4 address, this should be a number between 0 and 32. For
337 * a mask of an IPv6 address, this should be a number between 0 and 128. This
338 * function creates an IPv6 ast_sockaddr from the given netmask. For masks of
339 * IPv4 addresses, this is accomplished by adding 96 to the original netmask.
341 * \param[out] addr The ast_sockaddr produced from the CIDR netmask
342 * \param is_v4 Tells if the address we are masking is IPv4.
343 * \param mask_str The CIDR mask to convert
347 static int parse_cidr_mask(struct ast_sockaddr *addr, int is_v4, const char *mask_str)
351 if (sscanf(mask_str, "%30d", &mask) != 1) {
356 struct sockaddr_in sin;
357 if (mask < 0 || mask > 32) {
360 memset(&sin, 0, sizeof(sin));
361 sin.sin_family = AF_INET;
362 /* If mask is 0, then we already have the
363 * appropriate all 0s address in sin from
367 sin.sin_addr.s_addr = htonl(0xFFFFFFFF << (32 - mask));
369 ast_sockaddr_from_sin(addr, &sin);
371 struct sockaddr_in6 sin6;
373 if (mask < 0 || mask > 128) {
376 memset(&sin6, 0, sizeof(sin6));
377 sin6.sin6_family = AF_INET6;
378 for (i = 0; i < 4; ++i) {
379 /* Once mask reaches 0, we don't have
380 * to explicitly set anything anymore
381 * since sin6 was zeroed out already
384 V6_WORD(&sin6, i) = htonl(0xFFFFFFFF << (mask < 32 ? (32 - mask) : 0));
385 mask -= mask < 32 ? mask : 32;
388 memcpy(&addr->ss, &sin6, sizeof(sin6));
389 addr->len = sizeof(sin6);
395 struct ast_ha *ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
398 struct ast_ha *prev = NULL;
400 char *tmp = ast_strdupa(stuff);
401 char *address = NULL, *mask = NULL;
410 if (!(ha = ast_calloc(1, sizeof(*ha)))) {
417 address = strsep(&tmp, "/");
424 if (!ast_sockaddr_parse(&ha->addr, address, PARSE_PORT_FORBID)) {
425 ast_log(LOG_WARNING, "Invalid IP address: %s\n", address);
433 /* If someone specifies an IPv4-mapped IPv6 address,
434 * we just convert this to an IPv4 ACL
436 if (ast_sockaddr_ipv4_mapped(&ha->addr, &ha->addr)) {
437 ast_log(LOG_NOTICE, "IPv4-mapped ACL network address specified. "
438 "Converting to an IPv4 ACL network address.\n");
441 addr_is_v4 = ast_sockaddr_is_ipv4(&ha->addr);
444 parse_cidr_mask(&ha->netmask, addr_is_v4, addr_is_v4 ? "32" : "128");
445 } else if (strchr(mask, ':') || strchr(mask, '.')) {
447 /* Mask is of x.x.x.x or x:x:x:x:x:x:x:x variety */
448 if (!ast_sockaddr_parse(&ha->netmask, mask, PARSE_PORT_FORBID)) {
449 ast_log(LOG_WARNING, "Invalid netmask: %s\n", mask);
456 /* If someone specifies an IPv4-mapped IPv6 netmask,
457 * we just convert this to an IPv4 ACL
459 if (ast_sockaddr_ipv4_mapped(&ha->netmask, &ha->netmask)) {
460 ast_log(LOG_NOTICE, "IPv4-mapped ACL netmask specified. "
461 "Converting to an IPv4 ACL netmask.\n");
463 mask_is_v4 = ast_sockaddr_is_ipv4(&ha->netmask);
464 if (addr_is_v4 ^ mask_is_v4) {
465 ast_log(LOG_WARNING, "Address and mask are not using same address scheme.\n");
472 } else if (parse_cidr_mask(&ha->netmask, addr_is_v4, mask)) {
473 ast_log(LOG_WARNING, "Invalid CIDR netmask: %s\n", mask);
481 if (apply_netmask(&ha->addr, &ha->netmask, &ha->addr)) {
482 /* This shouldn't happen because ast_sockaddr_parse would
483 * have failed much earlier on an unsupported address scheme
485 char *failmask = ast_strdupa(ast_sockaddr_stringify(&ha->netmask));
486 char *failaddr = ast_strdupa(ast_sockaddr_stringify(&ha->addr));
487 ast_log(LOG_WARNING, "Unable to apply netmask %s to address %s\n", failmask, failaddr);
495 ha->sense = strncasecmp(sense, "p", 1) ? AST_SENSE_DENY : AST_SENSE_ALLOW;
505 const char *addr = ast_strdupa(ast_sockaddr_stringify(&ha->addr));
506 const char *mask = ast_strdupa(ast_sockaddr_stringify(&ha->netmask));
508 ast_debug(1, "%s/%s sense %d appended to acl for peer\n", addr, mask, ha->sense);
514 int ast_apply_ha(const struct ast_ha *ha, const struct ast_sockaddr *addr)
516 /* Start optimistic */
517 int res = AST_SENSE_ALLOW;
518 const struct ast_ha *current_ha;
520 for (current_ha = ha; current_ha; current_ha = current_ha->next) {
521 struct ast_sockaddr result;
522 struct ast_sockaddr mapped_addr;
523 const struct ast_sockaddr *addr_to_use;
524 #if 0 /* debugging code */
525 char iabuf[INET_ADDRSTRLEN];
526 char iabuf2[INET_ADDRSTRLEN];
528 ast_copy_string(iabuf, ast_inet_ntoa(sin->sin_addr), sizeof(iabuf));
529 ast_copy_string(iabuf2, ast_inet_ntoa(ha->netaddr), sizeof(iabuf2));
530 ast_debug(1, "##### Testing %s with %s\n", iabuf, iabuf2);
532 if (ast_sockaddr_is_ipv4(&ha->addr)) {
533 if (ast_sockaddr_is_ipv6(addr)) {
534 if (ast_sockaddr_is_ipv4_mapped(addr)) {
535 /* IPv4 ACLs apply to IPv4-mapped addresses */
536 ast_sockaddr_ipv4_mapped(addr, &mapped_addr);
537 addr_to_use = &mapped_addr;
539 /* An IPv4 ACL does not apply to an IPv6 address */
543 /* Address is IPv4 and ACL is IPv4. No biggie */
547 if (ast_sockaddr_is_ipv6(addr) && !ast_sockaddr_is_ipv4_mapped(addr)) {
550 /* Address is IPv4 or IPv4 mapped but ACL is IPv6. Skip */
555 /* For each rule, if this address and the netmask = the net address
556 apply the current rule */
557 if (apply_netmask(addr_to_use, ¤t_ha->netmask, &result)) {
558 /* Unlikely to happen since we know the address to be IPv4 or IPv6 */
561 if (!ast_sockaddr_cmp_addr(&result, ¤t_ha->addr)) {
562 res = current_ha->sense;
568 static int resolve_first(struct ast_sockaddr *addr, const char *name, int flag,
571 struct ast_sockaddr *addrs;
574 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
577 ast_debug(1, "Multiple addresses. Using the first only\n");
579 ast_sockaddr_copy(addr, &addrs[0]);
582 ast_log(LOG_WARNING, "Unable to lookup '%s'\n", name);
589 int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
597 snprintf(srv, sizeof(srv), "%s.%s", service, hostname);
598 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, srv)) > 0) {
603 if (resolve_first(addr, hostname, PARSE_PORT_FORBID, addr->ss.ss_family) != 0) {
608 ast_sockaddr_set_port(addr, tportno);
614 struct dscp_codepoint {
619 /* IANA registered DSCP codepoints */
621 static const struct dscp_codepoint dscp_pool1[] = {
645 int ast_str2cos(const char *value, unsigned int *cos)
649 if (sscanf(value, "%30d", &fval) == 1) {
659 int ast_str2tos(const char *value, unsigned int *tos)
664 if (sscanf(value, "%30i", &fval) == 1) {
669 for (x = 0; x < ARRAY_LEN(dscp_pool1); x++) {
670 if (!strcasecmp(value, dscp_pool1[x].name)) {
671 *tos = dscp_pool1[x].space << 2;
679 const char *ast_tos2str(unsigned int tos)
683 for (x = 0; x < ARRAY_LEN(dscp_pool1); x++) {
684 if (dscp_pool1[x].space == (tos >> 2)) {
685 return dscp_pool1[x].name;
692 int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
694 return ast_get_ip_or_srv(addr, hostname, NULL);
697 int ast_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us)
702 port = ast_sockaddr_port(us);
704 if ((s = socket(ast_sockaddr_is_ipv6(them) ? AF_INET6 : AF_INET,
705 SOCK_DGRAM, 0)) < 0) {
706 ast_log(LOG_ERROR, "Cannot create socket\n");
710 if (ast_connect(s, them)) {
711 ast_log(LOG_WARNING, "Cannot connect\n");
715 if (ast_getsockname(s, us)) {
717 ast_log(LOG_WARNING, "Cannot get socket name\n");
724 const char *them_addr = ast_strdupa(ast_sockaddr_stringify_addr(them));
725 const char *us_addr = ast_strdupa(ast_sockaddr_stringify_addr(us));
727 ast_debug(3, "For destination '%s', our source address is '%s'.\n",
731 ast_sockaddr_set_port(us, port);
736 int ast_find_ourip(struct ast_sockaddr *ourip, const struct ast_sockaddr *bindaddr, int family)
738 char ourhost[MAXHOSTNAMELEN] = "";
739 struct ast_sockaddr root;
741 /* just use the bind address if it is nonzero */
742 if (!ast_sockaddr_is_any(bindaddr)) {
743 ast_sockaddr_copy(ourip, bindaddr);
744 ast_debug(3, "Attached to given IP address\n");
747 /* try to use our hostname */
748 if (gethostname(ourhost, sizeof(ourhost) - 1)) {
749 ast_log(LOG_WARNING, "Unable to get hostname\n");
751 if (resolve_first(ourip, ourhost, PARSE_PORT_FORBID, family) == 0) {
755 ast_debug(3, "Trying to check A.ROOT-SERVERS.NET and get our IP address for that connection\n");
756 /* A.ROOT-SERVERS.NET. */
757 if (!resolve_first(&root, "A.ROOT-SERVERS.NET", PARSE_PORT_FORBID, 0) &&
758 !ast_ouraddrfor(&root, ourip)) {
761 return get_local_address(ourip);