Add *preliminary* per-peer outbound proxy (bug #2859, new patch though)
[asterisk/asterisk.git] / acl.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Various sorts of access control
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/time.h>
18 #include <signal.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <asterisk/acl.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/channel.h>
24 #include <asterisk/utils.h>
25 #include <asterisk/lock.h>
26 #include <asterisk/srv.h>
27 #include <arpa/inet.h>
28 #include <sys/socket.h>
29 #include <netdb.h>
30 #include <net/if.h>
31 #include <netinet/in_systm.h>
32 #include <netinet/ip.h>
33 #include <sys/ioctl.h>
34 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
35 #include <fcntl.h>
36 #include <net/route.h>
37
38 AST_MUTEX_DEFINE_STATIC(routeseq_lock);
39 #endif
40
41
42 struct ast_ha {
43         /* Host access rule */
44         struct in_addr netaddr;
45         struct in_addr netmask;
46         int sense;
47         struct ast_ha *next;
48 };
49
50 /* Default IP - if not otherwise set, don't breathe garbage */
51 static struct in_addr __ourip = { 0x00000000 };
52
53 struct my_ifreq {
54         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "eth0", "ppp0", etc.  */
55         struct sockaddr_in ifru_addr;
56 };
57
58 /* Free HA structure */
59 void ast_free_ha(struct ast_ha *ha)
60 {
61         struct ast_ha *hal;
62         while(ha) {
63                 hal = ha;
64                 ha = ha->next;
65                 free(hal);
66         }
67 }
68
69 /* Copy HA structure */
70 static void ast_copy_ha(struct ast_ha *from, struct ast_ha *to)
71 {
72         memcpy(&to->netaddr, &from->netaddr, sizeof(from->netaddr));
73         memcpy(&to->netmask, &from->netmask, sizeof(from->netmask));
74         to->sense = from->sense;
75 }
76
77 /* Create duplicate of ha structure */
78 static struct ast_ha *ast_duplicate_ha(struct ast_ha *original)
79 {
80         struct ast_ha *new_ha = malloc(sizeof(struct ast_ha));
81
82         /* Copy from original to new object */
83         ast_copy_ha(original, new_ha); 
84
85         return(new_ha);
86
87 }
88
89 /* Create duplicate HA link list */
90 /*  Used in chan_sip2 templates */
91 struct ast_ha *ast_duplicate_ha_list(struct ast_ha *original)
92 {
93         struct ast_ha *start=original;
94         struct ast_ha *ret = NULL;
95         struct ast_ha *link,*prev=NULL;
96
97         while(start) {
98                 link = ast_duplicate_ha(start);  /* Create copy of this object */
99                 if (prev)
100                         prev->next = link;              /* Link previous to this object */
101
102                 if (!ret) 
103                         ret = link;             /* Save starting point */
104
105                 start = start->next;            /* Go to next object */
106                 prev = link;                    /* Save pointer to this object */
107         }
108         return (ret);                           /* Return start of list */
109 }
110
111 struct ast_ha *ast_append_ha(char *sense, char *stuff, struct ast_ha *path)
112 {
113         struct ast_ha *ha = malloc(sizeof(struct ast_ha));
114         char *nm="255.255.255.255";
115         char tmp[256] = "";
116         struct ast_ha *prev = NULL;
117         struct ast_ha *ret;
118         int x,z;
119         unsigned int y;
120         ret = path;
121         while(path) {
122                 prev = path;
123                 path = path->next;
124         }
125         if (ha) {
126                 strncpy(tmp, stuff, sizeof(tmp) - 1);
127                 nm = strchr(tmp, '/');
128                 if (!nm)
129                         nm = "255.255.255.255";
130                 else {
131                         *nm = '\0';
132                         nm++;
133                 }
134                 if (!strchr(nm, '.')) {
135                         if ((sscanf(nm, "%i", &x) == 1) && (x >= 0) && (x <= 32)) {
136                                 y = 0;
137                                 for (z=0;z<x;z++) {
138                                         y >>= 1;
139                                         y |= 0x80000000;
140                                 }
141                                 ha->netmask.s_addr = htonl(y);
142                         }
143                 } else if (!inet_aton(nm, &ha->netmask)) {
144                         ast_log(LOG_WARNING, "%s not a valid netmask\n", nm);
145                         free(ha);
146                         return path;
147                 }
148                 if (!inet_aton(tmp, &ha->netaddr)) {
149                         ast_log(LOG_WARNING, "%s not a valid IP\n", tmp);
150                         free(ha);
151                         return path;
152                 }
153                 ha->netaddr.s_addr &= ha->netmask.s_addr;
154                 if (!strncasecmp(sense, "p", 1)) {
155                         ha->sense = AST_SENSE_ALLOW;
156                 } else {
157                         ha->sense = AST_SENSE_DENY;
158                 }
159                 ha->next = NULL;
160                 if (prev)
161                         prev->next = ha;
162                 else
163                         ret = ha;
164         }
165         ast_log(LOG_DEBUG, "%s/%s appended to acl for peer\n",stuff, nm);
166         return ret;
167 }
168
169 int ast_apply_ha(struct ast_ha *ha, struct sockaddr_in *sin)
170 {
171         /* Start optimistic */
172         int res = AST_SENSE_ALLOW;
173         while(ha) {
174                 char iabuf[INET_ADDRSTRLEN];
175                 char iabuf2[INET_ADDRSTRLEN];
176                 /* DEBUG */
177                 ast_log(LOG_DEBUG,
178                         "##### Testing %s with %s\n",
179                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr),
180                         ast_inet_ntoa(iabuf2, sizeof(iabuf2), ha->netaddr));
181                 /* For each rule, if this address and the netmask = the net address
182                    apply the current rule */
183                 if ((sin->sin_addr.s_addr & ha->netmask.s_addr) == (ha->netaddr.s_addr))
184                         res = ha->sense;
185                 ha = ha->next;
186         }
187         return res;
188 }
189
190 int ast_get_ip_or_srv(struct sockaddr_in *sin, const char *value, const char *service)
191 {
192         struct hostent *hp;
193         struct ast_hostent ahp;
194         char srv[256];
195         char host[256];
196         int tportno = ntohs(sin->sin_port);
197         if (service) {
198                 snprintf(srv, sizeof(srv), "%s.%s", service, value);
199                 if (ast_get_srv(NULL, host, sizeof(host), &tportno, srv) > 0) {
200                         sin->sin_port = htons(tportno);
201                         value = host;
202                 }
203         }
204         hp = ast_gethostbyname(value, &ahp);
205         if (hp) {
206                 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
207         } else {
208                 ast_log(LOG_WARNING, "Unable to lookup '%s'\n", value);
209                 return -1;
210         }
211         return 0;
212 }
213
214 int ast_get_ip(struct sockaddr_in *sin, const char *value)
215 {
216         return ast_get_ip_or_srv(sin, value, NULL);
217 }
218
219 /* iface is the interface (e.g. eth0); address is the return value */
220 int ast_lookup_iface(char *iface, struct in_addr *address) {
221         int mysock, res = 0;
222         struct my_ifreq ifreq;
223
224         memset(&ifreq, 0, sizeof(ifreq));
225         strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name) - 1);
226
227         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
228         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
229
230         close(mysock);
231         if (res < 0) {
232                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
233                 memcpy((char *)address,(char *)&__ourip,sizeof(__ourip));
234                 return -1;
235         } else {
236                 memcpy((char *)address,(char *)&ifreq.ifru_addr.sin_addr,sizeof(ifreq.ifru_addr.sin_addr));
237                 return 0;
238         }
239 }
240
241 int ast_ouraddrfor(struct in_addr *them, struct in_addr *us)
242 {
243 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
244         struct sockaddr_in *sin;
245         struct sockaddr *sa;
246         struct {
247                 struct  rt_msghdr m_rtm;
248                 char    m_space[512];
249         } m_rtmsg;
250         char iabuf[INET_ADDRSTRLEN];
251         char *cp, *p;
252         int i, l, s, seq, flags;
253         pid_t pid = getpid();
254         static int routeseq;    /* Protected by "routeseq_lock" mutex */
255
256         p = ast_strdupa(ast_inet_ntoa(iabuf, sizeof(iabuf), *them));
257         memset(us, 0, sizeof(struct in_addr));
258
259         memset(&m_rtmsg, 0, sizeof(m_rtmsg));
260         m_rtmsg.m_rtm.rtm_type = RTM_GET;
261         m_rtmsg.m_rtm.rtm_version = RTM_VERSION;
262         ast_mutex_lock(&routeseq_lock);
263         seq = ++routeseq;
264         ast_mutex_unlock(&routeseq_lock);
265         m_rtmsg.m_rtm.rtm_seq = seq;
266         m_rtmsg.m_rtm.rtm_addrs = RTA_DST | RTA_IFA;
267         m_rtmsg.m_rtm.rtm_msglen = sizeof(struct rt_msghdr) + sizeof(struct sockaddr_in);
268         sin = (struct sockaddr_in *)m_rtmsg.m_space;
269         sin->sin_family = AF_INET;
270         sin->sin_len = sizeof(struct sockaddr_in);
271         sin->sin_addr = *them;
272
273         if ((s = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC)) < 0) {
274                 ast_log(LOG_ERROR, "Error opening routing socket\n");
275                 return -1;
276         }
277         flags = fcntl(s, F_GETFL);
278         fcntl(s, F_SETFL, flags | O_NONBLOCK);
279         if (write(s, (char *)&m_rtmsg, m_rtmsg.m_rtm.rtm_msglen) < 0) {
280                 ast_log(LOG_ERROR, "Error writing to routing socket: %s\n", strerror(errno));
281                 close(s);
282                 return -1;
283         }
284         do {
285                 l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
286         } while (l > 0 && (m_rtmsg.m_rtm.rtm_seq != seq || m_rtmsg.m_rtm.rtm_pid != pid));
287         if (l < 0) {
288                 if (errno != EAGAIN)
289                         ast_log(LOG_ERROR, "Error reading from routing socket\n");
290                 close(s);
291                 return -1;
292         }
293         close(s);
294
295         if (m_rtmsg.m_rtm.rtm_version != RTM_VERSION) {
296                 ast_log(LOG_ERROR, "Unsupported route socket protocol version\n");
297                 return -1;
298         }
299
300         if (m_rtmsg.m_rtm.rtm_msglen != l)
301                 ast_log(LOG_WARNING, "Message length mismatch, in packet %d, returned %d\n",
302                                 m_rtmsg.m_rtm.rtm_msglen, l);
303
304         if (m_rtmsg.m_rtm.rtm_errno) {
305                 ast_log(LOG_ERROR, "RTM_GET got %s (%d)\n",
306                                 strerror(m_rtmsg.m_rtm.rtm_errno), m_rtmsg.m_rtm.rtm_errno);
307                 return -1;
308         }
309
310         cp = (char *)m_rtmsg.m_space;
311         if (m_rtmsg.m_rtm.rtm_addrs)
312                 for (i = 1; i; i <<= 1)
313                         if (m_rtmsg.m_rtm.rtm_addrs & i) {
314                                 sa = (struct sockaddr *)cp;
315                                 if (i == RTA_IFA && sa->sa_family == AF_INET) {
316                                         sin = (struct sockaddr_in *)sa;
317                                         *us = sin->sin_addr;
318                                         ast_log(LOG_DEBUG, "Found route to %s, output from our address %s.\n", p, ast_inet_ntoa(iabuf, sizeof(iabuf), *us));
319                                         return 0;
320                                 }
321                                 cp += sa->sa_len > 0 ?
322                                           (1 + ((sa->sa_len - 1) | (sizeof(long) - 1))) :
323                                           sizeof(long);
324                         }
325
326         ast_log(LOG_DEBUG, "No route found for address %s!\n", p);
327         return -1;
328 #else
329         FILE *PROC;
330         unsigned int remote_ip;
331         int res = 1;
332         char line[256];
333         remote_ip = them->s_addr;
334         
335         PROC = fopen("/proc/net/route","r");
336         if (!PROC) {
337                 bzero(us,sizeof(struct in_addr));
338                 return -1;
339         }
340         /* First line contains headers */
341         fgets(line,sizeof(line),PROC);
342
343         while (!feof(PROC)) {
344                 char iface[256];
345                 unsigned int dest, gateway, mask;
346                 int i,fieldnum;
347                 char *fields[40];
348
349                 fgets(line,sizeof(line),PROC);
350
351                 fieldnum = 0;
352                 for (i=0;i<sizeof(line);i++) {
353                         char *offset;
354
355                         fields[fieldnum++] = line + i;
356                         offset = strchr(line + i,'\t');
357                         if (offset == NULL) {
358                                 /* Exit loop */
359                                 break;
360                         } else if (fieldnum >= 9) {
361                                 /* Short-circuit: can't break at 8, since the end of field 7 is figured when fieldnum=8 */
362                                 break;
363                         } else {
364                                 *offset = '\0';
365                                 i = offset - line;
366                         }
367                 }
368                 if (fieldnum >= 8) {
369
370                         sscanf(fields[0],"%s",iface);
371                         sscanf(fields[1],"%x",&dest);
372                         sscanf(fields[2],"%x",&gateway);
373                         sscanf(fields[7],"%x",&mask);
374 #if 0
375                         { char iabuf[INET_ADDRSTRLEN]; 
376                         printf("Addr: %s %08x Dest: %08x Mask: %08x\n", ast_inet_ntoa(iabuf, sizeof(iabuf), *them), remote_ip, dest, mask); }
377 #endif          
378                         /* Looks simple, but here is the magic */
379                         if (((remote_ip & mask) ^ dest) == 0) {
380                                 res = ast_lookup_iface(iface,us);
381                                 break;
382                         }
383                 }
384         }
385         fclose(PROC);
386         if (res == 1) {
387                 ast_log(LOG_WARNING, "Yikes!  No default route?!!\n");
388                 bzero(us,sizeof(struct in_addr));
389                 return -2;
390         } else if (res) {
391                 /* We've already warned in subroutine */
392                 return -1;
393         }
394         return 0;
395 #endif
396 }