flowtop: rewrite presenter main handler
[netsniff-ng.git] / src / curvetun.c
blob73dc17ec5fde541ad9e9a0989f8f09ef05857eb1
1 /*
2 * curvetun - the cipherspace wormhole creator
3 * Part of the netsniff-ng project
4 * By Daniel Borkmann <daniel@netsniff-ng.org>
5 * Copyright 2011 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
6 * Copyright 2011 Emmanuel Roullit.
7 * Subject to the GPL, version 2.
9 * This is curvetun, a lightweight, high-speed ECDH multiuser IP tunnel for
10 * Linux that is based on epoll(2). curvetun uses the Linux TUN/TAP interface
11 * and supports {IPv4,IPv6} over {IPv4,IPv6} with UDP or TCP as carrier
12 * protocols. It has an integrated packet forwarding trie, thus multiple
13 * users with different IPs can be handled via a single tunnel device on the
14 * server side and flows are scheduled for processing in a CPU-local manner.
15 * For transmission, packets are being compressed and encrypted by both, the
16 * client and the server side. As an appropriate key management, public-key
17 * cryptography based on elliptic curves are being used and packets are
18 * encrypted by a symmetric stream cipher (Salsa20) and authenticated by a MAC
19 * (Poly1305), where keys have previously been computed with the ECDH key
20 * agreement protocol (Curve25519). Cryptography is based on Daniel J.
21 * Bernsteins Networking and Cryptography library (NaCl).
23 * He used often to say there was only one Road; that it was like a great
24 * river: it's springs were at every doorstep and every path was it's
25 * tributary. "It's a dangerous business, Frodo, going out of your door,"
26 * he used to say. "You step into the Road, and if you don't keep your
27 * feet, there is no telling where you might be swept off to."
29 * -- The Lord of the Rings, Frodo about his uncle Bilbo Baggins,
30 * Chapter 'Three is Company'.
33 #define _GNU_SOURCE
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <fcntl.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <getopt.h>
40 #include <errno.h>
41 #include <stdbool.h>
42 #include <limits.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/socket.h>
46 #include <sys/ptrace.h>
47 #include <netinet/in.h>
48 #include <unistd.h>
49 #include <signal.h>
51 #include "xutils.h"
52 #include "die.h"
53 #include "xmalloc.h"
54 #include "curvetun.h"
55 #include "curve.h"
56 #include "ct_usermgmt.h"
57 #include "ct_servmgmt.h"
58 #include "xio.h"
59 #include "tprintf.h"
60 #include "crypto_verify_32.h"
61 #include "crypto_box_curve25519xsalsa20poly1305.h"
62 #include "crypto_scalarmult_curve25519.h"
63 #include "crypto_auth_hmacsha512256.h"
65 #define CURVETUN_ENTROPY_SOURCE "/dev/random"
67 extern void print_stun_probe(char *server, uint16_t sport, uint16_t tunport);
69 enum working_mode {
70 MODE_UNKNOW,
71 MODE_KEYGEN,
72 MODE_EXPORT,
73 MODE_DUMPC,
74 MODE_DUMPS,
75 MODE_CLIENT,
76 MODE_SERVER,
79 volatile sig_atomic_t sigint = 0;
81 static const char *short_options = "kxc::svhp:t:d:uCS46DN";
82 static const struct option long_options[] = {
83 {"client", optional_argument, NULL, 'c'},
84 {"dev", required_argument, NULL, 'd'},
85 {"port", required_argument, NULL, 'p'},
86 {"stun", required_argument, NULL, 't'},
87 {"keygen", no_argument, NULL, 'k'},
88 {"export", no_argument, NULL, 'x'},
89 {"dumpc", no_argument, NULL, 'C'},
90 {"dumps", no_argument, NULL, 'S'},
91 {"no-logging", no_argument, NULL, 'N'},
92 {"server", no_argument, NULL, 's'},
93 {"udp", no_argument, NULL, 'u'},
94 {"ipv4", no_argument, NULL, '4'},
95 {"ipv6", no_argument, NULL, '6'},
96 {"nofork", no_argument, NULL, 'D'},
97 {"version", no_argument, NULL, 'v'},
98 {"help", no_argument, NULL, 'h'},
99 {NULL, 0, NULL, 0}
102 static void signal_handler(int number)
104 switch (number) {
105 case SIGINT:
106 sigint = 1;
107 break;
108 default:
109 break;
113 static void header(void)
115 printf("%s%s%s\n", colorize_start(bold), "curvetun "
116 VERSION_STRING, colorize_end());
119 static void help(void)
121 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n",
122 VERSION_STRING);
123 puts("http://www.netsniff-ng.org\n\n"
124 "Usage: curvetun [options]\n"
125 "Options, general:\n"
126 " -k|--keygen Generate public/private keypair\n"
127 " -x|--export Export your public data for remote servers\n"
128 " -C|--dumpc Dump parsed clients\n"
129 " -S|--dumps Dump parsed servers\n"
130 " -D|--nofork Do not daemonize\n"
131 " -d|--dev <tun> Networking tunnel device, e.g. tun0\n"
132 " -v|--version Print version\n"
133 " -h|--help Print this help\n"
134 " -c|--client[=alias] Client mode, server alias optional\n"
135 " -s|--server Server mode, options follow below\n"
136 " -N|--no-logging Disable server logging (for better anonymity)\n"
137 " -p|--port <num> Server port number (mandatory)\n"
138 " -t|--stun <server> Show public IP/Port mapping via STUN\n"
139 " -u|--udp Use UDP as carrier instead of TCP\n"
140 " -4|--ipv4 Tunnel devices are IPv4\n"
141 " -6|--ipv6 Tunnel devices are IPv6\n"
142 " (default: same as carrier protocol)\n\n"
143 "Example:\n"
144 " See Documentation/Curvetun for a configuration example.\n"
145 " curvetun --keygen\n"
146 " curvetun --export\n"
147 " curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n"
148 " curvetun --client=ethz\n\n"
149 "Note:\n"
150 " There is no default port specified, so that you are forced\n"
151 " to select your own! For client/server status messages see syslog!\n"
152 " This software is an experimental prototype intended for researchers.\n\n"
153 "Secret ingredient: 7647-14-5\n\n"
154 "Please report bugs to <bugs@netsniff-ng.org>\n"
155 "Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
156 "License: GNU GPL version 2.0\n"
157 "This is free software: you are free to change and redistribute it.\n"
158 "There is NO WARRANTY, to the extent permitted by law.\n");
159 die();
162 static void version(void)
164 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n",
165 VERSION_STRING);
166 puts("http://www.netsniff-ng.org\n\n"
167 "Please report bugs to <bugs@netsniff-ng.org>\n"
168 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
169 "License: GNU GPL version 2.0\n"
170 "This is free software: you are free to change and redistribute it.\n"
171 "There is NO WARRANTY, to the extent permitted by law.\n");
172 die();
175 static void check_file_or_die(char *home, char *file, int maybeempty)
177 char path[PATH_MAX];
178 struct stat st;
180 memset(path, 0, sizeof(path));
181 slprintf(path, sizeof(path), "%s/%s", home, file);
183 if (stat(path, &st))
184 panic("No such file %s! Type --help for further information\n",
185 path);
187 if (!S_ISREG(st.st_mode))
188 panic("%s is not a regular file!\n", path);
190 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
191 panic("You have set too many permissions on %s (%o)!\n",
192 path, st.st_mode);
194 if (maybeempty == 0 && st.st_size == 0)
195 panic("%s is empty!\n", path);
198 static void check_config_exists_or_die(char *home)
200 if (!home)
201 panic("No home dir specified!\n");
203 check_file_or_die(home, FILE_CLIENTS, 1);
204 check_file_or_die(home, FILE_SERVERS, 1);
205 check_file_or_die(home, FILE_PRIVKEY, 0);
206 check_file_or_die(home, FILE_PUBKEY, 0);
207 check_file_or_die(home, FILE_USERNAM, 0);
210 static char *fetch_home_dir(void)
212 char *home = getenv("HOME");
213 if (!home)
214 panic("No HOME defined!\n");
215 return home;
218 static void write_username(char *home)
220 int fd, ret;
221 char path[PATH_MAX];
222 char user[512];
224 memset(path, 0, sizeof(path));
225 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
227 printf("Username: [%s] ", getenv("USER"));
228 fflush(stdout);
230 memset(user, 0, sizeof(user));
231 if (fgets(user, sizeof(user), stdin) == NULL)
232 panic("Could not read from stdin!\n");
233 user[sizeof(user) - 1] = 0;
234 user[strlen(user) - 1] = 0; /* omit last \n */
235 if (strlen(user) == 0)
236 strlcpy(user, getenv("USER"), sizeof(user));
238 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
240 ret = write(fd, user, strlen(user));
241 if (ret != strlen(user))
242 panic("Could not write username!\n");
244 close(fd);
246 printf("Username written to %s!\n", path);
249 static void create_curvedir(char *home)
251 int ret;
252 char path[PATH_MAX];
254 memset(path, 0, sizeof(path));
255 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
257 errno = 0;
259 ret = mkdir(path, S_IRWXU);
260 if (ret < 0 && errno != EEXIST)
261 panic("Cannot create curvetun dir!\n");
263 printf("curvetun directory %s created!\n", path);
264 /* We also create empty files for clients and servers! */
266 memset(path, 0, sizeof(path));
267 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
269 create_or_die(path, S_IRUSR | S_IWUSR);
271 printf("Empty client file written to %s!\n", path);
273 memset(path, 0, sizeof(path));
274 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
276 create_or_die(path, S_IRUSR | S_IWUSR);
278 printf("Empty server file written to %s!\n", path);
281 static void create_keypair(char *home)
283 int fd, err = 0;
284 ssize_t ret;
285 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
286 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
287 char path[PATH_MAX];
288 const char * errstr = NULL;
290 printf("Reading from %s (this may take a while) ...\n", CURVETUN_ENTROPY_SOURCE);
292 fd = open_or_die(CURVETUN_ENTROPY_SOURCE, O_RDONLY);
294 ret = read_exact(fd, secretkey, sizeof(secretkey), 0);
295 if (ret != sizeof(secretkey)) {
296 err = EIO;
297 errstr = "Cannot read from "CURVETUN_ENTROPY_SOURCE"!\n";
298 goto out;
301 close(fd);
303 crypto_scalarmult_curve25519_base(publickey, secretkey);
305 memset(path, 0, sizeof(path));
306 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
308 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
309 if (fd < 0) {
310 err = EIO;
311 errstr = "Cannot open pubkey file!\n";
312 goto out;
315 ret = write(fd, publickey, sizeof(publickey));
316 if (ret != sizeof(publickey)) {
317 err = EIO;
318 errstr = "Cannot write public key!\n";
319 goto out;
322 close(fd);
324 printf("Public key written to %s!\n", path);
326 memset(path, 0, sizeof(path));
327 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
329 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
330 if (fd < 0) {
331 err = EIO;
332 errstr = "Cannot open privkey file!\n";
333 goto out;
336 ret = write(fd, secretkey, sizeof(secretkey));
337 if (ret != sizeof(secretkey)) {
338 err = EIO;
339 errstr = "Cannot write private key!\n";
340 goto out;
342 out:
343 close(fd);
345 xmemset(publickey, 0, sizeof(publickey));
346 xmemset(secretkey, 0, sizeof(secretkey));
348 if (err)
349 panic("%s: %s", errstr, strerror(errno));
350 else
351 printf("Private key written to %s!\n", path);
354 static void check_config_keypair_or_die(char *home)
356 int fd, err;
357 ssize_t ret;
358 const char * errstr = NULL;
359 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
360 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
361 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
362 char path[PATH_MAX];
364 memset(path, 0, sizeof(path));
365 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
367 fd = open(path, O_RDONLY);
368 if (fd < 0) {
369 err = EIO;
370 errstr = "Cannot open privkey file!\n";
371 goto out;
374 ret = read(fd, secretkey, sizeof(secretkey));
375 if (ret != sizeof(secretkey)) {
376 err = EIO;
377 errstr = "Cannot read private key!\n";
378 goto out;
381 close(fd);
383 memset(path, 0, sizeof(path));
384 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
386 fd = open(path, O_RDONLY);
387 if (fd < 0) {
388 err = EIO;
389 errstr = "Cannot open pubkey file!\n";
390 goto out;
393 ret = read(fd, publickey, sizeof(publickey));
394 if (ret != sizeof(publickey)) {
395 err = EIO;
396 errstr = "Cannot read public key!\n";
397 goto out;
400 crypto_scalarmult_curve25519_base(publicres, secretkey);
402 err = crypto_verify_32(publicres, publickey);
403 if (err) {
404 err = EINVAL;
405 errstr = "WARNING: your keypair is corrupted!!! You need to "
406 "generate new keys!!!\n";
407 goto out;
409 out:
410 close(fd);
412 xmemset(publickey, 0, sizeof(publickey));
413 xmemset(publicres, 0, sizeof(publicres));
414 xmemset(secretkey, 0, sizeof(secretkey));
416 if (err)
417 panic("%s: %s\n", errstr, strerror(errno));
420 static int main_keygen(char *home)
422 create_curvedir(home);
423 write_username(home);
424 create_keypair(home);
425 check_config_keypair_or_die(home);
427 return 0;
430 static int main_export(char *home)
432 int fd, i;
433 ssize_t ret;
434 char path[PATH_MAX], tmp[64];
436 check_config_exists_or_die(home);
437 check_config_keypair_or_die(home);
439 printf("Your exported public information:\n\n");
441 memset(path, 0, sizeof(path));
442 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
444 fd = open_or_die(path, O_RDONLY);
446 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
447 ret = write(STDOUT_FILENO, tmp, ret);
450 close(fd);
452 printf(";");
454 memset(path, 0, sizeof(path));
455 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
457 fd = open_or_die(path, O_RDONLY);
459 ret = read(fd, tmp, sizeof(tmp));
460 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
461 panic("Cannot read public key!\n");
463 for (i = 0; i < ret; ++i)
464 if (i == ret - 1)
465 printf("%02x\n\n", (unsigned char) tmp[i]);
466 else
467 printf("%02x:", (unsigned char) tmp[i]);
469 close(fd);
470 fflush(stdout);
472 return 0;
475 static int main_dumpc(char *home)
477 check_config_exists_or_die(home);
478 check_config_keypair_or_die(home);
480 printf("Your clients:\n\n");
482 parse_userfile_and_generate_user_store_or_die(home);
484 dump_user_store();
486 destroy_user_store();
488 printf("\n");
489 die();
490 return 0;
493 static int main_dumps(char *home)
495 check_config_exists_or_die(home);
496 check_config_keypair_or_die(home);
498 printf("Your servers:\n\n");
500 parse_userfile_and_generate_serv_store_or_die(home);
502 dump_serv_store();
504 destroy_serv_store();
506 printf("\n");
507 die();
508 return 0;
511 static void daemonize(const char *lockfile)
513 char pidstr[8];
514 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
515 int lfp;
517 if (getppid() == 1)
518 return;
520 if (daemon(0, 0))
521 panic("Cannot daemonize: %s", strerror(errno));
523 umask(lperm);
524 if (lockfile) {
525 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
526 S_IRUSR | S_IWUSR | S_IRGRP);
527 if (lfp < 0)
528 syslog_panic("Cannot create lockfile at %s! "
529 "curvetun server already running?\n",
530 lockfile);
532 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
533 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
534 syslog_panic("Could not write pid to pidfile %s",
535 lockfile);
537 close(lfp);
541 static int main_client(char *home, char *dev, char *alias, int daemon)
543 int ret, udp;
544 char *host, *port;
546 check_config_exists_or_die(home);
547 check_config_keypair_or_die(home);
549 parse_userfile_and_generate_serv_store_or_die(home);
551 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
552 &host, &port, &udp);
553 if (!host || !port || udp < 0)
554 panic("Did not find alias/entry in configuration!\n");
556 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
557 alias ? : "default", host, port, udp ? "udp" : "tcp");
558 if (daemon)
559 daemonize(NULL);
561 ret = client_main(home, dev, host, port, udp);
563 destroy_serv_store();
565 return ret;
568 static int main_server(char *home, char *dev, char *port, int udp,
569 int ipv4, int daemon, int log)
571 int ret;
573 check_config_exists_or_die(home);
574 check_config_keypair_or_die(home);
576 if (daemon)
577 daemonize(LOCKFILE);
579 ret = server_main(home, dev, port, udp, ipv4, log);
581 unlink(LOCKFILE);
583 return ret;
586 int main(int argc, char **argv)
588 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
589 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
590 enum working_mode wmode = MODE_UNKNOW;
592 if (getuid() != geteuid())
593 if (seteuid(getuid()));
595 home = fetch_home_dir();
597 while ((c = getopt_long(argc, argv, short_options, long_options,
598 &opt_index)) != EOF) {
599 switch (c) {
600 case 'h':
601 help();
602 break;
603 case 'v':
604 version();
605 break;
606 case 'D':
607 daemon = 0;
608 break;
609 case 'N':
610 log = 0;
611 break;
612 case 'C':
613 wmode = MODE_DUMPC;
614 break;
615 case 'S':
616 wmode = MODE_DUMPS;
617 break;
618 case 'c':
619 wmode = MODE_CLIENT;
620 if (optarg) {
621 if (*optarg == '=')
622 optarg++;
623 alias = xstrdup(optarg);
625 break;
626 case 'd':
627 dev = xstrdup(optarg);
628 break;
629 case 'k':
630 wmode = MODE_KEYGEN;
631 break;
632 case '4':
633 ipv4 = 1;
634 break;
635 case '6':
636 ipv4 = 0;
637 break;
638 case 'x':
639 wmode = MODE_EXPORT;
640 break;
641 case 's':
642 wmode = MODE_SERVER;
643 break;
644 case 'u':
645 udp = 1;
646 break;
647 case 't':
648 stun = xstrdup(optarg);
649 break;
650 case 'p':
651 port = xstrdup(optarg);
652 break;
653 case '?':
654 switch (optopt) {
655 case 't':
656 case 'd':
657 case 'u':
658 case 'p':
659 panic("Option -%c requires an argument!\n",
660 optopt);
661 default:
662 if (isprint(optopt))
663 whine("Unknown option character "
664 "`0x%X\'!\n", optopt);
665 die();
667 default:
668 break;
672 if (argc < 2)
673 help();
675 register_signal(SIGINT, signal_handler);
676 register_signal(SIGHUP, signal_handler);
677 register_signal(SIGTERM, signal_handler);
678 register_signal(SIGPIPE, signal_handler);
680 header();
682 curve25519_selftest();
684 switch (wmode) {
685 case MODE_KEYGEN:
686 ret = main_keygen(home);
687 break;
688 case MODE_EXPORT:
689 ret = main_export(home);
690 break;
691 case MODE_DUMPC:
692 ret = main_dumpc(home);
693 break;
694 case MODE_DUMPS:
695 ret = main_dumps(home);
696 break;
697 case MODE_CLIENT:
698 ret = main_client(home, dev, alias, daemon);
699 break;
700 case MODE_SERVER:
701 if (!port)
702 panic("No port specified!\n");
703 if (stun)
704 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
705 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
706 break;
707 default:
708 die();
711 if (dev)
712 xfree(dev);
713 if (stun)
714 xfree(stun);
715 if (port)
716 xfree(port);
717 if (alias)
718 xfree(alias);
720 return ret;