xio: add nacl's randombyte function
[netsniff-ng.git] / curvetun.c
blob3593aca271949bee131de5478d527f326a058912
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 <sys/fsuid.h>
48 #include <netinet/in.h>
49 #include <unistd.h>
50 #include <signal.h>
52 #include "xutils.h"
53 #include "die.h"
54 #include "xmalloc.h"
55 #include "curvetun.h"
56 #include "curve.h"
57 #include "ct_usermgmt.h"
58 #include "ct_servmgmt.h"
59 #include "xio.h"
60 #include "tprintf.h"
61 #include "crypto_verify_32.h"
62 #include "crypto_box_curve25519xsalsa20poly1305.h"
63 #include "crypto_scalarmult_curve25519.h"
64 #include "crypto_auth_hmacsha512256.h"
66 #define CURVETUN_ENTROPY_SOURCE "/dev/random"
68 extern void print_stun_probe(char *server, uint16_t sport, uint16_t tunport);
70 enum working_mode {
71 MODE_UNKNOW,
72 MODE_KEYGEN,
73 MODE_EXPORT,
74 MODE_DUMPC,
75 MODE_DUMPS,
76 MODE_CLIENT,
77 MODE_SERVER,
80 volatile sig_atomic_t sigint = 0;
82 static const char *short_options = "kxc::svhp:t:d:uCS46DN";
83 static const struct option long_options[] = {
84 {"client", optional_argument, NULL, 'c'},
85 {"dev", required_argument, NULL, 'd'},
86 {"port", required_argument, NULL, 'p'},
87 {"stun", required_argument, NULL, 't'},
88 {"keygen", no_argument, NULL, 'k'},
89 {"export", no_argument, NULL, 'x'},
90 {"dumpc", no_argument, NULL, 'C'},
91 {"dumps", no_argument, NULL, 'S'},
92 {"no-logging", no_argument, NULL, 'N'},
93 {"server", no_argument, NULL, 's'},
94 {"udp", no_argument, NULL, 'u'},
95 {"ipv4", no_argument, NULL, '4'},
96 {"ipv6", no_argument, NULL, '6'},
97 {"nofork", no_argument, NULL, 'D'},
98 {"version", no_argument, NULL, 'v'},
99 {"help", no_argument, NULL, 'h'},
100 {NULL, 0, NULL, 0}
103 static void signal_handler(int number)
105 switch (number) {
106 case SIGINT:
107 sigint = 1;
108 break;
109 default:
110 break;
114 static void header(void)
116 printf("%s%s%s\n", colorize_start(bold), "curvetun "
117 VERSION_STRING, colorize_end());
120 static void help(void)
122 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n",
123 VERSION_STRING);
124 puts("http://www.netsniff-ng.org\n\n"
125 "Usage: curvetun [options]\n"
126 "Options, general:\n"
127 " -k|--keygen Generate public/private keypair\n"
128 " -x|--export Export your public data for remote servers\n"
129 " -C|--dumpc Dump parsed clients\n"
130 " -S|--dumps Dump parsed servers\n"
131 " -D|--nofork Do not daemonize\n"
132 " -d|--dev <tun> Networking tunnel device, e.g. tun0\n"
133 " -v|--version Print version\n"
134 " -h|--help Print this help\n"
135 " -c|--client[=alias] Client mode, server alias optional\n"
136 " -s|--server Server mode, options follow below\n"
137 " -N|--no-logging Disable server logging (for better anonymity)\n"
138 " -p|--port <num> Server port number (mandatory)\n"
139 " -t|--stun <server> Show public IP/Port mapping via STUN\n"
140 " -u|--udp Use UDP as carrier instead of TCP\n"
141 " -4|--ipv4 Tunnel devices are IPv4\n"
142 " -6|--ipv6 Tunnel devices are IPv6\n"
143 " (default: same as carrier protocol)\n\n"
144 "Example:\n"
145 " See Documentation/Curvetun for a configuration example.\n"
146 " curvetun --keygen\n"
147 " curvetun --export\n"
148 " curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n"
149 " curvetun --client=ethz\n\n"
150 "Note:\n"
151 " There is no default port specified, so that you are forced\n"
152 " to select your own! For client/server status messages see syslog!\n"
153 " This software is an experimental prototype intended for researchers.\n\n"
154 "Secret ingredient: 7647-14-5\n\n"
155 "Please report bugs to <bugs@netsniff-ng.org>\n"
156 "Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
157 "License: GNU GPL version 2.0\n"
158 "This is free software: you are free to change and redistribute it.\n"
159 "There is NO WARRANTY, to the extent permitted by law.\n");
160 die();
163 static void version(void)
165 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n",
166 VERSION_STRING);
167 puts("http://www.netsniff-ng.org\n\n"
168 "Please report bugs to <bugs@netsniff-ng.org>\n"
169 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
170 "License: GNU GPL version 2.0\n"
171 "This is free software: you are free to change and redistribute it.\n"
172 "There is NO WARRANTY, to the extent permitted by law.\n");
173 die();
176 static void check_file_or_die(char *home, char *file, int maybeempty)
178 char path[PATH_MAX];
179 struct stat st;
181 memset(path, 0, sizeof(path));
182 slprintf(path, sizeof(path), "%s/%s", home, file);
184 if (stat(path, &st))
185 panic("No such file %s! Type --help for further information\n",
186 path);
188 if (!S_ISREG(st.st_mode))
189 panic("%s is not a regular file!\n", path);
191 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
192 panic("You have set too many permissions on %s (%o)!\n",
193 path, st.st_mode);
195 if (maybeempty == 0 && st.st_size == 0)
196 panic("%s is empty!\n", path);
199 static void check_config_exists_or_die(char *home)
201 if (!home)
202 panic("No home dir specified!\n");
204 check_file_or_die(home, FILE_CLIENTS, 1);
205 check_file_or_die(home, FILE_SERVERS, 1);
206 check_file_or_die(home, FILE_PRIVKEY, 0);
207 check_file_or_die(home, FILE_PUBKEY, 0);
208 check_file_or_die(home, FILE_USERNAM, 0);
211 static char *fetch_home_dir(void)
213 char *home = getenv("HOME");
214 if (!home)
215 panic("No HOME defined!\n");
216 return home;
219 static void write_username(char *home)
221 int fd, ret;
222 char path[PATH_MAX];
223 char user[512];
225 memset(path, 0, sizeof(path));
226 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
228 printf("Username: [%s] ", getenv("USER"));
229 fflush(stdout);
231 memset(user, 0, sizeof(user));
232 if (fgets(user, sizeof(user), stdin) == NULL)
233 panic("Could not read from stdin!\n");
234 user[sizeof(user) - 1] = 0;
235 user[strlen(user) - 1] = 0; /* omit last \n */
236 if (strlen(user) == 0)
237 strlcpy(user, getenv("USER"), sizeof(user));
239 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
241 ret = write(fd, user, strlen(user));
242 if (ret != strlen(user))
243 panic("Could not write username!\n");
245 close(fd);
247 printf("Username written to %s!\n", path);
250 static void create_curvedir(char *home)
252 int ret;
253 char path[PATH_MAX];
255 memset(path, 0, sizeof(path));
256 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
258 errno = 0;
260 ret = mkdir(path, S_IRWXU);
261 if (ret < 0 && errno != EEXIST)
262 panic("Cannot create curvetun dir!\n");
264 printf("curvetun directory %s created!\n", path);
265 /* We also create empty files for clients and servers! */
267 memset(path, 0, sizeof(path));
268 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
270 create_or_die(path, S_IRUSR | S_IWUSR);
272 printf("Empty client file written to %s!\n", path);
274 memset(path, 0, sizeof(path));
275 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
277 create_or_die(path, S_IRUSR | S_IWUSR);
279 printf("Empty server file written to %s!\n", path);
282 static void create_keypair(char *home)
284 int fd, err = 0;
285 ssize_t ret;
286 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
287 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
288 char path[PATH_MAX];
289 const char * errstr = NULL;
291 printf("Reading from %s (this may take a while) ...\n", CURVETUN_ENTROPY_SOURCE);
293 fd = open_or_die(CURVETUN_ENTROPY_SOURCE, O_RDONLY);
295 ret = read_exact(fd, secretkey, sizeof(secretkey), 0);
296 if (ret != sizeof(secretkey)) {
297 err = EIO;
298 errstr = "Cannot read from "CURVETUN_ENTROPY_SOURCE"!\n";
299 goto out;
302 close(fd);
304 crypto_scalarmult_curve25519_base(publickey, secretkey);
306 memset(path, 0, sizeof(path));
307 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
309 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
310 if (fd < 0) {
311 err = EIO;
312 errstr = "Cannot open pubkey file!\n";
313 goto out;
316 ret = write(fd, publickey, sizeof(publickey));
317 if (ret != sizeof(publickey)) {
318 err = EIO;
319 errstr = "Cannot write public key!\n";
320 goto out;
323 close(fd);
325 printf("Public key written to %s!\n", path);
327 memset(path, 0, sizeof(path));
328 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
330 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
331 if (fd < 0) {
332 err = EIO;
333 errstr = "Cannot open privkey file!\n";
334 goto out;
337 ret = write(fd, secretkey, sizeof(secretkey));
338 if (ret != sizeof(secretkey)) {
339 err = EIO;
340 errstr = "Cannot write private key!\n";
341 goto out;
343 out:
344 close(fd);
346 xmemset(publickey, 0, sizeof(publickey));
347 xmemset(secretkey, 0, sizeof(secretkey));
349 if (err)
350 panic("%s: %s", errstr, strerror(errno));
351 else
352 printf("Private key written to %s!\n", path);
355 static void check_config_keypair_or_die(char *home)
357 int fd, err;
358 ssize_t ret;
359 const char * errstr = NULL;
360 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
361 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
362 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
363 char path[PATH_MAX];
365 memset(path, 0, sizeof(path));
366 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
368 fd = open(path, O_RDONLY);
369 if (fd < 0) {
370 err = EIO;
371 errstr = "Cannot open privkey file!\n";
372 goto out;
375 ret = read(fd, secretkey, sizeof(secretkey));
376 if (ret != sizeof(secretkey)) {
377 err = EIO;
378 errstr = "Cannot read private key!\n";
379 goto out;
382 close(fd);
384 memset(path, 0, sizeof(path));
385 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
387 fd = open(path, O_RDONLY);
388 if (fd < 0) {
389 err = EIO;
390 errstr = "Cannot open pubkey file!\n";
391 goto out;
394 ret = read(fd, publickey, sizeof(publickey));
395 if (ret != sizeof(publickey)) {
396 err = EIO;
397 errstr = "Cannot read public key!\n";
398 goto out;
401 crypto_scalarmult_curve25519_base(publicres, secretkey);
403 err = crypto_verify_32(publicres, publickey);
404 if (err) {
405 err = EINVAL;
406 errstr = "WARNING: your keypair is corrupted!!! You need to "
407 "generate new keys!!!\n";
408 goto out;
410 out:
411 close(fd);
413 xmemset(publickey, 0, sizeof(publickey));
414 xmemset(publicres, 0, sizeof(publicres));
415 xmemset(secretkey, 0, sizeof(secretkey));
417 if (err)
418 panic("%s: %s\n", errstr, strerror(errno));
421 static int main_keygen(char *home)
423 create_curvedir(home);
424 write_username(home);
425 create_keypair(home);
426 check_config_keypair_or_die(home);
428 return 0;
431 static int main_export(char *home)
433 int fd, i;
434 ssize_t ret;
435 char path[PATH_MAX], tmp[64];
437 check_config_exists_or_die(home);
438 check_config_keypair_or_die(home);
440 printf("Your exported public information:\n\n");
442 memset(path, 0, sizeof(path));
443 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
445 fd = open_or_die(path, O_RDONLY);
447 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
448 ret = write(STDOUT_FILENO, tmp, ret);
451 close(fd);
453 printf(";");
455 memset(path, 0, sizeof(path));
456 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
458 fd = open_or_die(path, O_RDONLY);
460 ret = read(fd, tmp, sizeof(tmp));
461 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
462 panic("Cannot read public key!\n");
464 for (i = 0; i < ret; ++i)
465 if (i == ret - 1)
466 printf("%02x\n\n", (unsigned char) tmp[i]);
467 else
468 printf("%02x:", (unsigned char) tmp[i]);
470 close(fd);
471 fflush(stdout);
473 return 0;
476 static int main_dumpc(char *home)
478 check_config_exists_or_die(home);
479 check_config_keypair_or_die(home);
481 printf("Your clients:\n\n");
483 parse_userfile_and_generate_user_store_or_die(home);
485 dump_user_store();
487 destroy_user_store();
489 printf("\n");
490 die();
491 return 0;
494 static int main_dumps(char *home)
496 check_config_exists_or_die(home);
497 check_config_keypair_or_die(home);
499 printf("Your servers:\n\n");
501 parse_userfile_and_generate_serv_store_or_die(home);
503 dump_serv_store();
505 destroy_serv_store();
507 printf("\n");
508 die();
509 return 0;
512 static void daemonize(const char *lockfile)
514 char pidstr[8];
515 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
516 int lfp;
518 if (getppid() == 1)
519 return;
521 if (daemon(0, 0))
522 panic("Cannot daemonize: %s", strerror(errno));
524 umask(lperm);
525 if (lockfile) {
526 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
527 S_IRUSR | S_IWUSR | S_IRGRP);
528 if (lfp < 0)
529 syslog_panic("Cannot create lockfile at %s! "
530 "curvetun server already running?\n",
531 lockfile);
533 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
534 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
535 syslog_panic("Could not write pid to pidfile %s",
536 lockfile);
538 close(lfp);
542 static int main_client(char *home, char *dev, char *alias, int daemon)
544 int ret, udp;
545 char *host, *port;
547 check_config_exists_or_die(home);
548 check_config_keypair_or_die(home);
550 parse_userfile_and_generate_serv_store_or_die(home);
552 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
553 &host, &port, &udp);
554 if (!host || !port || udp < 0)
555 panic("Did not find alias/entry in configuration!\n");
557 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
558 alias ? : "default", host, port, udp ? "udp" : "tcp");
559 if (daemon)
560 daemonize(NULL);
562 ret = client_main(home, dev, host, port, udp);
564 destroy_serv_store();
566 return ret;
569 static int main_server(char *home, char *dev, char *port, int udp,
570 int ipv4, int daemon, int log)
572 int ret;
574 check_config_exists_or_die(home);
575 check_config_keypair_or_die(home);
577 if (daemon)
578 daemonize(LOCKFILE);
580 ret = server_main(home, dev, port, udp, ipv4, log);
582 unlink(LOCKFILE);
584 return ret;
587 int main(int argc, char **argv)
589 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
590 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
591 enum working_mode wmode = MODE_UNKNOW;
593 setfsuid(getuid());
594 setfsgid(getgid());
596 home = fetch_home_dir();
598 while ((c = getopt_long(argc, argv, short_options, long_options,
599 &opt_index)) != EOF) {
600 switch (c) {
601 case 'h':
602 help();
603 break;
604 case 'v':
605 version();
606 break;
607 case 'D':
608 daemon = 0;
609 break;
610 case 'N':
611 log = 0;
612 break;
613 case 'C':
614 wmode = MODE_DUMPC;
615 break;
616 case 'S':
617 wmode = MODE_DUMPS;
618 break;
619 case 'c':
620 wmode = MODE_CLIENT;
621 if (optarg) {
622 if (*optarg == '=')
623 optarg++;
624 alias = xstrdup(optarg);
626 break;
627 case 'd':
628 dev = xstrdup(optarg);
629 break;
630 case 'k':
631 wmode = MODE_KEYGEN;
632 break;
633 case '4':
634 ipv4 = 1;
635 break;
636 case '6':
637 ipv4 = 0;
638 break;
639 case 'x':
640 wmode = MODE_EXPORT;
641 break;
642 case 's':
643 wmode = MODE_SERVER;
644 break;
645 case 'u':
646 udp = 1;
647 break;
648 case 't':
649 stun = xstrdup(optarg);
650 break;
651 case 'p':
652 port = xstrdup(optarg);
653 break;
654 case '?':
655 switch (optopt) {
656 case 't':
657 case 'd':
658 case 'u':
659 case 'p':
660 panic("Option -%c requires an argument!\n",
661 optopt);
662 default:
663 if (isprint(optopt))
664 whine("Unknown option character "
665 "`0x%X\'!\n", optopt);
666 die();
668 default:
669 break;
673 if (argc < 2)
674 help();
676 register_signal(SIGINT, signal_handler);
677 register_signal(SIGHUP, signal_handler);
678 register_signal(SIGTERM, signal_handler);
679 register_signal(SIGPIPE, signal_handler);
681 header();
683 curve25519_selftest();
685 switch (wmode) {
686 case MODE_KEYGEN:
687 ret = main_keygen(home);
688 break;
689 case MODE_EXPORT:
690 ret = main_export(home);
691 break;
692 case MODE_DUMPC:
693 ret = main_dumpc(home);
694 break;
695 case MODE_DUMPS:
696 ret = main_dumps(home);
697 break;
698 case MODE_CLIENT:
699 ret = main_client(home, dev, alias, daemon);
700 break;
701 case MODE_SERVER:
702 if (!port)
703 panic("No port specified!\n");
704 if (stun)
705 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
706 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
707 break;
708 default:
709 die();
712 if (dev)
713 xfree(dev);
714 if (stun)
715 xfree(stun);
716 if (port)
717 xfree(port);
718 if (alias)
719 xfree(alias);
721 return ret;