die: minor: simplify code a bit
[netsniff-ng.git] / curvetun.c
blobffb63143d515cacec45dfff7ff6d22dd9237dc3b
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 "ct_usermgmt.h"
38 #include "ct_servmgmt.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 VPN/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, lightweight curve25519-based VPN/IP tunnel\n", VERSION_LONG);
133 puts("http://www.netsniff-ng.org\n\n"
134 "Please report bugs to <bugs@netsniff-ng.org>\n"
135 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
136 "Swiss federal institute of technology (ETH Zurich)\n"
137 "License: GNU GPL version 2.0\n"
138 "This is free software: you are free to change and redistribute it.\n"
139 "There is NO WARRANTY, to the extent permitted by law.\n");
140 die();
143 static void check_file_or_die(char *home, char *file, int maybeempty)
145 char path[PATH_MAX];
146 struct stat st;
148 memset(path, 0, sizeof(path));
149 slprintf(path, sizeof(path), "%s/%s", home, file);
151 if (stat(path, &st))
152 panic("No such file %s! Type --help for further information\n",
153 path);
155 if (!S_ISREG(st.st_mode))
156 panic("%s is not a regular file!\n", path);
158 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
159 panic("You have set too many permissions on %s (%o)!\n",
160 path, st.st_mode);
162 if (maybeempty == 0 && st.st_size == 0)
163 panic("%s is empty!\n", path);
166 static void check_config_exists_or_die(char *home)
168 if (!home)
169 panic("No home dir specified!\n");
171 check_file_or_die(home, FILE_CLIENTS, 1);
172 check_file_or_die(home, FILE_SERVERS, 1);
173 check_file_or_die(home, FILE_PRIVKEY, 0);
174 check_file_or_die(home, FILE_PUBKEY, 0);
175 check_file_or_die(home, FILE_USERNAM, 0);
178 static char *fetch_home_dir(void)
180 char *home = getenv("HOME");
181 if (!home)
182 panic("No HOME defined!\n");
183 return home;
186 static void write_username(char *home)
188 int fd, ret;
189 char path[PATH_MAX];
190 char user[512];
192 memset(path, 0, sizeof(path));
193 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
195 printf("Username: [%s] ", getenv("USER"));
196 fflush(stdout);
198 memset(user, 0, sizeof(user));
199 if (fgets(user, sizeof(user), stdin) == NULL)
200 panic("Could not read from stdin!\n");
201 user[sizeof(user) - 1] = 0;
202 user[strlen(user) - 1] = 0; /* omit last \n */
203 if (strlen(user) == 0)
204 strlcpy(user, getenv("USER"), sizeof(user));
206 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
208 ret = write(fd, user, strlen(user));
209 if (ret != strlen(user))
210 panic("Could not write username!\n");
212 close(fd);
214 printf("Username written to %s!\n", path);
217 static void create_curvedir(char *home)
219 int ret;
220 char path[PATH_MAX];
222 memset(path, 0, sizeof(path));
223 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
225 errno = 0;
227 ret = mkdir(path, S_IRWXU);
228 if (ret < 0 && errno != EEXIST)
229 panic("Cannot create curvetun dir!\n");
231 printf("curvetun directory %s created!\n", path);
232 /* We also create empty files for clients and servers! */
234 memset(path, 0, sizeof(path));
235 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
237 create_or_die(path, S_IRUSR | S_IWUSR);
239 printf("Empty client file written to %s!\n", path);
241 memset(path, 0, sizeof(path));
242 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
244 create_or_die(path, S_IRUSR | S_IWUSR);
246 printf("Empty server file written to %s!\n", path);
249 static void create_keypair(char *home)
251 int fd, err = 0;
252 ssize_t ret;
253 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
254 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
255 char path[PATH_MAX];
256 const char * errstr = NULL;
258 printf("Reading from %s (this may take a while) ...\n", HIG_ENTROPY_SOURCE);
260 gen_key_bytes(secretkey, sizeof(secretkey));
261 crypto_scalarmult_curve25519_base(publickey, secretkey);
263 memset(path, 0, sizeof(path));
264 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
266 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
267 if (fd < 0) {
268 err = EIO;
269 errstr = "Cannot open pubkey file!\n";
270 goto out_noclose;
273 ret = write(fd, publickey, sizeof(publickey));
274 if (ret != sizeof(publickey)) {
275 err = EIO;
276 errstr = "Cannot write public key!\n";
277 goto out;
280 close(fd);
282 printf("Public key written to %s!\n", path);
284 memset(path, 0, sizeof(path));
285 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
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 privkey file!\n";
291 goto out_noclose;
294 ret = write(fd, secretkey, sizeof(secretkey));
295 if (ret != sizeof(secretkey)) {
296 err = EIO;
297 errstr = "Cannot write private key!\n";
298 goto out;
300 out:
301 close(fd);
302 out_noclose:
303 xmemset(publickey, 0, sizeof(publickey));
304 xmemset(secretkey, 0, sizeof(secretkey));
306 if (err)
307 panic("%s: %s", errstr, strerror(errno));
308 else
309 printf("Private key written to %s!\n", path);
312 static void check_config_keypair_or_die(char *home)
314 int fd, err;
315 ssize_t ret;
316 const char * errstr = NULL;
317 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
318 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
319 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
320 char path[PATH_MAX];
322 memset(path, 0, sizeof(path));
323 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
325 fd = open(path, O_RDONLY);
326 if (fd < 0) {
327 err = EIO;
328 errstr = "Cannot open privkey file!\n";
329 goto out;
332 ret = read(fd, secretkey, sizeof(secretkey));
333 if (ret != sizeof(secretkey)) {
334 err = EIO;
335 errstr = "Cannot read private key!\n";
336 goto out;
339 close(fd);
341 memset(path, 0, sizeof(path));
342 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
344 fd = open(path, O_RDONLY);
345 if (fd < 0) {
346 err = EIO;
347 errstr = "Cannot open pubkey file!\n";
348 goto out;
351 ret = read(fd, publickey, sizeof(publickey));
352 if (ret != sizeof(publickey)) {
353 err = EIO;
354 errstr = "Cannot read public key!\n";
355 goto out;
358 crypto_scalarmult_curve25519_base(publicres, secretkey);
360 err = crypto_verify_32(publicres, publickey);
361 if (err) {
362 err = EINVAL;
363 errstr = "WARNING: your keypair is corrupted!!! You need to "
364 "generate new keys!!!\n";
365 goto out;
367 out:
368 close(fd);
370 xmemset(publickey, 0, sizeof(publickey));
371 xmemset(publicres, 0, sizeof(publicres));
372 xmemset(secretkey, 0, sizeof(secretkey));
374 if (err)
375 panic("%s: %s\n", errstr, strerror(errno));
378 static int main_keygen(char *home)
380 create_curvedir(home);
381 write_username(home);
382 create_keypair(home);
383 check_config_keypair_or_die(home);
385 return 0;
388 static int main_export(char *home)
390 int fd, i;
391 ssize_t ret;
392 char path[PATH_MAX], tmp[64];
394 check_config_exists_or_die(home);
395 check_config_keypair_or_die(home);
397 printf("Your exported public information:\n\n");
399 memset(path, 0, sizeof(path));
400 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
402 fd = open_or_die(path, O_RDONLY);
404 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
405 ret = write(STDOUT_FILENO, tmp, ret);
408 close(fd);
410 printf(";");
412 memset(path, 0, sizeof(path));
413 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
415 fd = open_or_die(path, O_RDONLY);
417 ret = read(fd, tmp, sizeof(tmp));
418 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
419 panic("Cannot read public key!\n");
421 for (i = 0; i < ret; ++i)
422 if (i == ret - 1)
423 printf("%02x\n\n", (unsigned char) tmp[i]);
424 else
425 printf("%02x:", (unsigned char) tmp[i]);
427 close(fd);
428 fflush(stdout);
430 return 0;
433 static int main_dumpc(char *home)
435 check_config_exists_or_die(home);
436 check_config_keypair_or_die(home);
438 printf("Your clients:\n\n");
440 parse_userfile_and_generate_user_store_or_die(home);
442 dump_user_store();
444 destroy_user_store();
446 printf("\n");
447 die();
448 return 0;
451 static int main_dumps(char *home)
453 check_config_exists_or_die(home);
454 check_config_keypair_or_die(home);
456 printf("Your servers:\n\n");
458 parse_userfile_and_generate_serv_store_or_die(home);
460 dump_serv_store();
462 destroy_serv_store();
464 printf("\n");
465 die();
466 return 0;
469 static void daemonize(const char *lockfile)
471 char pidstr[8];
472 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
473 int lfp;
475 if (getppid() == 1)
476 return;
478 if (daemon(0, 1))
479 panic("Cannot daemonize: %s", strerror(errno));
481 to_std_log(&stdout);
482 to_std_log(&stderr);
484 umask(lperm);
485 if (lockfile) {
486 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
487 S_IRUSR | S_IWUSR | S_IRGRP);
488 if (lfp < 0)
489 syslog_panic("Cannot create lockfile at %s! "
490 "curvetun server already running?\n",
491 lockfile);
493 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
494 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
495 syslog_panic("Could not write pid to pidfile %s",
496 lockfile);
498 close(lfp);
502 static int main_client(char *home, char *dev, char *alias, int daemon)
504 int ret, udp;
505 char *host, *port;
507 check_config_exists_or_die(home);
508 check_config_keypair_or_die(home);
510 parse_userfile_and_generate_serv_store_or_die(home);
512 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
513 &host, &port, &udp);
514 if (!host || !port || udp < 0)
515 panic("Did not find alias/entry in configuration!\n");
517 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
518 alias ? : "default", host, port, udp ? "udp" : "tcp");
519 if (daemon)
520 daemonize(NULL);
522 ret = client_main(home, dev, host, port, udp);
524 destroy_serv_store();
526 return ret;
529 static int main_server(char *home, char *dev, char *port, int udp,
530 int ipv4, int daemon, int log)
532 int ret;
534 check_config_exists_or_die(home);
535 check_config_keypair_or_die(home);
537 if (daemon)
538 daemonize(LOCKFILE);
540 ret = server_main(home, dev, port, udp, ipv4, log);
542 unlink(LOCKFILE);
544 return ret;
547 int main(int argc, char **argv)
549 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
550 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
551 enum working_mode wmode = MODE_UNKNOW;
553 setfsuid(getuid());
554 setfsgid(getgid());
556 home = fetch_home_dir();
558 while ((c = getopt_long(argc, argv, short_options, long_options,
559 &opt_index)) != EOF) {
560 switch (c) {
561 case 'h':
562 help();
563 break;
564 case 'v':
565 version();
566 break;
567 case 'D':
568 daemon = 0;
569 break;
570 case 'N':
571 log = 0;
572 break;
573 case 'C':
574 wmode = MODE_DUMPC;
575 break;
576 case 'S':
577 wmode = MODE_DUMPS;
578 break;
579 case 'c':
580 wmode = MODE_CLIENT;
581 if (optarg) {
582 if (*optarg == '=')
583 optarg++;
584 alias = xstrdup(optarg);
586 break;
587 case 'd':
588 dev = xstrdup(optarg);
589 break;
590 case 'k':
591 wmode = MODE_KEYGEN;
592 break;
593 case '4':
594 ipv4 = 1;
595 break;
596 case '6':
597 ipv4 = 0;
598 break;
599 case 'x':
600 wmode = MODE_EXPORT;
601 break;
602 case 's':
603 wmode = MODE_SERVER;
604 break;
605 case 'u':
606 udp = 1;
607 break;
608 case 't':
609 stun = xstrdup(optarg);
610 break;
611 case 'p':
612 port = xstrdup(optarg);
613 break;
614 case '?':
615 switch (optopt) {
616 case 't':
617 case 'd':
618 case 'u':
619 case 'p':
620 panic("Option -%c requires an argument!\n",
621 optopt);
622 default:
623 if (isprint(optopt))
624 printf("Unknown option character `0x%X\'!\n", optopt);
625 die();
627 default:
628 break;
632 if (argc < 2)
633 help();
635 register_signal(SIGINT, signal_handler);
636 register_signal(SIGHUP, signal_handler);
637 register_signal(SIGTERM, signal_handler);
638 register_signal(SIGPIPE, signal_handler);
640 curve25519_selftest();
642 switch (wmode) {
643 case MODE_KEYGEN:
644 ret = main_keygen(home);
645 break;
646 case MODE_EXPORT:
647 ret = main_export(home);
648 break;
649 case MODE_DUMPC:
650 ret = main_dumpc(home);
651 break;
652 case MODE_DUMPS:
653 ret = main_dumps(home);
654 break;
655 case MODE_CLIENT:
656 ret = main_client(home, dev, alias, daemon);
657 break;
658 case MODE_SERVER:
659 if (!port)
660 panic("No port specified!\n");
661 if (stun)
662 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
663 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
664 break;
665 default:
666 die();
669 free(dev);
670 free(stun);
671 free(port);
672 free(alias);
674 return ret;