docs: add tree for fedora/rhel maintenance
[netsniff-ng.git] / src / curvetun.c
blob2409ea7fa8103ee246b13bba0ff547c227606fd5
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";
83 static struct option long_options[] = {
84 {"client", optional_argument, 0, 'c'},
85 {"dev", required_argument, 0, 'd'},
86 {"port", required_argument, 0, 'p'},
87 {"stun", required_argument, 0, 't'},
88 {"keygen", no_argument, 0, 'k'},
89 {"export", no_argument, 0, 'x'},
90 {"dumpc", no_argument, 0, 'C'},
91 {"dumps", no_argument, 0, 'S'},
92 {"no-logging", no_argument, 0, 'N'},
93 {"server", no_argument, 0, 's'},
94 {"udp", no_argument, 0, 'u'},
95 {"ipv4", no_argument, 0, '4'},
96 {"ipv6", no_argument, 0, '6'},
97 {"nofork", no_argument, 0, 'D'},
98 {"version", no_argument, 0, 'v'},
99 {"help", no_argument, 0, 'h'},
100 {0, 0, 0, 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 multiuser IP tunnel\n",
123 VERSION_STRING);
124 printf("http://www.netsniff-ng.org\n\n");
125 printf("Usage: curvetun [options]\n");
126 printf("Options, general:\n");
127 printf(" -k|--keygen Generate public/private keypair\n");
128 printf(" -x|--export Export your public data for remote servers\n");
129 printf(" -C|--dumpc Dump parsed clients\n");
130 printf(" -S|--dumps Dump parsed servers\n");
131 printf(" -D|--nofork Do not daemonize\n");
132 printf(" -d|--dev <tun> Networking tunnel device, e.g. tun0\n");
133 printf(" -v|--version Print version\n");
134 printf(" -h|--help Print this help\n");
135 printf("Options for client:\n");
136 printf(" -c|--client[=alias] Client mode, server alias optional\n");
137 printf("Options for servers:\n");
138 printf(" -s|--server Server mode\n");
139 printf(" -N|--no-logging Disable server logging (for better anonymity)\n");
140 printf(" -p|--port <num> Port number (mandatory)\n");
141 printf(" -t|--stun <server> Show public IP/Port mapping via STUN\n");
142 printf(" -u|--udp Use UDP as carrier instead of TCP\n");
143 printf(" -4|--ipv4 Tunnel devices are IPv4\n");
144 printf(" -6|--ipv6 Tunnel devices are IPv6\n");
145 printf(" (default: same as carrier protocol)\n");
146 printf("\n");
147 printf("Example:\n");
148 printf(" See Documentation/Curvetun for a configuration example.\n");
149 printf(" curvetun --keygen\n");
150 printf(" curvetun --export\n");
151 printf(" curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n");
152 printf(" curvetun --client=ethz\n");
153 printf("\n");
154 printf("Note:\n");
155 printf(" There is no default port specified, so that you are forced\n");
156 printf(" to select your own! For client/server status messages see syslog!\n");
157 printf(" This software is an experimental prototype intended for researchers.\n");
158 printf("\n");
159 printf("Secret ingredient: 7647-14-5\n");
160 printf("\n");
161 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
162 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
163 printf("License: GNU GPL version 2\n");
164 printf("This is free software: you are free to change and redistribute it.\n");
165 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
166 die();
169 static void version(void)
171 printf("\ncurvetun %s, lightweight curve25519-based multiuser IP tunnel\n",
172 VERSION_STRING);
173 printf("Build: %s\n", BUILD_STRING);
174 printf("http://www.netsniff-ng.org\n\n");
175 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
176 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
177 printf("License: GNU GPL version 2\n");
178 printf("This is free software: you are free to change and redistribute it.\n");
179 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
180 die();
183 static void check_file_or_die(char *home, char *file, int maybeempty)
185 char path[PATH_MAX];
186 struct stat st;
188 memset(path, 0, sizeof(path));
189 slprintf(path, sizeof(path), "%s/%s", home, file);
191 if (stat(path, &st))
192 panic("No such file %s! Type --help for further information\n",
193 path);
195 if (!S_ISREG(st.st_mode))
196 panic("%s is not a regular file!\n", path);
198 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
199 panic("You have set too many permissions on %s (%o)!\n",
200 path, st.st_mode);
202 if (maybeempty == 0 && st.st_size == 0)
203 panic("%s is empty!\n", path);
206 static void check_config_exists_or_die(char *home)
208 if (!home)
209 panic("No home dir specified!\n");
211 check_file_or_die(home, FILE_CLIENTS, 1);
212 check_file_or_die(home, FILE_SERVERS, 1);
213 check_file_or_die(home, FILE_PRIVKEY, 0);
214 check_file_or_die(home, FILE_PUBKEY, 0);
215 check_file_or_die(home, FILE_USERNAM, 0);
218 static char *fetch_home_dir(void)
220 char *home = getenv("HOME");
221 if (!home)
222 panic("No HOME defined!\n");
223 return home;
226 static void write_username(char *home)
228 int fd, ret;
229 char path[PATH_MAX], *eof;
230 char user[512];
232 memset(path, 0, sizeof(path));
233 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
235 printf("Username: [%s] ", getenv("USER"));
236 fflush(stdout);
238 memset(user, 0, sizeof(user));
239 eof = fgets(user, sizeof(user), stdin);
240 user[sizeof(user) - 1] = 0;
241 user[strlen(user) - 1] = 0; /* omit last \n */
242 if (strlen(user) == 0)
243 strlcpy(user, getenv("USER"), sizeof(user));
245 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
247 ret = write(fd, user, strlen(user));
248 if (ret != strlen(user))
249 panic("Could not write username!\n");
251 close(fd);
253 printf("Username written to %s!\n", path);
256 static void create_curvedir(char *home)
258 int ret;
259 char path[PATH_MAX];
261 memset(path, 0, sizeof(path));
262 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
264 errno = 0;
266 ret = mkdir(path, S_IRWXU);
267 if (ret < 0 && errno != EEXIST)
268 panic("Cannot create curvetun dir!\n");
270 printf("curvetun directory %s created!\n", path);
271 /* We also create empty files for clients and servers! */
273 memset(path, 0, sizeof(path));
274 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
276 create_or_die(path, S_IRUSR | S_IWUSR);
278 printf("Empty client file written to %s!\n", path);
280 memset(path, 0, sizeof(path));
281 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
283 create_or_die(path, S_IRUSR | S_IWUSR);
285 printf("Empty server file written to %s!\n", path);
288 static void create_keypair(char *home)
290 int fd, err = 0;
291 ssize_t ret;
292 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
293 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
294 char path[PATH_MAX];
295 const char * errstr = NULL;
297 printf("Reading from %s (this may take a while) ...\n", CURVETUN_ENTROPY_SOURCE);
299 fd = open_or_die(CURVETUN_ENTROPY_SOURCE, O_RDONLY);
301 ret = read_exact(fd, secretkey, sizeof(secretkey), 0);
302 if (ret != sizeof(secretkey)) {
303 err = EIO;
304 errstr = "Cannot read from "CURVETUN_ENTROPY_SOURCE"!\n";
305 goto out;
308 close(fd);
310 crypto_scalarmult_curve25519_base(publickey, secretkey);
312 memset(path, 0, sizeof(path));
313 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
315 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
316 if (fd < 0) {
317 err = EIO;
318 errstr = "Cannot open pubkey file!\n";
319 goto out;
322 ret = write(fd, publickey, sizeof(publickey));
323 if (ret != sizeof(publickey)) {
324 err = EIO;
325 errstr = "Cannot write public key!\n";
326 goto out;
329 close(fd);
331 printf("Public key written to %s!\n", path);
333 memset(path, 0, sizeof(path));
334 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
336 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
337 if (fd < 0) {
338 err = EIO;
339 errstr = "Cannot open privkey file!\n";
340 goto out;
343 ret = write(fd, secretkey, sizeof(secretkey));
344 if (ret != sizeof(secretkey)) {
345 err = EIO;
346 errstr = "Cannot write private key!\n";
347 goto out;
349 out:
350 close(fd);
352 xmemset(publickey, 0, sizeof(publickey));
353 xmemset(secretkey, 0, sizeof(secretkey));
355 if (err)
356 panic("%s: %s", errstr, strerror(errno));
357 else
358 printf("Private key written to %s!\n", path);
361 static void check_config_keypair_or_die(char *home)
363 int fd, err;
364 ssize_t ret;
365 const char * errstr = NULL;
366 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
367 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
368 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
369 char path[PATH_MAX];
371 memset(path, 0, sizeof(path));
372 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
374 fd = open(path, O_RDONLY);
375 if (fd < 0) {
376 err = EIO;
377 errstr = "Cannot open privkey file!\n";
378 goto out;
381 ret = read(fd, secretkey, sizeof(secretkey));
382 if (ret != sizeof(secretkey)) {
383 err = EIO;
384 errstr = "Cannot read private key!\n";
385 goto out;
388 close(fd);
390 memset(path, 0, sizeof(path));
391 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
393 fd = open(path, O_RDONLY);
394 if (fd < 0) {
395 err = EIO;
396 errstr = "Cannot open pubkey file!\n";
397 goto out;
400 ret = read(fd, publickey, sizeof(publickey));
401 if (ret != sizeof(publickey)) {
402 err = EIO;
403 errstr = "Cannot read public key!\n";
404 goto out;
407 crypto_scalarmult_curve25519_base(publicres, secretkey);
409 err = crypto_verify_32(publicres, publickey);
410 if (err) {
411 err = EINVAL;
412 errstr = "WARNING: your keypair is corrupted!!! You need to "
413 "generate new keys!!!\n";
414 goto out;
416 out:
417 close(fd);
419 xmemset(publickey, 0, sizeof(publickey));
420 xmemset(publicres, 0, sizeof(publicres));
421 xmemset(secretkey, 0, sizeof(secretkey));
423 if (err)
424 panic("%s: %s\n", errstr, strerror(errno));
427 static int main_keygen(char *home)
429 create_curvedir(home);
430 write_username(home);
431 create_keypair(home);
432 check_config_keypair_or_die(home);
434 return 0;
437 static int main_export(char *home)
439 int fd, i;
440 ssize_t ret;
441 char path[PATH_MAX], tmp[64];
443 check_config_exists_or_die(home);
444 check_config_keypair_or_die(home);
446 printf("Your exported public information:\n\n");
448 memset(path, 0, sizeof(path));
449 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
451 fd = open_or_die(path, O_RDONLY);
453 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
454 ret = write(STDOUT_FILENO, tmp, ret);
457 close(fd);
459 printf(";");
461 memset(path, 0, sizeof(path));
462 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
464 fd = open_or_die(path, O_RDONLY);
466 ret = read(fd, tmp, sizeof(tmp));
467 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
468 panic("Cannot read public key!\n");
470 for (i = 0; i < ret; ++i)
471 if (i == ret - 1)
472 printf("%02x\n\n", (unsigned char) tmp[i]);
473 else
474 printf("%02x:", (unsigned char) tmp[i]);
476 close(fd);
477 fflush(stdout);
479 return 0;
482 static int main_dumpc(char *home)
484 check_config_exists_or_die(home);
485 check_config_keypair_or_die(home);
487 printf("Your clients:\n\n");
489 parse_userfile_and_generate_user_store_or_die(home);
491 dump_user_store();
493 destroy_user_store();
495 printf("\n");
496 die();
497 return 0;
500 static int main_dumps(char *home)
502 check_config_exists_or_die(home);
503 check_config_keypair_or_die(home);
505 printf("Your servers:\n\n");
507 parse_userfile_and_generate_serv_store_or_die(home);
509 dump_serv_store();
511 destroy_serv_store();
513 printf("\n");
514 die();
515 return 0;
518 static void daemonize(const char *lockfile)
520 char pidstr[8];
521 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
522 int lfp;
524 if (getppid() == 1)
525 return;
527 if (daemon(0, 0))
528 panic("Cannot daemonize: %s", strerror(errno));
530 umask(lperm);
531 if (lockfile) {
532 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
533 S_IRUSR | S_IWUSR | S_IRGRP);
534 if (lfp < 0)
535 syslog_panic("Cannot create lockfile at %s! "
536 "curvetun server already running?\n",
537 lockfile);
539 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
540 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
541 syslog_panic("Could not write pid to pidfile %s",
542 lockfile);
544 close(lfp);
548 static int main_client(char *home, char *dev, char *alias, int daemon)
550 int ret, udp;
551 char *host, *port;
553 check_config_exists_or_die(home);
554 check_config_keypair_or_die(home);
556 parse_userfile_and_generate_serv_store_or_die(home);
558 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
559 &host, &port, &udp);
560 if (!host || !port || udp < 0)
561 panic("Did not find alias/entry in configuration!\n");
563 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
564 alias ? : "default", host, port, udp ? "udp" : "tcp");
565 if (daemon)
566 daemonize(NULL);
568 ret = client_main(home, dev, host, port, udp);
570 destroy_serv_store();
572 return ret;
575 static int main_server(char *home, char *dev, char *port, int udp,
576 int ipv4, int daemon, int log)
578 int ret;
580 check_config_exists_or_die(home);
581 check_config_keypair_or_die(home);
583 if (daemon)
584 daemonize(LOCKFILE);
586 ret = server_main(home, dev, port, udp, ipv4, log);
588 unlink(LOCKFILE);
590 return ret;
593 int main(int argc, char **argv)
595 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
596 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
597 enum working_mode wmode = MODE_UNKNOW;
599 if (getuid() != geteuid())
600 seteuid(getuid());
602 home = fetch_home_dir();
604 while ((c = getopt_long(argc, argv, short_options, long_options,
605 &opt_index)) != EOF) {
606 switch (c) {
607 case 'h':
608 help();
609 break;
610 case 'v':
611 version();
612 break;
613 case 'D':
614 daemon = 0;
615 break;
616 case 'N':
617 log = 0;
618 break;
619 case 'C':
620 wmode = MODE_DUMPC;
621 break;
622 case 'S':
623 wmode = MODE_DUMPS;
624 break;
625 case 'c':
626 wmode = MODE_CLIENT;
627 if (optarg) {
628 if (*optarg == '=')
629 optarg++;
630 alias = xstrdup(optarg);
632 break;
633 case 'd':
634 dev = xstrdup(optarg);
635 break;
636 case 'k':
637 wmode = MODE_KEYGEN;
638 break;
639 case '4':
640 ipv4 = 1;
641 break;
642 case '6':
643 ipv4 = 0;
644 break;
645 case 'x':
646 wmode = MODE_EXPORT;
647 break;
648 case 's':
649 wmode = MODE_SERVER;
650 break;
651 case 'u':
652 udp = 1;
653 break;
654 case 't':
655 stun = xstrdup(optarg);
656 break;
657 case 'p':
658 port = xstrdup(optarg);
659 break;
660 case '?':
661 switch (optopt) {
662 case 't':
663 case 'd':
664 case 'u':
665 case 'p':
666 panic("Option -%c requires an argument!\n",
667 optopt);
668 default:
669 if (isprint(optopt))
670 whine("Unknown option character "
671 "`0x%X\'!\n", optopt);
672 die();
674 default:
675 break;
679 if (argc < 2)
680 help();
682 register_signal(SIGINT, signal_handler);
683 register_signal(SIGHUP, signal_handler);
684 register_signal(SIGTERM, signal_handler);
685 register_signal(SIGPIPE, signal_handler);
687 header();
689 curve25519_selftest();
691 switch (wmode) {
692 case MODE_KEYGEN:
693 ret = main_keygen(home);
694 break;
695 case MODE_EXPORT:
696 ret = main_export(home);
697 break;
698 case MODE_DUMPC:
699 ret = main_dumpc(home);
700 break;
701 case MODE_DUMPS:
702 ret = main_dumps(home);
703 break;
704 case MODE_CLIENT:
705 ret = main_client(home, dev, alias, daemon);
706 break;
707 case MODE_SERVER:
708 if (!port)
709 panic("No port specified!\n");
710 if (stun)
711 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
712 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
713 break;
714 default:
715 die();
718 if (dev)
719 xfree(dev);
720 if (stun)
721 xfree(stun);
722 if (port)
723 xfree(port);
724 if (alias)
725 xfree(alias);
727 return ret;