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