2 sptps_test.c -- Simple Peer-to-Peer Security test program
3 Copyright (C) 2011-2022 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <linux/if_tun.h>
36 #define closesocket(s) close(s)
39 // Symbols necessary to link with logger.o
40 bool send_request(struct connection_t *c, const char *msg, ...) {
46 list_t connection_list;
48 bool send_meta(struct connection_t *c, const void *msg, size_t len) {
55 bool do_detach = false;
61 static bool writeonly;
64 int addressfamily = AF_UNSPEC;
66 static bool send_data(void *handle, uint8_t type, const void *data, size_t len) {
68 char *hex = alloca(len * 2 + 1);
69 bin2hex(data, hex, len);
72 fprintf(stderr, "Sending %lu bytes of data:\n%s\n", (unsigned long)len, hex);
75 const int *sock = handle;
79 ssize_t sent = send(*sock, p, len, 0);
82 fprintf(stderr, "Error sending data: %s\n", strerror(errno));
93 static bool receive_record(void *handle, uint8_t type, const void *data, uint16_t len) {
97 fprintf(stderr, "Received type %d record of %u bytes:\n", type, len);
104 const char *p = data;
107 ssize_t written = write(out, p, len);
110 fprintf(stderr, "Error writing received data: %s\n", strerror(errno));
121 typedef enum option_t {
122 OPT_BAD_OPTION = '?',
127 OPT_QUIT_ON_EOF = 'q',
130 OPT_PACKET_LOSS = 'L',
131 OPT_REPLAY_WINDOW = 'W',
132 OPT_SPECIAL_CHAR = 's',
142 static struct option const long_options[] = {
143 {"datagram", no_argument, NULL, OPT_DATAGRAM},
144 {"quit", no_argument, NULL, OPT_QUIT_ON_EOF},
145 {"readonly", no_argument, NULL, OPT_READONLY},
146 {"writeonly", no_argument, NULL, OPT_WRITEONLY},
147 {"packet-loss", required_argument, NULL, OPT_PACKET_LOSS},
148 {"replay-window", required_argument, NULL, OPT_REPLAY_WINDOW},
149 {"special", no_argument, NULL, OPT_SPECIAL_CHAR},
150 {"tun", no_argument, NULL, OPT_TUN},
151 {"verbose", required_argument, NULL, OPT_VERBOSE},
152 {"help", no_argument, NULL, OPT_HELP},
156 static void usage(void) {
158 "Usage: %s [options] my_ed25519_key_file his_ed25519_key_file [host] port\n"
160 "Valid options are:\n"
161 " -d, --datagram Enable datagram mode.\n"
162 " -q, --quit Quit when EOF occurs on stdin.\n"
163 " -r, --readonly Only send data from the socket to stdout.\n"
165 " -t, --tun Use a tun device instead of stdio.\n"
167 " -w, --writeonly Only send data from stdin to the socket.\n"
168 " -L, --packet-loss RATE Fake packet loss of RATE percent.\n"
169 " -R, --replay-window N Set replay window to N bytes.\n"
170 " -s, --special Enable special handling of lines starting with #, ^ and $.\n"
171 " -v, --verbose Display debug messages.\n"
175 "Report bugs to tinc@tinc-vpn.org.\n",
181 int stdin_sock_fd = -1;
183 // Windows does not allow calling select() on anything but sockets. Therefore,
184 // to keep the same code as on other operating systems, we have to put a
185 // separate thread between the stdin and the sptps loop way below. This thread
186 // reads stdin and sends its content to the main thread through a TCP socket,
187 // which can be properly select()'ed.
188 static DWORD WINAPI stdin_reader_thread(LPVOID arg) {
189 struct sockaddr_in sa;
190 socklen_t sa_size = sizeof(sa);
193 int peer_fd = accept(stdin_sock_fd, (struct sockaddr *) &sa, &sa_size);
196 fprintf(stderr, "accept() failed: %s\n", strerror(errno));
201 fprintf(stderr, "New connection received from :%d\n", ntohs(sa.sin_port));
207 while((nread = read(STDIN_FILENO, buf, sizeof(buf))) > 0) {
209 fprintf(stderr, "Read %lld bytes from input\n", nread);
213 ssize_t nleft = nread;
216 ssize_t nsend = send(peer_fd, start, nleft, 0);
219 if(sockwouldblock(sockerrno)) {
231 fprintf(stderr, "Could not send data: %s\n", strerror(errno));
236 fprintf(stderr, "Sent %lld bytes to peer\n", nread);
240 closesocket(peer_fd);
243 closesocket(stdin_sock_fd);
248 static int start_input_reader(void) {
249 if(stdin_sock_fd != -1) {
250 fprintf(stderr, "stdin thread can only be started once.\n");
254 stdin_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
256 if(stdin_sock_fd < 0) {
257 fprintf(stderr, "Could not create server socket: %s\n", strerror(errno));
261 struct sockaddr_in serv_sa;
263 memset(&serv_sa, 0, sizeof(serv_sa));
265 serv_sa.sin_family = AF_INET;
267 serv_sa.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
269 int res = bind(stdin_sock_fd, (struct sockaddr *)&serv_sa, sizeof(serv_sa));
272 fprintf(stderr, "Could not bind socket: %s\n", strerror(errno));
276 if(listen(stdin_sock_fd, 1) < 0) {
277 fprintf(stderr, "Could not listen: %s\n", strerror(errno));
281 struct sockaddr_in connect_sa;
283 socklen_t addr_len = sizeof(connect_sa);
285 if(getsockname(stdin_sock_fd, (struct sockaddr *)&connect_sa, &addr_len) < 0) {
286 fprintf(stderr, "Could not determine the address of the stdin thread socket\n");
291 fprintf(stderr, "stdin thread is listening on :%d\n", ntohs(connect_sa.sin_port));
294 if(!CreateThread(NULL, 0, stdin_reader_thread, NULL, 0, NULL)) {
295 fprintf(stderr, "Could not start reader thread: %d\n", GetLastError());
299 int client_fd = socket(AF_INET, SOCK_STREAM, 0);
302 fprintf(stderr, "Could not create client socket: %s\n", strerror(errno));
306 if(connect(client_fd, (struct sockaddr *)&connect_sa, sizeof(connect_sa)) < 0) {
307 fprintf(stderr, "Could not connect: %s\n", strerror(errno));
308 closesocket(client_fd);
316 if(stdin_sock_fd != -1) {
317 closesocket(stdin_sock_fd);
324 #endif // HAVE_WINDOWS
326 static void print_listening_msg(int sock) {
328 socklen_t salen = sizeof(sa);
331 if(!getsockname(sock, &sa.sa, &salen)) {
332 port = ntohs(sa.in.sin_port);
335 fprintf(stderr, "Listening on %d...\n", port);
339 static int run_test(int argc, char *argv[]) {
340 program_name = argv[0];
341 bool initiator = false;
342 bool datagram = false;
348 int option_index = 0;
351 while((r = getopt_long(argc, argv, "dqrstwL:W:v46", long_options, &option_index)) != EOF) {
352 switch((option_t) r) {
353 case OPT_LONG_OPTION:
364 case OPT_QUIT_ON_EOF:
376 fprintf(stderr, "--tun is only supported on Linux.\n");
386 case OPT_PACKET_LOSS:
387 packetloss = atoi(optarg);
390 case OPT_REPLAY_WINDOW:
391 sptps_replaywin = atoi(optarg);
398 case OPT_SPECIAL_CHAR:
403 addressfamily = AF_INET;
407 addressfamily = AF_INET6;
422 if(argc < 4 || argc > 5) {
423 fprintf(stderr, "Wrong number of arguments.\n");
435 in = out = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
438 fprintf(stderr, "Could not open tun device: %s\n", strerror(errno));
446 if(ioctl(in, TUNSETIFF, &ifr)) {
447 fprintf(stderr, "Could not configure tun interface: %s\n", strerror(errno));
451 ifr.ifr_name[IFNAMSIZ - 1] = 0;
452 fprintf(stderr, "Using tun interface %s\n", ifr.ifr_name);
458 static struct WSAData wsa_state;
460 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
466 struct addrinfo *ai, hint;
467 memset(&hint, 0, sizeof(hint));
469 hint.ai_family = addressfamily;
470 hint.ai_socktype = datagram ? SOCK_DGRAM : SOCK_STREAM;
471 hint.ai_protocol = datagram ? IPPROTO_UDP : IPPROTO_TCP;
472 hint.ai_flags = initiator ? 0 : AI_PASSIVE;
474 if(getaddrinfo(initiator ? argv[3] : NULL, initiator ? argv[4] : argv[3], &hint, &ai) || !ai) {
475 fprintf(stderr, "getaddrinfo() failed: %s\n", sockstrerror(sockerrno));
479 int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
482 fprintf(stderr, "Could not create socket: %s\n", sockstrerror(sockerrno));
488 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
491 int res = connect(sock, ai->ai_addr, ai->ai_addrlen);
497 fprintf(stderr, "Could not connect to peer: %s\n", sockstrerror(sockerrno));
501 fprintf(stderr, "Connected\n");
503 int res = bind(sock, ai->ai_addr, ai->ai_addrlen);
509 fprintf(stderr, "Could not bind socket: %s\n", sockstrerror(sockerrno));
514 if(listen(sock, 1)) {
515 fprintf(stderr, "Could not listen on socket: %s\n", sockstrerror(sockerrno));
519 print_listening_msg(sock);
521 sock = accept(sock, NULL, NULL);
524 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
528 print_listening_msg(sock);
531 struct sockaddr addr;
532 socklen_t addrlen = sizeof(addr);
534 if(recvfrom(sock, buf, sizeof(buf), MSG_PEEK, &addr, &addrlen) <= 0) {
535 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
539 if(connect(sock, &addr, addrlen)) {
540 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
545 fprintf(stderr, "Connected\n");
548 FILE *fp = fopen(argv[1], "r");
551 fprintf(stderr, "Could not open %s: %s\n", argv[1], strerror(errno));
555 ecdsa_t *mykey = NULL;
557 if(!(mykey = ecdsa_read_pem_private_key(fp))) {
563 fp = fopen(argv[2], "r");
566 fprintf(stderr, "Could not open %s: %s\n", argv[2], strerror(errno));
571 ecdsa_t *hiskey = NULL;
573 if(!(hiskey = ecdsa_read_pem_public_key(fp))) {
581 fprintf(stderr, "Keys loaded\n");
586 if(!sptps_start(&s, &sock, initiator, datagram, mykey, hiskey, "sptps_test", 10, send_data, receive_record)) {
595 in = start_input_reader();
598 fprintf(stderr, "Could not init stdin reader thread\n");
607 int max_fd = MAX(sock, in);
610 if(writeonly && readonly) {
614 char buf[65535] = "";
615 size_t readsize = datagram ? 1460u : sizeof(buf);
620 if(!readonly && s.instate) {
626 if(select(max_fd + 1, &fds, NULL, NULL, NULL) <= 0) {
632 if(FD_ISSET(in, &fds)) {
634 ssize_t len = recv(in, buf, readsize, 0);
636 ssize_t len = read(in, buf, readsize);
640 fprintf(stderr, "Could not read from stdin: %s\n", strerror(errno));
648 shutdown(in, SD_SEND);
660 if(special && buf[0] == '#') {
661 s.outseqno = atoi(buf + 1);
664 if(special && buf[0] == '^') {
665 sptps_send_record(&s, SPTPS_HANDSHAKE, NULL, 0);
666 } else if(special && buf[0] == '$') {
670 sptps_send_record(&s, 0, buf, len);
672 } else if(!sptps_send_record(&s, buf[0] == '!' ? 1 : 0, buf, (len == 1 && buf[0] == '\n') ? 0 : buf[0] == '*' ? sizeof(buf) : (size_t)len)) {
679 if(FD_ISSET(sock, &fds)) {
680 ssize_t len = recv(sock, buf, sizeof(buf), 0);
683 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
690 fprintf(stderr, "Connection terminated by peer.\n");
695 char *hex = alloca(len * 2 + 1);
696 bin2hex(buf, hex, len);
697 fprintf(stderr, "Received %ld bytes of data:\n%s\n", (long)len, hex);
700 if(packetloss && (int)prng(100) < packetloss) {
702 fprintf(stderr, "Dropped.\n");
711 size_t done = sptps_receive_data(&s, bufp, len);
722 len -= (ssize_t) done;
727 bool stopped = sptps_stop(&s);
736 int main(int argc, char *argv[]) {
741 int result = run_test(argc, argv);