configure, netsniff-ng: make netsniff-ng's geoip dependency optional
[netsniff-ng.git] / curvetun.c
blobfbc1ea3dc9528fe78063ece44c8ddf94945e1bec
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.
7 */
9 #define _GNU_SOURCE
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <fcntl.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <getopt.h>
16 #include <errno.h>
17 #include <stdbool.h>
18 #include <limits.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <sys/ptrace.h>
23 #include <sys/fsuid.h>
24 #include <netinet/in.h>
25 #include <unistd.h>
26 #include <signal.h>
28 #include "die.h"
29 #include "str.h"
30 #include "sig.h"
31 #include "stun.h"
32 #include "cookie.h"
33 #include "ioexact.h"
34 #include "xmalloc.h"
35 #include "curvetun.h"
36 #include "curve.h"
37 #include "config.h"
38 #include "curvetun_mgmt.h"
39 #include "ioops.h"
40 #include "tprintf.h"
41 #include "crypto.h"
43 enum working_mode {
44 MODE_UNKNOW,
45 MODE_KEYGEN,
46 MODE_EXPORT,
47 MODE_DUMPC,
48 MODE_DUMPS,
49 MODE_CLIENT,
50 MODE_SERVER,
53 volatile sig_atomic_t sigint = 0;
55 static const char *short_options = "kxc::svhp:t:d:uCS46DN";
56 static const struct option long_options[] = {
57 {"client", optional_argument, NULL, 'c'},
58 {"dev", required_argument, NULL, 'd'},
59 {"port", required_argument, NULL, 'p'},
60 {"stun", required_argument, NULL, 't'},
61 {"keygen", no_argument, NULL, 'k'},
62 {"export", no_argument, NULL, 'x'},
63 {"dumpc", no_argument, NULL, 'C'},
64 {"dumps", no_argument, NULL, 'S'},
65 {"no-logging", no_argument, NULL, 'N'},
66 {"server", no_argument, NULL, 's'},
67 {"udp", no_argument, NULL, 'u'},
68 {"ipv4", no_argument, NULL, '4'},
69 {"ipv6", no_argument, NULL, '6'},
70 {"nofork", no_argument, NULL, 'D'},
71 {"version", no_argument, NULL, 'v'},
72 {"help", no_argument, NULL, 'h'},
73 {NULL, 0, NULL, 0}
76 static void signal_handler(int number)
78 switch (number) {
79 case SIGINT:
80 case SIGTERM:
81 sigint = 1;
82 break;
83 default:
84 break;
88 static void __noreturn help(void)
90 printf("\ncurvetun %s, lightweight curve25519-based IP tunnel\n", VERSION_STRING);
91 puts("http://www.netsniff-ng.org\n\n"
92 "Usage: curvetun [options]\n"
93 "Options, general:\n"
94 " -d|--dev <tun> Networking tunnel device, e.g. tun0\n"
95 " -p|--port <num> Server port number (mandatory)\n"
96 " -t|--stun <server> Show public IP/Port mapping via STUN\n"
97 " -c|--client[=alias] Client mode, server alias optional\n"
98 " -k|--keygen Generate public/private keypair\n"
99 " -x|--export Export your public data for remote servers\n"
100 " -C|--dumpc Dump parsed clients\n"
101 " -S|--dumps Dump parsed servers\n"
102 " -D|--nofork Do not daemonize\n"
103 " -s|--server Server mode, options follow below\n"
104 " -N|--no-logging Disable server logging (for better anonymity)\n"
105 " -u|--udp Use UDP as carrier instead of TCP\n"
106 " -4|--ipv4 Tunnel devices are IPv4\n"
107 " -6|--ipv6 Tunnel devices are IPv6\n"
108 " -v|--version Print version and exit\n"
109 " -h|--help Print this help and exit\n\n"
110 "Example:\n"
111 " See curvetun's man page for a configuration example.\n"
112 " curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n"
113 " curvetun --client=ethz\n\n"
114 " curvetun --keygen\n"
115 " curvetun --export\n"
116 "Note:\n"
117 " There is no default port specified, so that you are forced\n"
118 " to select your own! For client/server status messages see syslog!\n"
119 " This software is an experimental prototype intended for researchers.\n\n"
120 "Secret ingredient: 7647-14-5\n\n"
121 "Please report bugs to <bugs@netsniff-ng.org>\n"
122 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
123 "Swiss federal institute of technology (ETH Zurich)\n"
124 "License: GNU GPL version 2.0\n"
125 "This is free software: you are free to change and redistribute it.\n"
126 "There is NO WARRANTY, to the extent permitted by law.\n");
127 die();
130 static void __noreturn version(void)
132 printf("\ncurvetun %s, Git id: %s\n", VERSION_LONG, GITVERSION);
133 puts("lightweight curve25519-based IP tunnel\n"
134 "http://www.netsniff-ng.org\n\n"
135 "Please report bugs to <bugs@netsniff-ng.org>\n"
136 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
137 "Swiss federal institute of technology (ETH Zurich)\n"
138 "License: GNU GPL version 2.0\n"
139 "This is free software: you are free to change and redistribute it.\n"
140 "There is NO WARRANTY, to the extent permitted by law.\n");
141 die();
144 static void check_file_or_die(char *home, char *file, int maybeempty)
146 char path[PATH_MAX];
147 struct stat st;
149 memset(path, 0, sizeof(path));
150 slprintf(path, sizeof(path), "%s/%s", home, file);
152 if (stat(path, &st))
153 panic("No such file %s! Type --help for further information\n",
154 path);
156 if (!S_ISREG(st.st_mode))
157 panic("%s is not a regular file!\n", path);
159 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
160 panic("You have set too many permissions on %s (%o)!\n",
161 path, st.st_mode);
163 if (maybeempty == 0 && st.st_size == 0)
164 panic("%s is empty!\n", path);
167 static void check_config_exists_or_die(char *home)
169 if (!home)
170 panic("No home dir specified!\n");
172 check_file_or_die(home, FILE_CLIENTS, 1);
173 check_file_or_die(home, FILE_SERVERS, 1);
174 check_file_or_die(home, FILE_PRIVKEY, 0);
175 check_file_or_die(home, FILE_PUBKEY, 0);
176 check_file_or_die(home, FILE_USERNAM, 0);
179 static char *fetch_home_dir(void)
181 char *home = getenv("HOME");
182 if (!home)
183 panic("No HOME defined!\n");
184 return home;
187 static void write_username(char *home)
189 int fd, ret;
190 char path[PATH_MAX];
191 char user[512];
193 memset(path, 0, sizeof(path));
194 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
196 printf("Username: [%s] ", getenv("USER"));
197 fflush(stdout);
199 memset(user, 0, sizeof(user));
200 if (fgets(user, sizeof(user), stdin) == NULL)
201 panic("Could not read from stdin!\n");
202 user[sizeof(user) - 1] = 0;
203 user[strlen(user) - 1] = 0; /* omit last \n */
204 if (strlen(user) == 0)
205 strlcpy(user, getenv("USER"), sizeof(user));
207 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
209 ret = write(fd, user, strlen(user));
210 if (ret != strlen(user))
211 panic("Could not write username!\n");
213 close(fd);
215 printf("Username written to %s!\n", path);
218 static void create_curvedir(char *home)
220 int ret;
221 char path[PATH_MAX];
223 memset(path, 0, sizeof(path));
224 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
226 errno = 0;
228 ret = mkdir(path, S_IRWXU);
229 if (ret < 0 && errno != EEXIST)
230 panic("Cannot create curvetun dir!\n");
232 printf("curvetun directory %s created!\n", path);
233 /* We also create empty files for clients and servers! */
235 memset(path, 0, sizeof(path));
236 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
238 create_or_die(path, S_IRUSR | S_IWUSR);
240 printf("Empty client file written to %s!\n", path);
242 memset(path, 0, sizeof(path));
243 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
245 create_or_die(path, S_IRUSR | S_IWUSR);
247 printf("Empty server file written to %s!\n", path);
250 static void create_keypair(char *home)
252 int fd, err = 0;
253 ssize_t ret;
254 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
255 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
256 char path[PATH_MAX];
257 const char * errstr = NULL;
259 printf("Reading from %s (this may take a while) ...\n", HIG_ENTROPY_SOURCE);
261 gen_key_bytes(secretkey, sizeof(secretkey));
262 crypto_scalarmult_curve25519_base(publickey, secretkey);
264 memset(path, 0, sizeof(path));
265 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
267 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
268 if (fd < 0) {
269 err = EIO;
270 errstr = "Cannot open pubkey file!\n";
271 goto out_noclose;
274 ret = write(fd, publickey, sizeof(publickey));
275 if (ret != sizeof(publickey)) {
276 err = EIO;
277 errstr = "Cannot write public key!\n";
278 goto out;
281 close(fd);
283 printf("Public key written to %s!\n", path);
285 memset(path, 0, sizeof(path));
286 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
288 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
289 if (fd < 0) {
290 err = EIO;
291 errstr = "Cannot open privkey file!\n";
292 goto out_noclose;
295 ret = write(fd, secretkey, sizeof(secretkey));
296 if (ret != sizeof(secretkey)) {
297 err = EIO;
298 errstr = "Cannot write private key!\n";
299 goto out;
301 out:
302 close(fd);
303 out_noclose:
304 xmemset(publickey, 0, sizeof(publickey));
305 xmemset(secretkey, 0, sizeof(secretkey));
307 if (err)
308 panic("%s: %s", errstr, strerror(errno));
309 else
310 printf("Private key written to %s!\n", path);
313 static void check_config_keypair_or_die(char *home)
315 int fd, err;
316 ssize_t ret;
317 const char * errstr = NULL;
318 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
319 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
320 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
321 char path[PATH_MAX];
323 memset(path, 0, sizeof(path));
324 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
326 fd = open(path, O_RDONLY);
327 if (fd < 0) {
328 err = EIO;
329 errstr = "Cannot open privkey file!\n";
330 goto out;
333 ret = read(fd, secretkey, sizeof(secretkey));
334 if (ret != sizeof(secretkey)) {
335 err = EIO;
336 errstr = "Cannot read private key!\n";
337 goto out;
340 close(fd);
342 memset(path, 0, sizeof(path));
343 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
345 fd = open(path, O_RDONLY);
346 if (fd < 0) {
347 err = EIO;
348 errstr = "Cannot open pubkey file!\n";
349 goto out;
352 ret = read(fd, publickey, sizeof(publickey));
353 if (ret != sizeof(publickey)) {
354 err = EIO;
355 errstr = "Cannot read public key!\n";
356 goto out;
359 crypto_scalarmult_curve25519_base(publicres, secretkey);
361 err = crypto_verify_32(publicres, publickey);
362 if (err) {
363 err = EINVAL;
364 errstr = "WARNING: your keypair is corrupted!!! You need to "
365 "generate new keys!!!\n";
366 goto out;
368 out:
369 close(fd);
371 xmemset(publickey, 0, sizeof(publickey));
372 xmemset(publicres, 0, sizeof(publicres));
373 xmemset(secretkey, 0, sizeof(secretkey));
375 if (err)
376 panic("%s: %s\n", errstr, strerror(errno));
379 static int main_keygen(char *home)
381 create_curvedir(home);
382 write_username(home);
383 create_keypair(home);
384 check_config_keypair_or_die(home);
386 return 0;
389 static int main_export(char *home)
391 int fd, i;
392 ssize_t ret;
393 char path[PATH_MAX], tmp[64];
395 check_config_exists_or_die(home);
396 check_config_keypair_or_die(home);
398 printf("Your exported public information:\n\n");
400 memset(path, 0, sizeof(path));
401 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
403 fd = open_or_die(path, O_RDONLY);
405 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
406 ret = write(STDOUT_FILENO, tmp, ret);
409 close(fd);
411 printf(";");
413 memset(path, 0, sizeof(path));
414 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
416 fd = open_or_die(path, O_RDONLY);
418 ret = read(fd, tmp, sizeof(tmp));
419 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
420 panic("Cannot read public key!\n");
422 for (i = 0; i < ret; ++i)
423 if (i == ret - 1)
424 printf("%02x\n\n", (unsigned char) tmp[i]);
425 else
426 printf("%02x:", (unsigned char) tmp[i]);
428 close(fd);
429 fflush(stdout);
431 return 0;
434 static int main_dumpc(char *home)
436 check_config_exists_or_die(home);
437 check_config_keypair_or_die(home);
439 printf("Your clients:\n\n");
441 parse_userfile_and_generate_user_store_or_die(home);
443 dump_user_store();
445 destroy_user_store();
447 printf("\n");
448 die();
449 return 0;
452 static int main_dumps(char *home)
454 check_config_exists_or_die(home);
455 check_config_keypair_or_die(home);
457 printf("Your servers:\n\n");
459 parse_userfile_and_generate_serv_store_or_die(home);
461 dump_serv_store();
463 destroy_serv_store();
465 printf("\n");
466 die();
467 return 0;
470 static void daemonize(const char *lockfile)
472 char pidstr[8];
473 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
474 int lfp;
476 if (getppid() == 1)
477 return;
479 if (daemon(0, 1))
480 panic("Cannot daemonize: %s", strerror(errno));
482 to_std_log(&stdout);
483 to_std_log(&stderr);
485 umask(lperm);
486 if (lockfile) {
487 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
488 S_IRUSR | S_IWUSR | S_IRGRP);
489 if (lfp < 0)
490 syslog_panic("Cannot create lockfile at %s! "
491 "curvetun server already running?\n",
492 lockfile);
494 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
495 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
496 syslog_panic("Could not write pid to pidfile %s",
497 lockfile);
499 close(lfp);
503 static int main_client(char *home, char *dev, char *alias, int daemon)
505 int ret, udp;
506 char *host, *port;
508 check_config_exists_or_die(home);
509 check_config_keypair_or_die(home);
511 parse_userfile_and_generate_serv_store_or_die(home);
513 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
514 &host, &port, &udp);
515 if (!host || !port || udp < 0)
516 panic("Did not find alias/entry in configuration!\n");
518 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
519 alias ? : "default", host, port, udp ? "udp" : "tcp");
520 if (daemon)
521 daemonize(NULL);
523 ret = client_main(home, dev, host, port, udp);
525 destroy_serv_store();
527 return ret;
530 static int main_server(char *home, char *dev, char *port, int udp,
531 int ipv4, int daemon, int log)
533 int ret;
535 check_config_exists_or_die(home);
536 check_config_keypair_or_die(home);
538 if (daemon)
539 daemonize(LOCKFILE);
541 ret = server_main(home, dev, port, udp, ipv4, log);
543 unlink(LOCKFILE);
545 return ret;
548 int main(int argc, char **argv)
550 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
551 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
552 enum working_mode wmode = MODE_UNKNOW;
554 setfsuid(getuid());
555 setfsgid(getgid());
557 home = fetch_home_dir();
559 while ((c = getopt_long(argc, argv, short_options, long_options,
560 &opt_index)) != EOF) {
561 switch (c) {
562 case 'h':
563 help();
564 break;
565 case 'v':
566 version();
567 break;
568 case 'D':
569 daemon = 0;
570 break;
571 case 'N':
572 log = 0;
573 break;
574 case 'C':
575 wmode = MODE_DUMPC;
576 break;
577 case 'S':
578 wmode = MODE_DUMPS;
579 break;
580 case 'c':
581 wmode = MODE_CLIENT;
582 if (optarg) {
583 if (*optarg == '=')
584 optarg++;
585 alias = xstrdup(optarg);
587 break;
588 case 'd':
589 dev = xstrdup(optarg);
590 break;
591 case 'k':
592 wmode = MODE_KEYGEN;
593 break;
594 case '4':
595 ipv4 = 1;
596 break;
597 case '6':
598 ipv4 = 0;
599 break;
600 case 'x':
601 wmode = MODE_EXPORT;
602 break;
603 case 's':
604 wmode = MODE_SERVER;
605 break;
606 case 'u':
607 udp = 1;
608 break;
609 case 't':
610 stun = xstrdup(optarg);
611 break;
612 case 'p':
613 port = xstrdup(optarg);
614 break;
615 case '?':
616 switch (optopt) {
617 case 't':
618 case 'd':
619 case 'u':
620 case 'p':
621 panic("Option -%c requires an argument!\n",
622 optopt);
623 default:
624 if (isprint(optopt))
625 printf("Unknown option character `0x%X\'!\n", optopt);
626 die();
628 default:
629 break;
633 if (argc < 2)
634 help();
636 register_signal(SIGINT, signal_handler);
637 register_signal(SIGHUP, signal_handler);
638 register_signal(SIGTERM, signal_handler);
639 register_signal(SIGPIPE, signal_handler);
641 curve25519_selftest();
643 switch (wmode) {
644 case MODE_KEYGEN:
645 ret = main_keygen(home);
646 break;
647 case MODE_EXPORT:
648 ret = main_export(home);
649 break;
650 case MODE_DUMPC:
651 ret = main_dumpc(home);
652 break;
653 case MODE_DUMPS:
654 ret = main_dumps(home);
655 break;
656 case MODE_CLIENT:
657 ret = main_client(home, dev, alias, daemon);
658 break;
659 case MODE_SERVER:
660 if (!port)
661 panic("No port specified!\n");
662 if (stun)
663 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
664 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
665 break;
666 default:
667 die();
670 free(dev);
671 free(stun);
672 free(port);
673 free(alias);
675 return ret;