make: include build name
[netsniff-ng.git] / curvetun.c
blob29bee4a8e69f0ed9fc909d145e80fa369701f1c8
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 "xutils.h"
29 #include "die.h"
30 #include "xmalloc.h"
31 #include "curvetun.h"
32 #include "curve.h"
33 #include "ct_usermgmt.h"
34 #include "ct_servmgmt.h"
35 #include "xio.h"
36 #include "tprintf.h"
37 #include "crypto_verify_32.h"
38 #include "crypto_box_curve25519xsalsa20poly1305.h"
39 #include "crypto_scalarmult_curve25519.h"
40 #include "crypto_auth_hmacsha512256.h"
42 #define CURVETUN_ENTROPY_SOURCE "/dev/random"
44 extern void print_stun_probe(char *server, uint16_t sport, uint16_t tunport);
46 enum working_mode {
47 MODE_UNKNOW,
48 MODE_KEYGEN,
49 MODE_EXPORT,
50 MODE_DUMPC,
51 MODE_DUMPS,
52 MODE_CLIENT,
53 MODE_SERVER,
56 volatile sig_atomic_t sigint = 0;
58 static const char *short_options = "kxc::svhp:t:d:uCS46DN";
59 static const struct option long_options[] = {
60 {"client", optional_argument, NULL, 'c'},
61 {"dev", required_argument, NULL, 'd'},
62 {"port", required_argument, NULL, 'p'},
63 {"stun", required_argument, NULL, 't'},
64 {"keygen", no_argument, NULL, 'k'},
65 {"export", no_argument, NULL, 'x'},
66 {"dumpc", no_argument, NULL, 'C'},
67 {"dumps", no_argument, NULL, 'S'},
68 {"no-logging", no_argument, NULL, 'N'},
69 {"server", no_argument, NULL, 's'},
70 {"udp", no_argument, NULL, 'u'},
71 {"ipv4", no_argument, NULL, '4'},
72 {"ipv6", no_argument, NULL, '6'},
73 {"nofork", no_argument, NULL, 'D'},
74 {"version", no_argument, NULL, 'v'},
75 {"help", no_argument, NULL, 'h'},
76 {NULL, 0, NULL, 0}
79 static void signal_handler(int number)
81 switch (number) {
82 case SIGINT:
83 case SIGTERM:
84 sigint = 1;
85 break;
86 default:
87 break;
91 static void __noreturn help(void)
93 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n", VERSION_STRING);
94 puts("http://www.netsniff-ng.org\n\n"
95 "Usage: curvetun [options]\n"
96 "Options, general:\n"
97 " -d|--dev <tun> Networking tunnel device, e.g. tun0\n"
98 " -p|--port <num> Server port number (mandatory)\n"
99 " -t|--stun <server> Show public IP/Port mapping via STUN\n"
100 " -c|--client[=alias] Client mode, server alias optional\n"
101 " -k|--keygen Generate public/private keypair\n"
102 " -x|--export Export your public data for remote servers\n"
103 " -C|--dumpc Dump parsed clients\n"
104 " -S|--dumps Dump parsed servers\n"
105 " -D|--nofork Do not daemonize\n"
106 " -s|--server Server mode, options follow below\n"
107 " -N|--no-logging Disable server logging (for better anonymity)\n"
108 " -u|--udp Use UDP as carrier instead of TCP\n"
109 " -4|--ipv4 Tunnel devices are IPv4\n"
110 " -6|--ipv6 Tunnel devices are IPv6\n"
111 " -v|--version Print version and exit\n"
112 " -h|--help Print this help and exit\n\n"
113 "Example:\n"
114 " See curvetun's man page for a configuration example.\n"
115 " curvetun --server -4 -u -N --port 6666 --stun stunserver.org\n"
116 " curvetun --client=ethz\n\n"
117 " curvetun --keygen\n"
118 " curvetun --export\n"
119 "Note:\n"
120 " There is no default port specified, so that you are forced\n"
121 " to select your own! For client/server status messages see syslog!\n"
122 " This software is an experimental prototype intended for researchers.\n\n"
123 "Secret ingredient: 7647-14-5\n\n"
124 "Please report bugs to <bugs@netsniff-ng.org>\n"
125 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
126 "Swiss federal institute of technology (ETH Zurich)\n"
127 "License: GNU GPL version 2.0\n"
128 "This is free software: you are free to change and redistribute it.\n"
129 "There is NO WARRANTY, to the extent permitted by law.\n");
130 die();
133 static void __noreturn version(void)
135 printf("\ncurvetun %s, lightweight curve25519-based VPN/IP tunnel\n", VERSION_LONG);
136 puts("http://www.netsniff-ng.org\n\n"
137 "Please report bugs to <bugs@netsniff-ng.org>\n"
138 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
139 "Swiss federal institute of technology (ETH Zurich)\n"
140 "License: GNU GPL version 2.0\n"
141 "This is free software: you are free to change and redistribute it.\n"
142 "There is NO WARRANTY, to the extent permitted by law.\n");
143 die();
146 static void check_file_or_die(char *home, char *file, int maybeempty)
148 char path[PATH_MAX];
149 struct stat st;
151 memset(path, 0, sizeof(path));
152 slprintf(path, sizeof(path), "%s/%s", home, file);
154 if (stat(path, &st))
155 panic("No such file %s! Type --help for further information\n",
156 path);
158 if (!S_ISREG(st.st_mode))
159 panic("%s is not a regular file!\n", path);
161 if ((st.st_mode & ~S_IFREG) != (S_IRUSR | S_IWUSR))
162 panic("You have set too many permissions on %s (%o)!\n",
163 path, st.st_mode);
165 if (maybeempty == 0 && st.st_size == 0)
166 panic("%s is empty!\n", path);
169 static void check_config_exists_or_die(char *home)
171 if (!home)
172 panic("No home dir specified!\n");
174 check_file_or_die(home, FILE_CLIENTS, 1);
175 check_file_or_die(home, FILE_SERVERS, 1);
176 check_file_or_die(home, FILE_PRIVKEY, 0);
177 check_file_or_die(home, FILE_PUBKEY, 0);
178 check_file_or_die(home, FILE_USERNAM, 0);
181 static char *fetch_home_dir(void)
183 char *home = getenv("HOME");
184 if (!home)
185 panic("No HOME defined!\n");
186 return home;
189 static void write_username(char *home)
191 int fd, ret;
192 char path[PATH_MAX];
193 char user[512];
195 memset(path, 0, sizeof(path));
196 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
198 printf("Username: [%s] ", getenv("USER"));
199 fflush(stdout);
201 memset(user, 0, sizeof(user));
202 if (fgets(user, sizeof(user), stdin) == NULL)
203 panic("Could not read from stdin!\n");
204 user[sizeof(user) - 1] = 0;
205 user[strlen(user) - 1] = 0; /* omit last \n */
206 if (strlen(user) == 0)
207 strlcpy(user, getenv("USER"), sizeof(user));
209 fd = open_or_die_m(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
211 ret = write(fd, user, strlen(user));
212 if (ret != strlen(user))
213 panic("Could not write username!\n");
215 close(fd);
217 printf("Username written to %s!\n", path);
220 static void create_curvedir(char *home)
222 int ret;
223 char path[PATH_MAX];
225 memset(path, 0, sizeof(path));
226 slprintf(path, sizeof(path), "%s/%s", home, ".curvetun/");
228 errno = 0;
230 ret = mkdir(path, S_IRWXU);
231 if (ret < 0 && errno != EEXIST)
232 panic("Cannot create curvetun dir!\n");
234 printf("curvetun directory %s created!\n", path);
235 /* We also create empty files for clients and servers! */
237 memset(path, 0, sizeof(path));
238 slprintf(path, sizeof(path), "%s/%s", home, FILE_CLIENTS);
240 create_or_die(path, S_IRUSR | S_IWUSR);
242 printf("Empty client file written to %s!\n", path);
244 memset(path, 0, sizeof(path));
245 slprintf(path, sizeof(path), "%s/%s", home, FILE_SERVERS);
247 create_or_die(path, S_IRUSR | S_IWUSR);
249 printf("Empty server file written to %s!\n", path);
252 static void create_keypair(char *home)
254 int fd, err = 0;
255 ssize_t ret;
256 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
257 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
258 char path[PATH_MAX];
259 const char * errstr = NULL;
261 printf("Reading from %s (this may take a while) ...\n", CURVETUN_ENTROPY_SOURCE);
263 fd = open_or_die(CURVETUN_ENTROPY_SOURCE, O_RDONLY);
265 ret = read_exact(fd, secretkey, sizeof(secretkey), 0);
266 if (ret != sizeof(secretkey)) {
267 err = EIO;
268 errstr = "Cannot read from "CURVETUN_ENTROPY_SOURCE"!\n";
269 goto out;
272 close(fd);
274 crypto_scalarmult_curve25519_base(publickey, secretkey);
276 memset(path, 0, sizeof(path));
277 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
279 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
280 if (fd < 0) {
281 err = EIO;
282 errstr = "Cannot open pubkey file!\n";
283 goto out_noclose;
286 ret = write(fd, publickey, sizeof(publickey));
287 if (ret != sizeof(publickey)) {
288 err = EIO;
289 errstr = "Cannot write public key!\n";
290 goto out;
293 close(fd);
295 printf("Public key written to %s!\n", path);
297 memset(path, 0, sizeof(path));
298 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
300 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
301 if (fd < 0) {
302 err = EIO;
303 errstr = "Cannot open privkey file!\n";
304 goto out_noclose;
307 ret = write(fd, secretkey, sizeof(secretkey));
308 if (ret != sizeof(secretkey)) {
309 err = EIO;
310 errstr = "Cannot write private key!\n";
311 goto out;
313 out:
314 close(fd);
315 out_noclose:
316 xmemset(publickey, 0, sizeof(publickey));
317 xmemset(secretkey, 0, sizeof(secretkey));
319 if (err)
320 panic("%s: %s", errstr, strerror(errno));
321 else
322 printf("Private key written to %s!\n", path);
325 static void check_config_keypair_or_die(char *home)
327 int fd, err;
328 ssize_t ret;
329 const char * errstr = NULL;
330 unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
331 unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
332 unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
333 char path[PATH_MAX];
335 memset(path, 0, sizeof(path));
336 slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);
338 fd = open(path, O_RDONLY);
339 if (fd < 0) {
340 err = EIO;
341 errstr = "Cannot open privkey file!\n";
342 goto out;
345 ret = read(fd, secretkey, sizeof(secretkey));
346 if (ret != sizeof(secretkey)) {
347 err = EIO;
348 errstr = "Cannot read private key!\n";
349 goto out;
352 close(fd);
354 memset(path, 0, sizeof(path));
355 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
357 fd = open(path, O_RDONLY);
358 if (fd < 0) {
359 err = EIO;
360 errstr = "Cannot open pubkey file!\n";
361 goto out;
364 ret = read(fd, publickey, sizeof(publickey));
365 if (ret != sizeof(publickey)) {
366 err = EIO;
367 errstr = "Cannot read public key!\n";
368 goto out;
371 crypto_scalarmult_curve25519_base(publicres, secretkey);
373 err = crypto_verify_32(publicres, publickey);
374 if (err) {
375 err = EINVAL;
376 errstr = "WARNING: your keypair is corrupted!!! You need to "
377 "generate new keys!!!\n";
378 goto out;
380 out:
381 close(fd);
383 xmemset(publickey, 0, sizeof(publickey));
384 xmemset(publicres, 0, sizeof(publicres));
385 xmemset(secretkey, 0, sizeof(secretkey));
387 if (err)
388 panic("%s: %s\n", errstr, strerror(errno));
391 static int main_keygen(char *home)
393 create_curvedir(home);
394 write_username(home);
395 create_keypair(home);
396 check_config_keypair_or_die(home);
398 return 0;
401 static int main_export(char *home)
403 int fd, i;
404 ssize_t ret;
405 char path[PATH_MAX], tmp[64];
407 check_config_exists_or_die(home);
408 check_config_keypair_or_die(home);
410 printf("Your exported public information:\n\n");
412 memset(path, 0, sizeof(path));
413 slprintf(path, sizeof(path), "%s/%s", home, FILE_USERNAM);
415 fd = open_or_die(path, O_RDONLY);
417 while ((ret = read(fd, tmp, sizeof(tmp))) > 0) {
418 ret = write(STDOUT_FILENO, tmp, ret);
421 close(fd);
423 printf(";");
425 memset(path, 0, sizeof(path));
426 slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);
428 fd = open_or_die(path, O_RDONLY);
430 ret = read(fd, tmp, sizeof(tmp));
431 if (ret != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
432 panic("Cannot read public key!\n");
434 for (i = 0; i < ret; ++i)
435 if (i == ret - 1)
436 printf("%02x\n\n", (unsigned char) tmp[i]);
437 else
438 printf("%02x:", (unsigned char) tmp[i]);
440 close(fd);
441 fflush(stdout);
443 return 0;
446 static int main_dumpc(char *home)
448 check_config_exists_or_die(home);
449 check_config_keypair_or_die(home);
451 printf("Your clients:\n\n");
453 parse_userfile_and_generate_user_store_or_die(home);
455 dump_user_store();
457 destroy_user_store();
459 printf("\n");
460 die();
461 return 0;
464 static int main_dumps(char *home)
466 check_config_exists_or_die(home);
467 check_config_keypair_or_die(home);
469 printf("Your servers:\n\n");
471 parse_userfile_and_generate_serv_store_or_die(home);
473 dump_serv_store();
475 destroy_serv_store();
477 printf("\n");
478 die();
479 return 0;
482 static void daemonize(const char *lockfile)
484 char pidstr[8];
485 mode_t lperm = S_IRWXU | S_IRGRP | S_IXGRP; /* 0750 */
486 int lfp;
488 if (getppid() == 1)
489 return;
491 if (daemon(0, 1))
492 panic("Cannot daemonize: %s", strerror(errno));
494 to_std_log(&stdout);
495 to_std_log(&stderr);
497 umask(lperm);
498 if (lockfile) {
499 lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
500 S_IRUSR | S_IWUSR | S_IRGRP);
501 if (lfp < 0)
502 syslog_panic("Cannot create lockfile at %s! "
503 "curvetun server already running?\n",
504 lockfile);
506 slprintf(pidstr, sizeof(pidstr), "%u", getpid());
507 if (write(lfp, pidstr, strlen(pidstr)) <= 0)
508 syslog_panic("Could not write pid to pidfile %s",
509 lockfile);
511 close(lfp);
515 static int main_client(char *home, char *dev, char *alias, int daemon)
517 int ret, udp;
518 char *host, *port;
520 check_config_exists_or_die(home);
521 check_config_keypair_or_die(home);
523 parse_userfile_and_generate_serv_store_or_die(home);
525 get_serv_store_entry_by_alias(alias, alias ? strlen(alias) + 1 : 0,
526 &host, &port, &udp);
527 if (!host || !port || udp < 0)
528 panic("Did not find alias/entry in configuration!\n");
530 printf("Using [%s] -> %s:%s via %s as endpoint!\n",
531 alias ? : "default", host, port, udp ? "udp" : "tcp");
532 if (daemon)
533 daemonize(NULL);
535 ret = client_main(home, dev, host, port, udp);
537 destroy_serv_store();
539 return ret;
542 static int main_server(char *home, char *dev, char *port, int udp,
543 int ipv4, int daemon, int log)
545 int ret;
547 check_config_exists_or_die(home);
548 check_config_keypair_or_die(home);
550 if (daemon)
551 daemonize(LOCKFILE);
553 ret = server_main(home, dev, port, udp, ipv4, log);
555 unlink(LOCKFILE);
557 return ret;
560 int main(int argc, char **argv)
562 int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
563 char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
564 enum working_mode wmode = MODE_UNKNOW;
566 setfsuid(getuid());
567 setfsgid(getgid());
569 home = fetch_home_dir();
571 while ((c = getopt_long(argc, argv, short_options, long_options,
572 &opt_index)) != EOF) {
573 switch (c) {
574 case 'h':
575 help();
576 break;
577 case 'v':
578 version();
579 break;
580 case 'D':
581 daemon = 0;
582 break;
583 case 'N':
584 log = 0;
585 break;
586 case 'C':
587 wmode = MODE_DUMPC;
588 break;
589 case 'S':
590 wmode = MODE_DUMPS;
591 break;
592 case 'c':
593 wmode = MODE_CLIENT;
594 if (optarg) {
595 if (*optarg == '=')
596 optarg++;
597 alias = xstrdup(optarg);
599 break;
600 case 'd':
601 dev = xstrdup(optarg);
602 break;
603 case 'k':
604 wmode = MODE_KEYGEN;
605 break;
606 case '4':
607 ipv4 = 1;
608 break;
609 case '6':
610 ipv4 = 0;
611 break;
612 case 'x':
613 wmode = MODE_EXPORT;
614 break;
615 case 's':
616 wmode = MODE_SERVER;
617 break;
618 case 'u':
619 udp = 1;
620 break;
621 case 't':
622 stun = xstrdup(optarg);
623 break;
624 case 'p':
625 port = xstrdup(optarg);
626 break;
627 case '?':
628 switch (optopt) {
629 case 't':
630 case 'd':
631 case 'u':
632 case 'p':
633 panic("Option -%c requires an argument!\n",
634 optopt);
635 default:
636 if (isprint(optopt))
637 printf("Unknown option character `0x%X\'!\n", optopt);
638 die();
640 default:
641 break;
645 if (argc < 2)
646 help();
648 register_signal(SIGINT, signal_handler);
649 register_signal(SIGHUP, signal_handler);
650 register_signal(SIGTERM, signal_handler);
651 register_signal(SIGPIPE, signal_handler);
653 curve25519_selftest();
655 switch (wmode) {
656 case MODE_KEYGEN:
657 ret = main_keygen(home);
658 break;
659 case MODE_EXPORT:
660 ret = main_export(home);
661 break;
662 case MODE_DUMPC:
663 ret = main_dumpc(home);
664 break;
665 case MODE_DUMPS:
666 ret = main_dumps(home);
667 break;
668 case MODE_CLIENT:
669 ret = main_client(home, dev, alias, daemon);
670 break;
671 case MODE_SERVER:
672 if (!port)
673 panic("No port specified!\n");
674 if (stun)
675 print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
676 ret = main_server(home, dev, port, udp, ipv4, daemon, log);
677 break;
678 default:
679 die();
682 free(dev);
683 free(stun);
684 free(port);
685 free(alias);
687 return ret;