Handle IPv6 server correctly when setting $VPNGATEWAY
[platform/upstream/openconnect.git] / tun.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008 Intel Corporation.
5  *
6  * Author: David Woodhouse <dwmw2@infradead.org>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * version 2.1, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to:
19  *
20  *   Free Software Foundation, Inc.
21  *   51 Franklin Street, Fifth Floor,
22  *   Boston, MA 02110-1301 USA
23  */
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/socket.h>
28 #include <sys/ioctl.h>
29 #include <string.h>
30 #include <signal.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <netdb.h>
34 #include <netinet/in_systm.h>
35 #include <netinet/in.h>
36 #include <netinet/ip.h>
37 #include <net/if.h>
38 #include <arpa/inet.h>
39 #include <errno.h>
40 #if defined(__sun__)
41 #include <net/if_tun.h>
42 #include <stropts.h>
43 #include <sys/sockio.h>
44 #endif
45
46 #include "openconnect.h"
47
48 /*
49  * If an if_tun.h include file was found anywhere (by the Makefile), it's 
50  * included. Else, we end up assuming that we have BSD-style devices such
51  * as /dev/tun0 etc.
52  */
53 #ifdef IF_TUN_HDR
54 #include IF_TUN_HDR
55 #endif
56
57 /*
58  * The OS X tun/tap driver doesn't provide a header file; you're expected
59  * to define this for yourself.
60  */
61 #ifdef __APPLE__
62 #define TUNSIFHEAD  _IOW('t', 96, int)
63 #endif
64
65 /*
66  * OpenBSD always puts the protocol family prefix onto packets. Other
67  * systems let us enable that with the TUNSIFHEAD ioctl, and some of them
68  * (e.g. FreeBSD) _need_ it otherwise they'll interpret IPv6 packets as IPv4.
69  */
70 #if defined(__OpenBSD__) || defined(TUNSIFHEAD)
71 #define TUN_HAS_AF_PREFIX 1
72 #endif
73
74 #ifdef __sun__
75 static int local_config_tun(struct openconnect_info *vpninfo, int mtu_only)
76 {
77         if (!mtu_only)
78                 vpninfo->progress(vpninfo, PRG_ERR,
79                                   "No vpnc-script configured. Need Solaris IP-setting code\n");
80         return 0;
81 }
82 #else
83 static int local_config_tun(struct openconnect_info *vpninfo, int mtu_only)
84 {
85         struct ifreq ifr;
86         int net_fd;
87
88         net_fd = socket(PF_INET, SOCK_DGRAM, 0);
89         if (net_fd < 0) {
90                 perror("open net");
91                 return -EINVAL;
92         }
93         memset(&ifr, 0, sizeof(ifr));
94         strncpy(ifr.ifr_name, vpninfo->ifname, sizeof(ifr.ifr_name) - 1);
95
96         if (!mtu_only) {
97                 struct sockaddr_in addr;
98
99                 if (ioctl(net_fd, SIOCGIFFLAGS, &ifr) < 0)
100                         perror("SIOCGIFFLAGS");
101
102                 ifr.ifr_flags |= IFF_UP | IFF_POINTOPOINT;
103                 if (ioctl(net_fd, SIOCSIFFLAGS, &ifr) < 0)
104                         perror("SIOCSIFFLAGS");
105
106                 addr.sin_family = AF_INET;
107                 addr.sin_addr.s_addr = inet_addr(vpninfo->vpn_addr);
108                 memcpy(&ifr.ifr_addr, &addr, sizeof(addr));
109                 if (ioctl(net_fd, SIOCSIFADDR, &ifr) < 0)
110                         perror("SIOCSIFADDR");
111         }
112
113         ifr.ifr_mtu = vpninfo->mtu;
114         if (ioctl(net_fd, SIOCSIFMTU, &ifr) < 0)
115                 perror("SIOCSIFMTU");
116
117         close(net_fd);
118
119         return 0;
120 }
121 #endif
122
123 static int setenv_int(const char *opt, int value)
124 {
125         char buf[16];
126         sprintf(buf, "%d", value);
127         return setenv(opt, buf, 1);
128 }
129
130 static int netmasklen(struct in_addr addr)
131 {
132         int masklen;
133
134         for (masklen = 0; masklen < 32; masklen++) {
135                 if (ntohl(addr.s_addr) >= (0xffffffff << masklen))
136                         break;
137         }
138         return 32 - masklen;
139 }
140
141 static int process_split_xxclude(struct openconnect_info *vpninfo,
142                                  char *in_ex, char *route, int *v4_incs,
143                                  int *v6_incs)
144 {
145         struct in_addr addr;
146         char envname[80];
147         char *slash;
148
149         slash = strchr(route, '/');
150         if (!slash) {
151         badinc:
152                 vpninfo->progress(vpninfo, PRG_ERR,
153                                   "Discard bad split %sclude: \"%s\"\n",
154                                   in_ex, route);
155                 return -EINVAL;
156         }
157
158         *slash = 0;
159
160         if (strchr(route, ':')) {
161                 snprintf(envname, 79, "CISCO_IPV6_SPLIT_%sC_%d_ADDR", in_ex,
162                          *v6_incs);
163                 setenv(envname, route, 1);
164
165                 snprintf(envname, 79, "CISCO_IPV6_SPLIT_%sC_%d_MASKLEN", in_ex,
166                          *v6_incs);
167                 setenv(envname, slash+1, 1);
168
169                 (*v6_incs)++;
170                 return 0;
171         }
172                 
173         if (!inet_aton(route, &addr)) {
174                 *slash = '/';
175                 goto badinc;
176         }
177
178         envname[79] = 0;
179         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_ADDR", in_ex, *v4_incs);
180         setenv(envname, route, 1);
181
182         /* Put it back how we found it */
183         *slash = '/';
184
185         if (!inet_aton(slash+1, &addr))
186                 goto badinc;
187
188         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_MASK", in_ex, *v4_incs);
189         setenv(envname, slash+1, 1);
190
191         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_MASKLEN", in_ex, *v4_incs);
192         setenv_int(envname, netmasklen(addr));
193
194         (*v4_incs)++;
195         return 0;
196 }
197
198 static int appendenv(const char *opt, const char *new)
199 {
200         char buf[1024];
201         char *old = getenv(opt);
202
203         buf[1023] = 0;
204         if (old)
205                 snprintf(buf, 1023, "%s %s", old, new);
206         else
207                 snprintf(buf, 1023, "%s", new);
208
209         return setenv(opt, buf, 1);
210 }
211
212 static void setenv_cstp_opts(struct openconnect_info *vpninfo)
213 {
214         char *env_buf;
215         int buflen = 0;
216         int bufofs = 0;
217         struct vpn_option *opt;
218
219         for (opt = vpninfo->cstp_options; opt; opt = opt->next)
220                 buflen += 2 + strlen(opt->option) + strlen(opt->value);
221
222         env_buf = malloc(buflen + 1);
223         if (!env_buf)
224                 return;
225
226         env_buf[buflen] = 0;
227
228         for (opt = vpninfo->cstp_options; opt; opt = opt->next)
229                 bufofs += snprintf(env_buf + bufofs, buflen - bufofs,
230                                    "%s=%s\n", opt->option, opt->value);
231
232         setenv("CISCO_CSTP_OPTIONS", env_buf, 1);
233         free(env_buf);
234 }
235
236 static void set_script_env(struct openconnect_info *vpninfo)
237 {
238         char host[80];
239         int ret = getnameinfo(vpninfo->peer_addr, vpninfo->peer_addrlen, host,
240                               sizeof(host), NULL, 0, NI_NUMERICHOST);
241         if (!ret)
242                 setenv("VPNGATEWAY", host, 1);
243         setenv("TUNDEV", vpninfo->ifname, 1);
244         setenv("reason", "connect", 1);
245         unsetenv("CISCO_BANNER");
246         unsetenv("CISCO_SPLIT_INC");
247         unsetenv("CISCO_SPLIT_EXC");
248
249         setenv_int("INTERNAL_IP4_MTU", vpninfo->mtu);
250
251         if (vpninfo->vpn_addr) {
252                 setenv("INTERNAL_IP4_ADDRESS", vpninfo->vpn_addr, 1);
253                 if (vpninfo->vpn_netmask) {
254                         struct in_addr addr;
255                         struct in_addr mask;
256
257                         if (inet_aton(vpninfo->vpn_addr, &addr) &&
258                             inet_aton(vpninfo->vpn_netmask, &mask)) {
259                                 char *netaddr;
260
261                                 addr.s_addr &= mask.s_addr;
262                                 netaddr = inet_ntoa(addr);
263
264                                 setenv("INTERNAL_IP4_NETADDR", netaddr, 1);
265                                 setenv("INTERNAL_IP4_NETMASK", vpninfo->vpn_netmask, 1);
266                                 setenv_int("INTERNAL_IP4_NETMASKLEN", netmasklen(mask));
267                         }
268                 }
269         }
270         if (vpninfo->vpn_addr6) {
271                 setenv("INTERNAL_IP6_ADDRESS", vpninfo->vpn_addr6, 1);
272                 setenv("INTERNAL_IP6_NETMASK", vpninfo->vpn_netmask6, 1);
273         }
274
275         if (vpninfo->vpn_dns[0])
276                 setenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[0], 1);
277         else
278                 unsetenv("INTERNAL_IP4_DNS");
279         if (vpninfo->vpn_dns[1])
280                 appendenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[1]);
281         if (vpninfo->vpn_dns[2])
282                 appendenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[2]);
283
284         if (vpninfo->vpn_nbns[0])
285                 setenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[0], 1);
286         else
287                 unsetenv("INTERNAL_IP4_NBNS");
288         if (vpninfo->vpn_nbns[1])
289                 appendenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[1]);
290         if (vpninfo->vpn_nbns[2])
291                 appendenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[2]);
292
293         if (vpninfo->vpn_domain)
294                 setenv("CISCO_DEF_DOMAIN", vpninfo->vpn_domain, 1);
295         else unsetenv ("CISCO_DEF_DOMAIN");
296
297         if (vpninfo->vpn_proxy_pac)
298                 setenv("CISCO_PROXY_PAC", vpninfo->vpn_proxy_pac, 1);
299
300         if (vpninfo->split_includes) {
301                 struct split_include *this = vpninfo->split_includes;
302                 int nr_split_includes = 0;
303                 int nr_v6_split_includes = 0;
304
305                 while (this) {
306                         process_split_xxclude(vpninfo, "IN", this->route,
307                                               &nr_split_includes,
308                                               &nr_v6_split_includes);
309                         this = this->next;
310                 }
311                 if (nr_split_includes)
312                         setenv_int("CISCO_SPLIT_INC", nr_split_includes);
313                 if (nr_v6_split_includes)
314                         setenv_int("CISCO_IPV6_SPLIT_INC", nr_v6_split_includes);
315         }
316         if (vpninfo->split_excludes) {
317                 struct split_include *this = vpninfo->split_excludes;
318                 int nr_split_excludes = 0;
319                 int nr_v6_split_excludes = 0;
320
321                 while (this) {
322                         process_split_xxclude(vpninfo, "EX", this->route,
323                                               &nr_split_excludes,
324                                               &nr_v6_split_excludes);
325                         this = this->next;
326                 }
327                 if (nr_split_excludes)
328                         setenv_int("CISCO_SPLIT_EXC", nr_split_excludes);
329                 if (nr_v6_split_excludes)
330                         setenv_int("CISCO_IPV6_SPLIT_EXC", nr_v6_split_excludes);
331         }
332         setenv_cstp_opts(vpninfo);
333 }
334
335 static int script_config_tun(struct openconnect_info *vpninfo)
336 {
337         set_script_env(vpninfo);
338
339         system(vpninfo->vpnc_script);
340         return 0;
341 }
342
343
344 /* Set up a tuntap device. */
345 int setup_tun(struct openconnect_info *vpninfo)
346 {
347         int tun_fd;
348
349         if (vpninfo->script_tun) {
350                 pid_t child;
351                 int fds[2];
352
353                 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fds)) {
354                         perror("socketpair");
355                         exit(1);
356                 }
357                 tun_fd = fds[0];
358                 child = fork();
359                 if (child < 0) {
360                         perror("fork");
361                         exit(1);
362                 } else if (!child) {
363                         close(tun_fd);
364                         setenv_int("VPNFD", fds[1]);
365                         execl("/bin/sh", "/bin/sh", "-c", vpninfo->vpnc_script, NULL);
366                         perror("execl");
367                         exit(1);
368                 }
369                 close(fds[1]);
370                 vpninfo->script_tun = child;
371                 vpninfo->ifname = "(script)";
372         } else {
373 #ifdef IFF_TUN /* Linux */
374                 struct ifreq ifr;
375
376                 tun_fd = open("/dev/net/tun", O_RDWR);
377                 if (tun_fd < 0) {
378                         vpninfo->progress(vpninfo, PRG_ERR,
379                                           "Failed to open tun device: %s\n",
380                                           strerror(errno));
381                         exit(1);
382                 }
383                 memset(&ifr, 0, sizeof(ifr));
384                 ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
385                 if (vpninfo->ifname)
386                         strncpy(ifr.ifr_name, vpninfo->ifname,
387                                 sizeof(ifr.ifr_name) - 1);
388                 if (ioctl(tun_fd, TUNSETIFF, (void *) &ifr) < 0) {
389                         vpninfo->progress(vpninfo, PRG_ERR,
390                                           "TUNSETIFF failed: %s\n",
391                                           strerror(errno));
392                         exit(1);
393                 }
394                 if (!vpninfo->ifname)
395                         vpninfo->ifname = strdup(ifr.ifr_name);
396 #elif defined (__sun__)
397                 static char tun_name[80];
398                 int tun2_fd, ip_fd = open("/dev/ip", O_RDWR);
399                 int unit_nr, mux_id;
400                 struct ifreq ifr;
401
402                 if (ip_fd < 0) {
403                         perror("open /dev/ip");
404                         return -EIO;
405                 }
406
407                 tun_fd = open("/dev/tun", O_RDWR);
408                 if (tun_fd < 0) {
409                         perror("open /dev/tun");
410                         close(ip_fd);
411                         return -EIO;
412                 }
413
414                 unit_nr = ioctl(tun_fd, TUNNEWPPA, -1);
415                 if (unit_nr < 0) {
416                         perror("Failed to create new tun");
417                         close(tun_fd);
418                         close(ip_fd);
419                         return -EIO;
420                 }
421                 
422                 tun2_fd = open("/dev/tun", O_RDWR);
423                 if (tun2_fd < 0) {
424                         perror("open /dev/tun again");
425                         close(tun_fd);
426                         close(ip_fd);
427                         return -EIO;
428                 }
429                 if (ioctl(tun2_fd, I_PUSH, "ip") < 0) {
430                         perror("Can't push IP");
431                         close(tun2_fd);
432                         close(tun_fd);
433                         close(ip_fd);
434                         return -EIO;
435                 }
436                 if (ioctl(tun2_fd, IF_UNITSEL, &unit_nr) < 0) {
437                         perror("Can't select unit");
438                         close(tun2_fd);
439                         close(tun_fd);
440                         close(ip_fd);
441                         return -EIO;
442                 }
443                 mux_id = ioctl(ip_fd, I_PLINK, tun2_fd);
444                 if (mux_id < 0) {
445                         perror("Can't link tun to IP");
446                         close(tun2_fd);
447                         close(tun_fd);
448                         close(ip_fd);
449                         return -EIO;
450                 }
451                 close(tun2_fd);
452
453                 sprintf(tun_name, "tun%d", unit_nr);
454                 vpninfo->ifname = tun_name;
455
456                 memset(&ifr, 0, sizeof(ifr));
457                 strcpy(ifr.ifr_name, tun_name);
458                 ifr.ifr_ip_muxid = mux_id;
459
460                 if (ioctl(ip_fd, SIOCSIFMUXID, &ifr) < 0) {
461                         perror("Set mux id");
462                         close(tun_fd);
463                         ioctl(ip_fd, I_PUNLINK, mux_id);
464                         close(ip_fd);
465                         return -EIO;
466                 }
467                 /* Solaris tunctl needs this in order to tear it down */
468                 vpninfo->progress(vpninfo, PRG_DEBUG, "mux id is %d\n", mux_id);
469                 vpninfo->tun_muxid = mux_id;
470                 vpninfo->ip_fd = ip_fd;
471
472 #else /* BSD et al have /dev/tun$x devices */
473                 static char tun_name[80];
474                 int i;
475                 for (i = 0; i < 255; i++) {
476                         sprintf(tun_name, "/dev/tun%d", i);
477                         tun_fd = open(tun_name, O_RDWR);
478                         if (tun_fd >= 0)
479                                 break;
480                 }
481                 if (tun_fd < 0) {
482                         perror("open tun");
483                         exit(1);
484                 }
485                 vpninfo->ifname = tun_name + 5;
486 #ifdef TUNSIFHEAD
487                 i = 1;
488                 if (ioctl(tun_fd, TUNSIFHEAD, &i) < 0) {
489                         perror("TUNSIFHEAD");
490                         exit(1);
491                 }
492 #endif
493 #endif
494                 if (vpninfo->vpnc_script) {
495                         script_config_tun(vpninfo);
496                         /* We have to set the MTU for ourselves, because the script doesn't */
497                         local_config_tun(vpninfo, 1);
498                 } else
499                         local_config_tun(vpninfo, 0);
500         }
501
502         fcntl(tun_fd, F_SETFD, FD_CLOEXEC);
503
504         vpninfo->tun_fd = tun_fd;
505
506         if (vpninfo->select_nfds <= tun_fd)
507                 vpninfo->select_nfds = tun_fd + 1;
508
509         FD_SET(tun_fd, &vpninfo->select_rfds);
510
511         fcntl(vpninfo->tun_fd, F_SETFL, fcntl(vpninfo->tun_fd, F_GETFL) | O_NONBLOCK);
512
513         return 0;
514 }
515
516 int tun_mainloop(struct openconnect_info *vpninfo, int *timeout)
517 {
518         unsigned char buf[2000];
519         int len;
520         int work_done = 0;
521
522         if (FD_ISSET(vpninfo->tun_fd, &vpninfo->select_rfds)) {
523                 while ((len = read(vpninfo->tun_fd, buf, sizeof(buf))) > 0) {
524                         unsigned char *pkt = buf;
525 #ifdef TUN_HAS_AF_PREFIX
526                         pkt += 4;
527                         len -= 4;
528 #endif
529                         if (queue_new_packet(&vpninfo->outgoing_queue, pkt,
530                                              len))
531                                 break;
532
533                         work_done = 1;
534                         vpninfo->outgoing_qlen++;
535                         if (vpninfo->outgoing_qlen == vpninfo->max_qlen) {
536                                 FD_CLR(vpninfo->tun_fd, &vpninfo->select_rfds);
537                                 break;
538                         }
539                 }
540         } else if (vpninfo->outgoing_qlen < vpninfo->max_qlen) {
541                 FD_SET(vpninfo->tun_fd, &vpninfo->select_rfds);
542         }
543
544         /* The kernel returns -ENOMEM when the queue is full, so theoretically
545            we could handle that and retry... but it doesn't let us poll() for
546            the no-longer-full situation, so let's not bother. */
547         while (vpninfo->incoming_queue) {
548                 struct pkt *this = vpninfo->incoming_queue;
549                 unsigned char *data = this->data;
550                 int len = this->len;
551
552 #ifdef TUN_HAS_AF_PREFIX
553                 struct ip *iph = (void *)data;
554                 int type;
555
556                 if (iph->ip_v == 6)
557                         type = AF_INET6;
558                 else if (iph->ip_v == 4)
559                         type = AF_INET;
560                 else {
561                         static int complained = 0;
562                         if (!complained) {
563                                 complained = 1;
564                                 vpninfo->progress(vpninfo, PRG_ERR,
565                                                   "Unknown packet (len %d) received: %02x %02x %02x %02x...\n",
566                                                   len, data[0], data[1], data[2], data[3]);
567                         }
568                         free(this);
569                         continue;
570                 }
571                 data -= 4;
572                 len += 4;
573                 *(int *)data = htonl(type);
574 #endif
575                 vpninfo->incoming_queue = this->next;
576
577                 if (write(vpninfo->tun_fd, data, len) < 0 &&
578                     errno == ENOTCONN) {
579                         vpninfo->quit_reason = "Client connection terminated";
580                         return 1;
581                 }
582                 free(this);
583         }
584         /* Work is not done if we just got rid of packets off the queue */
585         return work_done;
586 }
587
588 void shutdown_tun(struct openconnect_info *vpninfo)
589 {       
590         if (vpninfo->script_tun) {
591                 kill(vpninfo->script_tun, SIGHUP);
592         } else {
593                 if (vpninfo->vpnc_script) {
594                         setenv("TUNDEV", vpninfo->ifname, 1);
595                         setenv("reason", "disconnect", 1);
596                         system(vpninfo->vpnc_script);
597                 }
598 #ifdef __sun__
599                 if (ioctl(vpninfo->ip_fd, I_PUNLINK, vpninfo->tun_muxid) < 0)
600                         perror("ioctl(I_PUNLINK)");
601
602                 close(vpninfo->ip_fd);
603                 vpninfo->ip_fd = -1;
604 #endif
605         }
606
607         close(vpninfo->tun_fd);
608         vpninfo->tun_fd = -1;
609 }