Check all Address statements when making outgoing connections.
[tinc] / src / sptps_test.c
1 /*
2     sptps_test.c -- Simple Peer-to-Peer Security test program
3     Copyright (C) 2011-2014 Guus Sliepen <guus@tinc-vpn.org>
4
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.
9
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.
14
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.
18 */
19
20 #include "system.h"
21
22 #ifdef HAVE_LINUX
23 #include <linux/if_tun.h>
24 #endif
25
26 #include <getopt.h>
27
28 #include "crypto.h"
29 #include "ecdsa.h"
30 #include "sptps.h"
31 #include "utils.h"
32
33 // Symbols necessary to link with logger.o
34 bool send_request(void *c, const char *msg, ...) {
35         (void)c;
36         (void)msg;
37         return false;
38 }
39
40 struct list_t *connection_list = NULL;
41
42 bool send_meta(void *c, const char *msg, int len) {
43         (void)c;
44         (void)msg;
45         (void)len;
46         return false;
47 }
48
49 char *logfilename = NULL;
50 bool do_detach = false;
51 struct timeval now;
52
53 static bool special;
54 static bool verbose;
55 static bool readonly;
56 static bool writeonly;
57 static int in = 0;
58 static int out = 1;
59 static int addressfamily = AF_UNSPEC;
60
61 static bool send_data(void *handle, uint8_t type, const void *data, size_t len) {
62         (void)type;
63         char hex[len * 2 + 1];
64         bin2hex(data, hex, len);
65
66         if(verbose) {
67                 fprintf(stderr, "Sending %d bytes of data:\n%s\n", (int)len, hex);
68         }
69
70         const int *sock = handle;
71
72         if((size_t)send(*sock, data, len, 0) != len) {
73                 return false;
74         }
75
76         return true;
77 }
78
79 static bool receive_record(void *handle, uint8_t type, const void *data, uint16_t len) {
80         (void)handle;
81         if(verbose) {
82                 fprintf(stderr, "Received type %d record of %u bytes:\n", type, len);
83         }
84
85         if(!writeonly) {
86                 write(out, data, len);
87         }
88
89         return true;
90 }
91
92 static struct option const long_options[] = {
93         {"datagram", no_argument, NULL, 'd'},
94         {"quit", no_argument, NULL, 'q'},
95         {"readonly", no_argument, NULL, 'r'},
96         {"writeonly", no_argument, NULL, 'w'},
97         {"packet-loss", required_argument, NULL, 'L'},
98         {"replay-window", required_argument, NULL, 'W'},
99         {"special", no_argument, NULL, 's'},
100         {"verbose", required_argument, NULL, 'v'},
101         {"help", no_argument, NULL, 1},
102         {NULL, 0, NULL, 0}
103 };
104
105 const char *program_name;
106
107 static void usage() {
108         fprintf(stderr, "Usage: %s [options] my_ed25519_key_file his_ed25519_key_file [host] port\n\n", program_name);
109         fprintf(stderr, "Valid options are:\n"
110                 "  -d, --datagram          Enable datagram mode.\n"
111                 "  -q, --quit              Quit when EOF occurs on stdin.\n"
112                 "  -r, --readonly          Only send data from the socket to stdout.\n"
113 #ifdef HAVE_LINUX
114                 "  -t, --tun               Use a tun device instead of stdio.\n"
115 #endif
116                 "  -w, --writeonly         Only send data from stdin to the socket.\n"
117                 "  -L, --packet-loss RATE  Fake packet loss of RATE percent.\n"
118                 "  -R, --replay-window N   Set replay window to N bytes.\n"
119                 "  -s, --special           Enable special handling of lines starting with #, ^ and $.\n"
120                 "  -v, --verbose           Display debug messages.\n"
121                 "  -4                      Use IPv4.\n"
122                 "  -6                      Use IPv6.\n"
123                 "\n");
124         fprintf(stderr, "Report bugs to tinc@tinc-vpn.org.\n");
125 }
126
127 int main(int argc, char *argv[]) {
128         program_name = argv[0];
129         bool initiator = false;
130         bool datagram = false;
131 #ifdef HAVE_LINUX
132         bool tun = false;
133 #endif
134         int packetloss = 0;
135         int r;
136         int option_index = 0;
137         ecdsa_t *mykey = NULL, *hiskey = NULL;
138         bool quit = false;
139
140         while((r = getopt_long(argc, argv, "dqrstwL:W:v46", long_options, &option_index)) != EOF) {
141                 switch(r) {
142                 case 0:   /* long option */
143                         break;
144
145                 case 'd': /* datagram mode */
146                         datagram = true;
147                         break;
148
149                 case 'q': /* close connection on EOF from stdin */
150                         quit = true;
151                         break;
152
153                 case 'r': /* read only */
154                         readonly = true;
155                         break;
156
157                 case 't': /* read only */
158 #ifdef HAVE_LINUX
159                         tun = true;
160 #else
161                         fprintf(stderr, "--tun is only supported on Linux.\n");
162                         usage();
163                         return 1;
164 #endif
165                         break;
166
167                 case 'w': /* write only */
168                         writeonly = true;
169                         break;
170
171                 case 'L': /* packet loss rate */
172                         packetloss = atoi(optarg);
173                         break;
174
175                 case 'W': /* replay window size */
176                         sptps_replaywin = atoi(optarg);
177                         break;
178
179                 case 'v': /* be verbose */
180                         verbose = true;
181                         break;
182
183                 case 's': /* special character handling */
184                         special = true;
185                         break;
186
187                 case '?': /* wrong options */
188                         usage();
189                         return 1;
190
191                 case '4': /* IPv4 */
192                         addressfamily = AF_INET;
193                         break;
194
195                 case '6': /* IPv6 */
196                         addressfamily = AF_INET6;
197                         break;
198
199                 case 1: /* help */
200                         usage();
201                         return 0;
202
203                 default:
204                         break;
205                 }
206         }
207
208         argc -= optind - 1;
209         argv += optind - 1;
210
211         if(argc < 4 || argc > 5) {
212                 fprintf(stderr, "Wrong number of arguments.\n");
213                 usage();
214                 return 1;
215         }
216
217         if(argc > 4) {
218                 initiator = true;
219         }
220
221         srand(time(NULL));
222
223 #ifdef HAVE_LINUX
224
225         if(tun) {
226                 in = out = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
227
228                 if(in < 0) {
229                         fprintf(stderr, "Could not open tun device: %s\n", strerror(errno));
230                         return 1;
231                 }
232
233                 struct ifreq ifr = {
234                         .ifr_flags = IFF_TUN
235                 };
236
237                 if(ioctl(in, TUNSETIFF, &ifr)) {
238                         fprintf(stderr, "Could not configure tun interface: %s\n", strerror(errno));
239                         return 1;
240                 }
241
242                 ifr.ifr_name[IFNAMSIZ - 1] = 0;
243                 fprintf(stderr, "Using tun interface %s\n", ifr.ifr_name);
244         }
245
246 #endif
247
248 #ifdef HAVE_MINGW
249         static struct WSAData wsa_state;
250
251         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
252                 return 1;
253         }
254
255 #endif
256
257         struct addrinfo *ai, hint;
258         memset(&hint, 0, sizeof(hint));
259
260         hint.ai_family = addressfamily;
261         hint.ai_socktype = datagram ? SOCK_DGRAM : SOCK_STREAM;
262         hint.ai_protocol = datagram ? IPPROTO_UDP : IPPROTO_TCP;
263         hint.ai_flags = initiator ? 0 : AI_PASSIVE;
264
265         if(getaddrinfo(initiator ? argv[3] : NULL, initiator ? argv[4] : argv[3], &hint, &ai) || !ai) {
266                 fprintf(stderr, "getaddrinfo() failed: %s\n", sockstrerror(sockerrno));
267                 return 1;
268         }
269
270         int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
271
272         if(sock < 0) {
273                 fprintf(stderr, "Could not create socket: %s\n", sockstrerror(sockerrno));
274                 return 1;
275         }
276
277         int one = 1;
278         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
279
280         if(initiator) {
281                 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
282                         fprintf(stderr, "Could not connect to peer: %s\n", sockstrerror(sockerrno));
283                         return 1;
284                 }
285
286                 fprintf(stderr, "Connected\n");
287         } else {
288                 if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
289                         fprintf(stderr, "Could not bind socket: %s\n", sockstrerror(sockerrno));
290                         return 1;
291                 }
292
293                 if(!datagram) {
294                         if(listen(sock, 1)) {
295                                 fprintf(stderr, "Could not listen on socket: %s\n", sockstrerror(sockerrno));
296                                 return 1;
297                         }
298
299                         fprintf(stderr, "Listening...\n");
300
301                         sock = accept(sock, NULL, NULL);
302
303                         if(sock < 0) {
304                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
305                                 return 1;
306                         }
307                 } else {
308                         fprintf(stderr, "Listening...\n");
309
310                         char buf[65536];
311                         struct sockaddr addr;
312                         socklen_t addrlen = sizeof(addr);
313
314                         if(recvfrom(sock, buf, sizeof(buf), MSG_PEEK, &addr, &addrlen) <= 0) {
315                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
316                                 return 1;
317                         }
318
319                         if(connect(sock, &addr, addrlen)) {
320                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
321                                 return 1;
322                         }
323                 }
324
325                 fprintf(stderr, "Connected\n");
326         }
327
328         crypto_init();
329
330         FILE *fp = fopen(argv[1], "r");
331
332         if(!fp) {
333                 fprintf(stderr, "Could not open %s: %s\n", argv[1], strerror(errno));
334                 return 1;
335         }
336
337         if(!(mykey = ecdsa_read_pem_private_key(fp))) {
338                 return 1;
339         }
340
341         fclose(fp);
342
343         fp = fopen(argv[2], "r");
344
345         if(!fp) {
346                 fprintf(stderr, "Could not open %s: %s\n", argv[2], strerror(errno));
347                 return 1;
348         }
349
350         if(!(hiskey = ecdsa_read_pem_public_key(fp))) {
351                 return 1;
352         }
353
354         fclose(fp);
355
356         if(verbose) {
357                 fprintf(stderr, "Keys loaded\n");
358         }
359
360         sptps_t s;
361
362         if(!sptps_start(&s, &sock, initiator, datagram, mykey, hiskey, "sptps_test", 10, send_data, receive_record)) {
363                 return 1;
364         }
365
366         while(true) {
367                 if(writeonly && readonly) {
368                         break;
369                 }
370
371                 char buf[65535] = "";
372
373                 fd_set fds;
374                 FD_ZERO(&fds);
375 #ifndef HAVE_MINGW
376
377                 if(!readonly && s.instate) {
378                         FD_SET(in, &fds);
379                 }
380
381 #endif
382                 FD_SET(sock, &fds);
383
384                 if(select(sock + 1, &fds, NULL, NULL, NULL) <= 0) {
385                         return 1;
386                 }
387
388                 if(FD_ISSET(in, &fds)) {
389                         ssize_t len = read(in, buf, sizeof(buf));
390
391                         if(len < 0) {
392                                 fprintf(stderr, "Could not read from stdin: %s\n", strerror(errno));
393                                 return 1;
394                         }
395
396                         if(len == 0) {
397                                 if(quit) {
398                                         break;
399                                 }
400
401                                 readonly = true;
402                                 continue;
403                         }
404
405                         if(special && buf[0] == '#') {
406                                 s.outseqno = atoi(buf + 1);
407                         }
408
409                         if(special && buf[0] == '^') {
410                                 sptps_send_record(&s, SPTPS_HANDSHAKE, NULL, 0);
411                         } else if(special && buf[0] == '$') {
412                                 sptps_force_kex(&s);
413
414                                 if(len > 1) {
415                                         sptps_send_record(&s, 0, buf, len);
416                                 }
417                         } else if(!sptps_send_record(&s, buf[0] == '!' ? 1 : 0, buf, (len == 1 && buf[0] == '\n') ? 0 : buf[0] == '*' ? sizeof(buf) : (size_t)len)) {
418                                 return 1;
419                         }
420                 }
421
422                 if(FD_ISSET(sock, &fds)) {
423                         ssize_t len = recv(sock, buf, sizeof(buf), 0);
424
425                         if(len < 0) {
426                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
427                                 return 1;
428                         }
429
430                         if(len == 0) {
431                                 fprintf(stderr, "Connection terminated by peer.\n");
432                                 break;
433                         }
434
435                         if(verbose) {
436                                 char hex[len * 2 + 1];
437                                 bin2hex(buf, hex, len);
438                                 fprintf(stderr, "Received %d bytes of data:\n%s\n", (int)len, hex);
439                         }
440
441                         if(packetloss && (rand() % 100) < packetloss) {
442                                 if(verbose) {
443                                         fprintf(stderr, "Dropped.\n");
444                                 }
445
446                                 continue;
447                         }
448
449                         char *bufp = buf;
450
451                         while(len) {
452                                 size_t done = sptps_receive_data(&s, bufp, len);
453
454                                 if(!done) {
455                                         if(!datagram) {
456                                                 return 1;
457                                         }
458                                 }
459
460                                 bufp += done;
461                                 len -= done;
462                         }
463                 }
464         }
465
466         if(!sptps_stop(&s)) {
467                 return 1;
468         }
469
470         return 0;
471 }