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