99410900f729c7003b5c3dba3b33c25e32ba14f8
[BearSSL] / tools / sslio.c
1 /*
2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdint.h>
29 #include <errno.h>
30
31 #ifdef _WIN32
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 #else
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netdb.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <poll.h>
43
44 #define SOCKET int
45 #define INVALID_SOCKET (-1)
46 #endif
47
48 #include "brssl.h"
49
50 static void
51 dump_blob(const char *name, const void *data, size_t len)
52 {
53 const unsigned char *buf;
54 size_t u;
55
56 buf = data;
57 fprintf(stderr, "%s (len = %lu)", name, (unsigned long)len);
58 for (u = 0; u < len; u ++) {
59 if ((u & 15) == 0) {
60 fprintf(stderr, "\n%08lX ", (unsigned long)u);
61 } else if ((u & 7) == 0) {
62 fprintf(stderr, " ");
63 }
64 fprintf(stderr, " %02x", buf[u]);
65 }
66 fprintf(stderr, "\n");
67 }
68
69 /*
70 * Inspect the provided data in case it is a "command" to trigger a
71 * special behaviour. If the command is recognised, then it is executed
72 * and this function returns 1. Otherwise, this function returns 0.
73 */
74 static int
75 run_command(br_ssl_engine_context *cc, unsigned char *buf, size_t len)
76 {
77 /*
78 * A single static slot for saving session parameters.
79 */
80 static br_ssl_session_parameters slot;
81 static int slot_used = 0;
82
83 size_t u;
84
85 if (len < 2 || len > 3) {
86 return 0;
87 }
88 if (len == 3 && (buf[1] != '\r' || buf[2] != '\n')) {
89 return 0;
90 }
91 if (len == 2 && buf[1] != '\n') {
92 return 0;
93 }
94 switch (buf[0]) {
95 case 'Q':
96 fprintf(stderr, "closing...\n");
97 br_ssl_engine_close(cc);
98 return 1;
99 case 'R':
100 if (br_ssl_engine_renegotiate(cc)) {
101 fprintf(stderr, "renegotiating...\n");
102 } else {
103 fprintf(stderr, "not renegotiating.\n");
104 }
105 return 1;
106 case 'F':
107 /*
108 * Session forget is nominally client-only. But the
109 * session parameters are in the engine structure, which
110 * is the first field of the client context, so the cast
111 * still works properly. On the server, this forgetting
112 * has no effect.
113 */
114 fprintf(stderr, "forgetting session...\n");
115 br_ssl_client_forget_session((br_ssl_client_context *)cc);
116 return 1;
117 case 'S':
118 fprintf(stderr, "saving session parameters...\n");
119 br_ssl_engine_get_session_parameters(cc, &slot);
120 fprintf(stderr, " id = ");
121 for (u = 0; u < slot.session_id_len; u ++) {
122 fprintf(stderr, "%02X", slot.session_id[u]);
123 }
124 fprintf(stderr, "\n");
125 slot_used = 1;
126 return 1;
127 case 'P':
128 if (slot_used) {
129 fprintf(stderr, "restoring session parameters...\n");
130 fprintf(stderr, " id = ");
131 for (u = 0; u < slot.session_id_len; u ++) {
132 fprintf(stderr, "%02X", slot.session_id[u]);
133 }
134 fprintf(stderr, "\n");
135 br_ssl_engine_set_session_parameters(cc, &slot);
136 return 1;
137 }
138 return 0;
139 default:
140 return 0;
141 }
142 }
143
144 #ifdef _WIN32
145
146 typedef struct {
147 unsigned char buf[1024];
148 size_t ptr, len;
149 } in_buffer;
150
151 static int
152 in_return_bytes(in_buffer *bb, unsigned char *buf, size_t len)
153 {
154 if (bb->ptr < bb->len) {
155 size_t clen;
156
157 if (buf == NULL) {
158 return 1;
159 }
160 clen = bb->len - bb->ptr;
161 if (clen > len) {
162 clen = len;
163 }
164 memcpy(buf, bb->buf + bb->ptr, clen);
165 bb->ptr += clen;
166 if (bb->ptr == bb->len) {
167 bb->ptr = bb->len = 0;
168 }
169 return (int)clen;
170 }
171 return 0;
172 }
173
174 /*
175 * A buffered version of in_read(), using a buffer to return only
176 * full lines when feasible.
177 */
178 static int
179 in_read_buffered(HANDLE h_in, in_buffer *bb, unsigned char *buf, size_t len)
180 {
181 int n;
182
183 if (len == 0) {
184 return 0;
185 }
186 n = in_return_bytes(bb, buf, len);
187 if (n != 0) {
188 return n;
189 }
190 for (;;) {
191 INPUT_RECORD inrec;
192 DWORD v;
193
194 if (!PeekConsoleInput(h_in, &inrec, 1, &v)) {
195 fprintf(stderr, "ERROR: PeekConsoleInput()"
196 " failed with 0x%08lX\n",
197 (unsigned long)GetLastError());
198 return -1;
199 }
200 if (v == 0) {
201 return 0;
202 }
203 if (!ReadConsoleInput(h_in, &inrec, 1, &v)) {
204 fprintf(stderr, "ERROR: ReadConsoleInput()"
205 " failed with 0x%08lX\n",
206 (unsigned long)GetLastError());
207 return -1;
208 }
209 if (v == 0) {
210 return 0;
211 }
212 if (inrec.EventType == KEY_EVENT
213 && inrec.Event.KeyEvent.bKeyDown)
214 {
215 int c;
216
217 c = inrec.Event.KeyEvent.uChar.AsciiChar;
218 if (c == '\n' || c == '\r' || c == '\t'
219 || (c >= 32 && c != 127))
220 {
221 if (c == '\r') {
222 c = '\n';
223 }
224 bb->buf[bb->ptr ++] = (unsigned char)c;
225 printf("%c", c);
226 fflush(stdout);
227 bb->len = bb->ptr;
228 if (bb->len == sizeof bb->buf || c == '\n') {
229 bb->ptr = 0;
230 return in_return_bytes(bb, buf, len);
231 }
232 }
233 }
234 }
235 }
236
237 static int
238 in_avail_buffered(HANDLE h_in, in_buffer *bb)
239 {
240 return in_read_buffered(h_in, bb, NULL, 1);
241 }
242
243 #endif
244
245 /* see brssl.h */
246 int
247 run_ssl_engine(br_ssl_engine_context *cc, unsigned long fd, unsigned flags)
248 {
249 int hsdetails;
250 int retcode;
251 int verbose;
252 int trace;
253 #ifdef _WIN32
254 WSAEVENT fd_event;
255 int can_send, can_recv;
256 HANDLE h_in, h_out;
257 in_buffer bb;
258 #endif
259
260 hsdetails = 0;
261 retcode = 0;
262 verbose = (flags & RUN_ENGINE_VERBOSE) != 0;
263 trace = (flags & RUN_ENGINE_TRACE) != 0;
264
265 #ifdef _WIN32
266 fd_event = WSA_INVALID_EVENT;
267 can_send = 0;
268 can_recv = 0;
269 bb.ptr = bb.len = 0;
270 #endif
271
272 /*
273 * On Unix systems, we need to follow three descriptors:
274 * standard input (0), standard output (1), and the socket
275 * itself (for both read and write). This is done with a poll()
276 * call.
277 *
278 * On Windows systems, we use WSAEventSelect() to associate
279 * an event handle with the network activity, and we use
280 * WaitForMultipleObjectsEx() on that handle and the standard
281 * input handle, when appropriate. Standard output is assumed
282 * to be always writeable, and standard input to be the console;
283 * this does not work well (or at all) with redirections (to
284 * pipes or files) but it should be enough for a debug tool
285 * (TODO: make something that handles redirections as well).
286 */
287
288 #ifdef _WIN32
289 fd_event = WSACreateEvent();
290 if (fd_event == WSA_INVALID_EVENT) {
291 fprintf(stderr, "ERROR: WSACreateEvent() failed with %d\n",
292 WSAGetLastError());
293 retcode = -2;
294 goto engine_exit;
295 }
296 WSAEventSelect(fd, fd_event, FD_READ | FD_WRITE | FD_CLOSE);
297 h_in = GetStdHandle(STD_INPUT_HANDLE);
298 h_out = GetStdHandle(STD_OUTPUT_HANDLE);
299 SetConsoleMode(h_in, ENABLE_ECHO_INPUT
300 | ENABLE_LINE_INPUT
301 | ENABLE_PROCESSED_INPUT
302 | ENABLE_PROCESSED_OUTPUT
303 | ENABLE_WRAP_AT_EOL_OUTPUT);
304 #else
305 /*
306 * Make sure that stdin and stdout are non-blocking.
307 */
308 fcntl(0, F_SETFL, O_NONBLOCK);
309 fcntl(1, F_SETFL, O_NONBLOCK);
310 #endif
311
312 /*
313 * Perform the loop.
314 */
315 for (;;) {
316 unsigned st;
317 int sendrec, recvrec, sendapp, recvapp;
318 #ifdef _WIN32
319 HANDLE pfd[2];
320 DWORD wt;
321 #else
322 struct pollfd pfd[3];
323 int n;
324 #endif
325 size_t u, k_fd, k_in, k_out;
326 int sendrec_ok, recvrec_ok, sendapp_ok, recvapp_ok;
327
328 /*
329 * Get current engine state.
330 */
331 st = br_ssl_engine_current_state(cc);
332 if (st == BR_SSL_CLOSED) {
333 int err;
334
335 err = br_ssl_engine_last_error(cc);
336 if (err == BR_ERR_OK) {
337 if (verbose) {
338 fprintf(stderr,
339 "SSL closed normally\n");
340 }
341 retcode = 0;
342 goto engine_exit;
343 } else {
344 fprintf(stderr, "ERROR: SSL error %d", err);
345 retcode = err;
346 if (err >= BR_ERR_SEND_FATAL_ALERT) {
347 err -= BR_ERR_SEND_FATAL_ALERT;
348 fprintf(stderr,
349 " (sent alert %d)\n", err);
350 } else if (err >= BR_ERR_RECV_FATAL_ALERT) {
351 err -= BR_ERR_RECV_FATAL_ALERT;
352 fprintf(stderr,
353 " (received alert %d)\n", err);
354 } else {
355 const char *ename;
356
357 ename = find_error_name(err, NULL);
358 if (ename == NULL) {
359 ename = "unknown";
360 }
361 fprintf(stderr, " (%s)\n", ename);
362 }
363 goto engine_exit;
364 }
365 }
366
367 /*
368 * Compute descriptors that must be polled, depending
369 * on engine state.
370 */
371 sendrec = ((st & BR_SSL_SENDREC) != 0);
372 recvrec = ((st & BR_SSL_RECVREC) != 0);
373 sendapp = ((st & BR_SSL_SENDAPP) != 0);
374 recvapp = ((st & BR_SSL_RECVAPP) != 0);
375 if (verbose && sendapp && !hsdetails) {
376 char csn[80];
377 const char *pname;
378
379 fprintf(stderr, "Handshake completed\n");
380 fprintf(stderr, " version: ");
381 switch (cc->session.version) {
382 case BR_SSL30:
383 fprintf(stderr, "SSL 3.0");
384 break;
385 case BR_TLS10:
386 fprintf(stderr, "TLS 1.0");
387 break;
388 case BR_TLS11:
389 fprintf(stderr, "TLS 1.1");
390 break;
391 case BR_TLS12:
392 fprintf(stderr, "TLS 1.2");
393 break;
394 default:
395 fprintf(stderr, "unknown (0x%04X)",
396 (unsigned)cc->session.version);
397 break;
398 }
399 fprintf(stderr, "\n");
400 get_suite_name_ext(
401 cc->session.cipher_suite, csn, sizeof csn);
402 fprintf(stderr, " cipher suite: %s\n", csn);
403 if (uses_ecdhe(cc->session.cipher_suite)) {
404 get_curve_name_ext(
405 br_ssl_engine_get_ecdhe_curve(cc),
406 csn, sizeof csn);
407 fprintf(stderr,
408 " ECDHE curve: %s\n", csn);
409 }
410 fprintf(stderr, " secure renegotiation: %s\n",
411 cc->reneg == 1 ? "no" : "yes");
412 pname = br_ssl_engine_get_selected_protocol(cc);
413 if (pname != NULL) {
414 fprintf(stderr,
415 " protocol name (ALPN): %s\n",
416 pname);
417 }
418 hsdetails = 1;
419 }
420
421 k_fd = (size_t)-1;
422 k_in = (size_t)-1;
423 k_out = (size_t)-1;
424
425 u = 0;
426 #ifdef _WIN32
427 /*
428 * If we recorded that we can send or receive data, and we
429 * want to do exactly that, then we don't wait; we just do
430 * it.
431 */
432 recvapp_ok = 0;
433 sendrec_ok = 0;
434 recvrec_ok = 0;
435 sendapp_ok = 0;
436
437 if (sendrec && can_send) {
438 sendrec_ok = 1;
439 } else if (recvrec && can_recv) {
440 recvrec_ok = 1;
441 } else if (recvapp) {
442 recvapp_ok = 1;
443 } else if (sendapp && in_avail_buffered(h_in, &bb)) {
444 sendapp_ok = 1;
445 } else {
446 /*
447 * If we cannot do I/O right away, then we must
448 * wait for some event, and try again.
449 */
450 pfd[u] = (HANDLE)fd_event;
451 k_fd = u;
452 u ++;
453 if (sendapp) {
454 pfd[u] = h_in;
455 k_in = u;
456 u ++;
457 }
458 wt = WaitForMultipleObjectsEx(u, pfd,
459 FALSE, INFINITE, FALSE);
460 if (wt == WAIT_FAILED) {
461 fprintf(stderr, "ERROR:"
462 " WaitForMultipleObjectsEx()"
463 " failed with 0x%08lX",
464 (unsigned long)GetLastError());
465 retcode = -2;
466 goto engine_exit;
467 }
468 if (wt == k_fd) {
469 WSANETWORKEVENTS e;
470
471 if (WSAEnumNetworkEvents(fd, fd_event, &e)) {
472 fprintf(stderr, "ERROR:"
473 " WSAEnumNetworkEvents()"
474 " failed with %d\n",
475 WSAGetLastError());
476 retcode = -2;
477 goto engine_exit;
478 }
479 if (e.lNetworkEvents & (FD_WRITE | FD_CLOSE)) {
480 can_send = 1;
481 }
482 if (e.lNetworkEvents & (FD_READ | FD_CLOSE)) {
483 can_recv = 1;
484 }
485 }
486 continue;
487 }
488 #else
489 if (sendrec || recvrec) {
490 pfd[u].fd = fd;
491 pfd[u].revents = 0;
492 pfd[u].events = 0;
493 if (sendrec) {
494 pfd[u].events |= POLLOUT;
495 }
496 if (recvrec) {
497 pfd[u].events |= POLLIN;
498 }
499 k_fd = u;
500 u ++;
501 }
502 if (sendapp) {
503 pfd[u].fd = 0;
504 pfd[u].revents = 0;
505 pfd[u].events = POLLIN;
506 k_in = u;
507 u ++;
508 }
509 if (recvapp) {
510 pfd[u].fd = 1;
511 pfd[u].revents = 0;
512 pfd[u].events = POLLOUT;
513 k_out = u;
514 u ++;
515 }
516 n = poll(pfd, u, -1);
517 if (n < 0) {
518 if (errno == EINTR) {
519 continue;
520 }
521 perror("ERROR: poll()");
522 retcode = -2;
523 goto engine_exit;
524 }
525 if (n == 0) {
526 continue;
527 }
528
529 /*
530 * We transform closures/errors into read+write accesses
531 * so as to force the read() or write() call that will
532 * detect the situation.
533 */
534 while (u -- > 0) {
535 if (pfd[u].revents & (POLLERR | POLLHUP)) {
536 pfd[u].revents |= POLLIN | POLLOUT;
537 }
538 }
539
540 recvapp_ok = recvapp && (pfd[k_out].revents & POLLOUT) != 0;
541 sendrec_ok = sendrec && (pfd[k_fd].revents & POLLOUT) != 0;
542 recvrec_ok = recvrec && (pfd[k_fd].revents & POLLIN) != 0;
543 sendapp_ok = sendapp && (pfd[k_in].revents & POLLIN) != 0;
544 #endif
545
546 /*
547 * We give preference to outgoing data, on stdout and on
548 * the socket.
549 */
550 if (recvapp_ok) {
551 unsigned char *buf;
552 size_t len;
553 #ifdef _WIN32
554 DWORD wlen;
555 #else
556 ssize_t wlen;
557 #endif
558
559 buf = br_ssl_engine_recvapp_buf(cc, &len);
560 #ifdef _WIN32
561 if (!WriteFile(h_out, buf, len, &wlen, NULL)) {
562 if (verbose) {
563 fprintf(stderr, "stdout closed...\n");
564 }
565 retcode = -2;
566 goto engine_exit;
567 }
568 #else
569 wlen = write(1, buf, len);
570 if (wlen <= 0) {
571 if (verbose) {
572 fprintf(stderr, "stdout closed...\n");
573 }
574 retcode = -2;
575 goto engine_exit;
576 }
577 #endif
578 br_ssl_engine_recvapp_ack(cc, wlen);
579 continue;
580 }
581 if (sendrec_ok) {
582 unsigned char *buf;
583 size_t len;
584 int wlen;
585
586 buf = br_ssl_engine_sendrec_buf(cc, &len);
587 wlen = send(fd, buf, len, 0);
588 if (wlen <= 0) {
589 #ifdef _WIN32
590 int err;
591
592 err = WSAGetLastError();
593 if (err == EWOULDBLOCK
594 || err == WSAEWOULDBLOCK)
595 {
596 can_send = 0;
597 continue;
598 }
599 #else
600 if (errno == EINTR || errno == EWOULDBLOCK) {
601 continue;
602 }
603 #endif
604 if (verbose) {
605 fprintf(stderr, "socket closed...\n");
606 }
607 retcode = -1;
608 goto engine_exit;
609 }
610 if (trace) {
611 dump_blob("Outgoing bytes", buf, wlen);
612 }
613 br_ssl_engine_sendrec_ack(cc, wlen);
614 continue;
615 }
616 if (recvrec_ok) {
617 unsigned char *buf;
618 size_t len;
619 int rlen;
620
621 buf = br_ssl_engine_recvrec_buf(cc, &len);
622 rlen = recv(fd, buf, len, 0);
623 if (rlen <= 0) {
624 #ifdef _WIN32
625 int err;
626
627 err = WSAGetLastError();
628 if (err == EWOULDBLOCK
629 || err == WSAEWOULDBLOCK)
630 {
631 can_recv = 0;
632 continue;
633 }
634 #else
635 if (errno == EINTR || errno == EWOULDBLOCK) {
636 continue;
637 }
638 #endif
639 if (verbose) {
640 fprintf(stderr, "socket closed...\n");
641 }
642 retcode = -1;
643 goto engine_exit;
644 }
645 if (trace) {
646 dump_blob("Incoming bytes", buf, rlen);
647 }
648 br_ssl_engine_recvrec_ack(cc, rlen);
649 continue;
650 }
651 if (sendapp_ok) {
652 unsigned char *buf;
653 size_t len;
654 #ifdef _WIN32
655 int rlen;
656 #else
657 ssize_t rlen;
658 #endif
659
660 buf = br_ssl_engine_sendapp_buf(cc, &len);
661 #ifdef _WIN32
662 rlen = in_read_buffered(h_in, &bb, buf, len);
663 #else
664 rlen = read(0, buf, len);
665 #endif
666 if (rlen <= 0) {
667 if (verbose) {
668 fprintf(stderr, "stdin closed...\n");
669 }
670 br_ssl_engine_close(cc);
671 } else if (!run_command(cc, buf, rlen)) {
672 br_ssl_engine_sendapp_ack(cc, rlen);
673 }
674 br_ssl_engine_flush(cc, 0);
675 continue;
676 }
677
678 /* We should never reach that point. */
679 fprintf(stderr, "ERROR: poll() misbehaves\n");
680 retcode = -2;
681 goto engine_exit;
682 }
683
684 /*
685 * Release allocated structures.
686 */
687 engine_exit:
688 #ifdef _WIN32
689 if (fd_event != WSA_INVALID_EVENT) {
690 WSACloseEvent(fd_event);
691 }
692 #endif
693 return retcode;
694 }