Corrected spinning loop potential in getrandombytes
[netsniff-ng.git] / curvetun.c
blobe81debec52218b8e52bcb2dd90904a27018a7850
1 /*
2 * curvetun - the cipherspace wormhole creator
3 * Part of the netsniff-ng project
4 * Copyright 2011 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
5 * Copyright 2011 Emmanuel Roullit.
6 * Subject to the GPL, version 2.
8 * He used often to say there was only one Road; that it was like a great
9 * river: it's springs were at every doorstep and every path was it's
10 * tributary. "It's a dangerous business, Frodo, going out of your door,"
11 * he used to say. "You step into the Road, and if you don't keep your
12 * feet, there is no telling where you might be swept off to."
14 * -- The Lord of the Rings, Frodo about his uncle Bilbo Baggins,
15 * Chapter 'Three is Company'.
18 #define _GNU_SOURCE
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <fcntl.h>
22 #include <string.h>
23 #include <ctype.h>
24 #include <getopt.h>
25 #include <errno.h>
26 #include <stdbool.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/socket.h>
31 #include <sys/ptrace.h>
32 #include <sys/fsuid.h>
33 #include <netinet/in.h>
34 #include <unistd.h>
35 #include <signal.h>
37 #include "xutils.h"
38 #include "die.h"
39 #include "xmalloc.h"
40 #include "curvetun.h"
41 #include "curve.h"
42 #include "ct_usermgmt.h"
43 #include "ct_servmgmt.h"
44 #include "xio.h"
45 #include "tprintf.h"
46 #include "crypto_verify_32.h"
47 #include "crypto_box_curve25519xsalsa20poly1305.h"
48 #include "crypto_scalarmult_curve25519.h"
49 #include "crypto_auth_hmacsha512256.h"
51 #define CURVETUN_ENTROPY_SOURCE "/dev/random"
53 extern void print_stun_probe(char *server, uint16_t sport, uint16_t tunport);
55 enum working_mode {
56 MODE_UNKNOW,
57 MODE_KEYGEN,
58 MODE_EXPORT,
59 MODE_DUMPC,
60 MODE_DUMPS,
61 MODE_CLIENT,
62 MODE_SERVER,
65 volatile sig_atomic_t sigint = 0;
67 static const char *short_options = "kxc::svhp:t:d:uCS46DN";
68 static const struct option long_options[] = {
69 {"client", optional_argument, NULL, 'c'},
70 {"dev", required_argument, NULL, 'd'},
71 {"port", required_argument, NULL, 'p'},
72 {"stun", required_argument, NULL, 't'},
73 {"keygen", no_argument, NULL, 'k'},
74 {"export", no_argument, NULL, 'x'},
75 {"dumpc", no_argument, NULL, 'C'},
76 {"dumps", no_argument, NULL, 'S'},
77 {"no-logging", no_argument, NULL, 'N'},
78 {"server", no_argument, NULL, 's'},
79 {"udp", no_argument, NULL, 'u'},
80 {"ipv4", no_argument, NULL, '4'},
81 {"ipv6", no_argument, NULL, '6'},
82 {"nofork", no_argument, NULL, 'D'},
83 {"version", no_argument, NULL, 'v'},
84 {"help", no_argument, NULL, 'h'},
85 {NULL, 0, NULL, 0}
88 static void signal_handler(int number)
90 switch (number) {
91 case SIGINT:
92 sigint = 1;
93 break;
94 default:
95 break;
99 static void help(void)
101 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n", VERSION_STRING);
102 puts("http://www.netsniff-ng.org\n\n"
103 "Usage: curvetun [options]\n"
104 "Options, general:\n"
105 " -d|--dev <tun> Networking tunnel device, e.g. tun0\n"
106 " -p|--port <num> Server port number (mandatory)\n"
107 " -t|--stun <server> Show public IP/Port mapping via STUN\n"
108 " -c|--client[=alias] Client mode, server alias optional\n"
109 " -k|--keygen Generate public/private keypair\n"
110 " -x|--export Export your public data for remote servers\n"
111 " -C|--dumpc Dump parsed clients\n"
112 " -S|--dumps Dump parsed servers\n"
113 " -D|--nofork Do not daemonize\n"
114 " -s|--server Server mode, options follow below\n"
115 " -N|--no-logging Disable server logging (for better anonymity)\n"
116 " -u|--udp Use UDP as carrier instead of TCP\n"
117 " -4|--ipv4 Tunnel devices are IPv4\n"
118 " -6|--ipv6 Tunnel devices are IPv6\n"
119 " -v|--version Print version\n"
120 " -h|--help Print this help\n\n"
121 "Example:\n"
122 " See Documentation/Curvetun for a configuration example.\n"
123 " curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n"
124 " curvetun --client=ethz\n\n"
125 " curvetun --keygen\n"
126 " curvetun --export\n"
127 "Note:\n"
128 " There is no default port specified, so that you are forced\n"
129 " to select your own! For client/server status messages see syslog!\n"
130 " This software is an experimental prototype intended for researchers.\n\n"
131 "Secret ingredient: 7647-14-5\n\n"
132 "Please report bugs to <bugs@netsniff-ng.org>\n"
133 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
134 "Swiss federal institute of technology (ETH Zurich)\n"
135 "License: GNU GPL version 2.0\n"
136 "This is free software: you are free to change and redistribute it.\n"
137 "There is NO WARRANTY, to the extent permitted by law.\n");
138 die();
141 static void version(void)
143 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n", VERSION_STRING);
144 puts("http://www.netsniff-ng.org\n\n"
145 "Please report bugs to <bugs@netsniff-ng.org>\n"
146 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
147 "Swiss federal institute of technology (ETH Zurich)\n"
148 "License: GNU GPL version 2.0\n"
149 "This is free software: you are free to change and redistribute it.\n"
150 "There is NO WARRANTY, to the extent permitted by law.\n");
151 die();
154 static void check_file_or_die(char *home, char *file, int maybeempty)
156 char path[PATH_MAX];
157 struct stat st;
159 memset(path, 0, sizeof(path));
160 slprintf(path, sizeof(path), "%s/%s", home, file);
162 if (stat(path, &st))
163 panic("No such file %s! Type --help for further information\n",
164 path);
166 if (!S_ISREG(st.st_mode))
167 panic("%s is not a regular file!\n", path);
169 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
170 panic("You have set too many permissions on %s (%o)!\n",
171 path, st.st_mode);
173 if (maybeempty == 0 && st.st_size == 0)
174 panic("%s is empty!\n", path);
177 static void check_config_exists_or_die(char *home)
179 if (!home)
180 panic("No home dir specified!\n");
182 check_file_or_die(home, FILE_CLIENTS, 1);
183 check_file_or_die(home, FILE_SERVERS, 1);
184 check_file_or_die(home, FILE_PRIVKEY, 0);
185 check_file_or_die(home, FILE_PUBKEY, 0);
186 check_file_or_die(home, FILE_USERNAM, 0);
189 static char *fetch_home_dir(void)
191 char *home = getenv("HOME");
192 if (!home)
193 panic("No HOME defined!\n");
194 return home;
197 static void write_username(char *home)
199 int fd, ret;
200 char path[PATH_MAX];
201 char user[512];
203 memset(path, 0, sizeof(path));
204 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
206 printf("Username: [%s] ", getenv("USER"));
207 fflush(stdout);
209 memset(user, 0, sizeof(user));
210 if (fgets(user, sizeof(user), stdin) == NULL)
211 panic("Could not read from stdin!\n");
212 user[sizeof(user) - 1] = 0;
213 user[strlen(user) - 1] = 0; /* omit last \n */
214 if (strlen(user) == 0)
215 strlcpy(user, getenv("USER"), sizeof(user));
217 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
219 ret = write(fd, user, strlen(user));
220 if (ret != strlen(user))
221 panic("Could not write username!\n");
223 close(fd);
225 printf("Username written to %s!\n", path);
228 static void create_curvedir(char *home)
230 int ret;
231 char path[PATH_MAX];
233 memset(path, 0, sizeof(path));
234 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
236 errno = 0;
238 ret = mkdir(path, S_IRWXU);
239 if (ret < 0 && errno != EEXIST)
240 panic("Cannot create curvetun dir!\n");
242 printf("curvetun directory %s created!\n", path);
243 /* We also create empty files for clients and servers! */
245 memset(path, 0, sizeof(path));
246 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
248 create_or_die(path, S_IRUSR | S_IWUSR);
250 printf("Empty client file written to %s!\n", path);
252 memset(path, 0, sizeof(path));
253 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
255 create_or_die(path, S_IRUSR | S_IWUSR);
257 printf("Empty server file written to %s!\n", path);
260 static void create_keypair(char *home)
262 int fd, err = 0;
263 ssize_t ret;
264 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
265 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
266 char path[PATH_MAX];
267 const char * errstr = NULL;
269 printf("Reading from %s (this may take a while) ...\n", CURVETUN_ENTROPY_SOURCE);
271 fd = open_or_die(CURVETUN_ENTROPY_SOURCE, O_RDONLY);
273 ret = read_exact(fd, secretkey, sizeof(secretkey), 0);
274 if (ret != sizeof(secretkey)) {
275 err = EIO;
276 errstr = "Cannot read from "CURVETUN_ENTROPY_SOURCE"!\n";
277 goto out;
280 close(fd);
282 crypto_scalarmult_curve25519_base(publickey, secretkey);
284 memset(path, 0, sizeof(path));
285 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
287 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
288 if (fd < 0) {
289 err = EIO;
290 errstr = "Cannot open pubkey file!\n";
291 goto out;
294 ret = write(fd, publickey, sizeof(publickey));
295 if (ret != sizeof(publickey)) {
296 err = EIO;
297 errstr = "Cannot write public key!\n";
298 goto out;
301 close(fd);
303 printf("Public key written to %s!\n", path);
305 memset(path, 0, sizeof(path));
306 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
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 privkey file!\n";
312 goto out;
315 ret = write(fd, secretkey, sizeof(secretkey));
316 if (ret != sizeof(secretkey)) {
317 err = EIO;
318 errstr = "Cannot write private key!\n";
319 goto out;
321 out:
322 close(fd);
324 xmemset(publickey, 0, sizeof(publickey));
325 xmemset(secretkey, 0, sizeof(secretkey));
327 if (err)
328 panic("%s: %s", errstr, strerror(errno));
329 else
330 printf("Private key written to %s!\n", path);
333 static void check_config_keypair_or_die(char *home)
335 int fd, err;
336 ssize_t ret;
337 const char * errstr = NULL;
338 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
339 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
340 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
341 char path[PATH_MAX];
343 memset(path, 0, sizeof(path));
344 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
346 fd = open(path, O_RDONLY);
347 if (fd < 0) {
348 err = EIO;
349 errstr = "Cannot open privkey file!\n";
350 goto out;
353 ret = read(fd, secretkey, sizeof(secretkey));
354 if (ret != sizeof(secretkey)) {
355 err = EIO;
356 errstr = "Cannot read private key!\n";
357 goto out;
360 close(fd);
362 memset(path, 0, sizeof(path));
363 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
365 fd = open(path, O_RDONLY);
366 if (fd < 0) {
367 err = EIO;
368 errstr = "Cannot open pubkey file!\n";
369 goto out;
372 ret = read(fd, publickey, sizeof(publickey));
373 if (ret != sizeof(publickey)) {
374 err = EIO;
375 errstr = "Cannot read public key!\n";
376 goto out;
379 crypto_scalarmult_curve25519_base(publicres, secretkey);
381 err = crypto_verify_32(publicres, publickey);
382 if (err) {
383 err = EINVAL;
384 errstr = "WARNING: your keypair is corrupted!!! You need to "
385 "generate new keys!!!\n";
386 goto out;
388 out:
389 close(fd);
391 xmemset(publickey, 0, sizeof(publickey));
392 xmemset(publicres, 0, sizeof(publicres));
393 xmemset(secretkey, 0, sizeof(secretkey));
395 if (err)
396 panic("%s: %s\n", errstr, strerror(errno));
399 static int main_keygen(char *home)
401 create_curvedir(home);
402 write_username(home);
403 create_keypair(home);
404 check_config_keypair_or_die(home);
406 return 0;
409 static int main_export(char *home)
411 int fd, i;
412 ssize_t ret;
413 char path[PATH_MAX], tmp[64];
415 check_config_exists_or_die(home);
416 check_config_keypair_or_die(home);
418 printf("Your exported public information:\n\n");
420 memset(path, 0, sizeof(path));
421 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
423 fd = open_or_die(path, O_RDONLY);
425 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
426 ret = write(STDOUT_FILENO, tmp, ret);
429 close(fd);
431 printf(";");
433 memset(path, 0, sizeof(path));
434 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
436 fd = open_or_die(path, O_RDONLY);
438 ret = read(fd, tmp, sizeof(tmp));
439 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
440 panic("Cannot read public key!\n");
442 for (i = 0; i < ret; ++i)
443 if (i == ret - 1)
444 printf("%02x\n\n", (unsigned char) tmp[i]);
445 else
446 printf("%02x:", (unsigned char) tmp[i]);
448 close(fd);
449 fflush(stdout);
451 return 0;
454 static int main_dumpc(char *home)
456 check_config_exists_or_die(home);
457 check_config_keypair_or_die(home);
459 printf("Your clients:\n\n");
461 parse_userfile_and_generate_user_store_or_die(home);
463 dump_user_store();
465 destroy_user_store();
467 printf("\n");
468 die();
469 return 0;
472 static int main_dumps(char *home)
474 check_config_exists_or_die(home);
475 check_config_keypair_or_die(home);
477 printf("Your servers:\n\n");
479 parse_userfile_and_generate_serv_store_or_die(home);
481 dump_serv_store();
483 destroy_serv_store();
485 printf("\n");
486 die();
487 return 0;
490 static void daemonize(const char *lockfile)
492 char pidstr[8];
493 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
494 int lfp;
496 if (getppid() == 1)
497 return;
499 if (daemon(0, 1))
500 panic("Cannot daemonize: %s", strerror(errno));
502 to_std_log(&stdout);
503 to_std_log(&stderr);
505 umask(lperm);
506 if (lockfile) {
507 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
508 S_IRUSR | S_IWUSR | S_IRGRP);
509 if (lfp < 0)
510 syslog_panic("Cannot create lockfile at %s! "
511 "curvetun server already running?\n",
512 lockfile);
514 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
515 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
516 syslog_panic("Could not write pid to pidfile %s",
517 lockfile);
519 close(lfp);
523 static int main_client(char *home, char *dev, char *alias, int daemon)
525 int ret, udp;
526 char *host, *port;
528 check_config_exists_or_die(home);
529 check_config_keypair_or_die(home);
531 parse_userfile_and_generate_serv_store_or_die(home);
533 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
534 &host, &port, &udp);
535 if (!host || !port || udp < 0)
536 panic("Did not find alias/entry in configuration!\n");
538 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
539 alias ? : "default", host, port, udp ? "udp" : "tcp");
540 if (daemon)
541 daemonize(NULL);
543 ret = client_main(home, dev, host, port, udp);
545 destroy_serv_store();
547 return ret;
550 static int main_server(char *home, char *dev, char *port, int udp,
551 int ipv4, int daemon, int log)
553 int ret;
555 check_config_exists_or_die(home);
556 check_config_keypair_or_die(home);
558 if (daemon)
559 daemonize(LOCKFILE);
561 ret = server_main(home, dev, port, udp, ipv4, log);
563 unlink(LOCKFILE);
565 return ret;
568 int main(int argc, char **argv)
570 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
571 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
572 enum working_mode wmode = MODE_UNKNOW;
574 setfsuid(getuid());
575 setfsgid(getgid());
577 home = fetch_home_dir();
579 while ((c = getopt_long(argc, argv, short_options, long_options,
580 &opt_index)) != EOF) {
581 switch (c) {
582 case 'h':
583 help();
584 break;
585 case 'v':
586 version();
587 break;
588 case 'D':
589 daemon = 0;
590 break;
591 case 'N':
592 log = 0;
593 break;
594 case 'C':
595 wmode = MODE_DUMPC;
596 break;
597 case 'S':
598 wmode = MODE_DUMPS;
599 break;
600 case 'c':
601 wmode = MODE_CLIENT;
602 if (optarg) {
603 if (*optarg == '=')
604 optarg++;
605 alias = xstrdup(optarg);
607 break;
608 case 'd':
609 dev = xstrdup(optarg);
610 break;
611 case 'k':
612 wmode = MODE_KEYGEN;
613 break;
614 case '4':
615 ipv4 = 1;
616 break;
617 case '6':
618 ipv4 = 0;
619 break;
620 case 'x':
621 wmode = MODE_EXPORT;
622 break;
623 case 's':
624 wmode = MODE_SERVER;
625 break;
626 case 'u':
627 udp = 1;
628 break;
629 case 't':
630 stun = xstrdup(optarg);
631 break;
632 case 'p':
633 port = xstrdup(optarg);
634 break;
635 case '?':
636 switch (optopt) {
637 case 't':
638 case 'd':
639 case 'u':
640 case 'p':
641 panic("Option -%c requires an argument!\n",
642 optopt);
643 default:
644 if (isprint(optopt))
645 printf("Unknown option character `0x%X\'!\n", optopt);
646 die();
648 default:
649 break;
653 if (argc < 2)
654 help();
656 register_signal(SIGINT, signal_handler);
657 register_signal(SIGHUP, signal_handler);
658 register_signal(SIGTERM, signal_handler);
659 register_signal(SIGPIPE, signal_handler);
661 curve25519_selftest();
663 switch (wmode) {
664 case MODE_KEYGEN:
665 ret = main_keygen(home);
666 break;
667 case MODE_EXPORT:
668 ret = main_export(home);
669 break;
670 case MODE_DUMPC:
671 ret = main_dumpc(home);
672 break;
673 case MODE_DUMPS:
674 ret = main_dumps(home);
675 break;
676 case MODE_CLIENT:
677 ret = main_client(home, dev, alias, daemon);
678 break;
679 case MODE_SERVER:
680 if (!port)
681 panic("No port specified!\n");
682 if (stun)
683 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
684 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
685 break;
686 default:
687 die();
690 if (dev)
691 xfree(dev);
692 if (stun)
693 xfree(stun);
694 if (port)
695 xfree(port);
696 if (alias)
697 xfree(alias);
699 return ret;