1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/base.h>
16
17 #include <string>
18 #include <vector>
19
20 #include <errno.h>
21 #include <limits.h>
22 #include <stddef.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26
27 #if !defined(OPENSSL_WINDOWS)
28 #include <arpa/inet.h>
29 #include <fcntl.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <sys/select.h>
33 #include <sys/socket.h>
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 OPENSSL_MSVC_PRAGMA(warning(push, 3))
38 #include <winsock2.h>
39 #include <ws2tcpip.h>
40 OPENSSL_MSVC_PRAGMA(warning(pop))
41
42 typedef int ssize_t;
43 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
44 #endif
45
46 #include <openssl/err.h>
47 #include <openssl/ssl.h>
48 #include <openssl/x509.h>
49
50 #include "../crypto/internal.h"
51 #include "internal.h"
52 #include "transport_common.h"
53
54
55 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)56 static int closesocket(int sock) {
57 return close(sock);
58 }
59 #endif
60
InitSocketLibrary()61 bool InitSocketLibrary() {
62 #if defined(OPENSSL_WINDOWS)
63 WSADATA wsaData;
64 int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
65 if (err != 0) {
66 fprintf(stderr, "WSAStartup failed with error %d\n", err);
67 return false;
68 }
69 #endif
70 return true;
71 }
72
SplitHostPort(std::string * out_hostname,std::string * out_port,const std::string & hostname_and_port)73 static void SplitHostPort(std::string *out_hostname, std::string *out_port,
74 const std::string &hostname_and_port) {
75 size_t colon_offset = hostname_and_port.find_last_of(':');
76 const size_t bracket_offset = hostname_and_port.find_last_of(']');
77 std::string hostname, port;
78
79 // An IPv6 literal may have colons internally, guarded by square brackets.
80 if (bracket_offset != std::string::npos &&
81 colon_offset != std::string::npos && bracket_offset > colon_offset) {
82 colon_offset = std::string::npos;
83 }
84
85 if (colon_offset == std::string::npos) {
86 *out_hostname = hostname_and_port;
87 *out_port = "443";
88 } else {
89 *out_hostname = hostname_and_port.substr(0, colon_offset);
90 *out_port = hostname_and_port.substr(colon_offset + 1);
91 }
92 }
93
94 // Connect sets |*out_sock| to be a socket connected to the destination given
95 // in |hostname_and_port|, which should be of the form "www.example.com:123".
96 // It returns true on success and false otherwise.
Connect(int * out_sock,const std::string & hostname_and_port)97 bool Connect(int *out_sock, const std::string &hostname_and_port) {
98 std::string hostname, port;
99 SplitHostPort(&hostname, &port, hostname_and_port);
100
101 // Handle IPv6 literals.
102 if (hostname.size() >= 2 && hostname[0] == '[' &&
103 hostname[hostname.size() - 1] == ']') {
104 hostname = hostname.substr(1, hostname.size() - 2);
105 }
106
107 struct addrinfo hint, *result;
108 OPENSSL_memset(&hint, 0, sizeof(hint));
109 hint.ai_family = AF_UNSPEC;
110 hint.ai_socktype = SOCK_STREAM;
111
112 int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
113 if (ret != 0) {
114 fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
115 return false;
116 }
117
118 bool ok = false;
119 char buf[256];
120
121 *out_sock =
122 socket(result->ai_family, result->ai_socktype, result->ai_protocol);
123 if (*out_sock < 0) {
124 perror("socket");
125 goto out;
126 }
127
128 switch (result->ai_family) {
129 case AF_INET: {
130 struct sockaddr_in *sin =
131 reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
132 fprintf(stderr, "Connecting to %s:%d\n",
133 inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
134 ntohs(sin->sin_port));
135 break;
136 }
137 case AF_INET6: {
138 struct sockaddr_in6 *sin6 =
139 reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
140 fprintf(stderr, "Connecting to [%s]:%d\n",
141 inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
142 ntohs(sin6->sin6_port));
143 break;
144 }
145 }
146
147 if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
148 perror("connect");
149 goto out;
150 }
151 ok = true;
152
153 out:
154 freeaddrinfo(result);
155 return ok;
156 }
157
~Listener()158 Listener::~Listener() {
159 if (server_sock_ >= 0) {
160 closesocket(server_sock_);
161 }
162 }
163
Init(const std::string & port)164 bool Listener::Init(const std::string &port) {
165 if (server_sock_ >= 0) {
166 return false;
167 }
168
169 struct sockaddr_in6 addr;
170 OPENSSL_memset(&addr, 0, sizeof(addr));
171
172 addr.sin6_family = AF_INET6;
173 addr.sin6_addr = IN6ADDR_ANY_INIT;
174 addr.sin6_port = htons(atoi(port.c_str()));
175
176 #if defined(OPENSSL_WINDOWS)
177 const BOOL enable = TRUE;
178 #else
179 const int enable = 1;
180 #endif
181
182 server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0);
183 if (server_sock_ < 0) {
184 perror("socket");
185 return false;
186 }
187
188 if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
189 sizeof(enable)) < 0) {
190 perror("setsockopt");
191 return false;
192 }
193
194 if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
195 perror("connect");
196 return false;
197 }
198
199 listen(server_sock_, SOMAXCONN);
200 return true;
201 }
202
Accept(int * out_sock)203 bool Listener::Accept(int *out_sock) {
204 struct sockaddr_in6 addr;
205 socklen_t addr_len = sizeof(addr);
206 *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len);
207 return *out_sock >= 0;
208 }
209
VersionFromString(uint16_t * out_version,const std::string & version)210 bool VersionFromString(uint16_t *out_version, const std::string &version) {
211 if (version == "ssl3") {
212 *out_version = SSL3_VERSION;
213 return true;
214 } else if (version == "tls1" || version == "tls1.0") {
215 *out_version = TLS1_VERSION;
216 return true;
217 } else if (version == "tls1.1") {
218 *out_version = TLS1_1_VERSION;
219 return true;
220 } else if (version == "tls1.2") {
221 *out_version = TLS1_2_VERSION;
222 return true;
223 } else if (version == "tls1.3") {
224 *out_version = TLS1_3_VERSION;
225 return true;
226 }
227 return false;
228 }
229
SignatureAlgorithmToString(uint16_t version,uint16_t sigalg)230 static const char *SignatureAlgorithmToString(uint16_t version, uint16_t sigalg) {
231 const bool is_tls12 = version == TLS1_2_VERSION || version == DTLS1_2_VERSION;
232 switch (sigalg) {
233 case SSL_SIGN_RSA_PKCS1_SHA1:
234 return "rsa_pkcs1_sha1";
235 case SSL_SIGN_RSA_PKCS1_SHA256:
236 return "rsa_pkcs1_sha256";
237 case SSL_SIGN_RSA_PKCS1_SHA384:
238 return "rsa_pkcs1_sha384";
239 case SSL_SIGN_RSA_PKCS1_SHA512:
240 return "rsa_pkcs1_sha512";
241 case SSL_SIGN_ECDSA_SHA1:
242 return "ecdsa_sha1";
243 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
244 return is_tls12 ? "ecdsa_sha256" : "ecdsa_secp256r1_sha256";
245 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
246 return is_tls12 ? "ecdsa_sha384" : "ecdsa_secp384r1_sha384";
247 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
248 return is_tls12 ? "ecdsa_sha512" : "ecdsa_secp521r1_sha512";
249 case SSL_SIGN_RSA_PSS_SHA256:
250 return "rsa_pss_sha256";
251 case SSL_SIGN_RSA_PSS_SHA384:
252 return "rsa_pss_sha384";
253 case SSL_SIGN_RSA_PSS_SHA512:
254 return "rsa_pss_sha512";
255 case SSL_SIGN_ED25519:
256 return "ed25519";
257 default:
258 return "(unknown)";
259 }
260 }
261
PrintConnectionInfo(const SSL * ssl)262 void PrintConnectionInfo(const SSL *ssl) {
263 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
264
265 fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
266 fprintf(stderr, " Resumed session: %s\n",
267 SSL_session_reused(ssl) ? "yes" : "no");
268 fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
269 uint16_t curve = SSL_get_curve_id(ssl);
270 if (curve != 0) {
271 fprintf(stderr, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
272 }
273 uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
274 if (sigalg != 0) {
275 fprintf(stderr, " Signature algorithm: %s\n",
276 SignatureAlgorithmToString(SSL_version(ssl), sigalg));
277 }
278 fprintf(stderr, " Secure renegotiation: %s\n",
279 SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
280 fprintf(stderr, " Extended master secret: %s\n",
281 SSL_get_extms_support(ssl) ? "yes" : "no");
282
283 const uint8_t *next_proto;
284 unsigned next_proto_len;
285 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
286 fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
287 next_proto);
288
289 const uint8_t *alpn;
290 unsigned alpn_len;
291 SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
292 fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
293
294 const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
295 if (host_name != nullptr && SSL_is_server(ssl)) {
296 fprintf(stderr, " Client sent SNI: %s\n", host_name);
297 }
298
299 if (!SSL_is_server(ssl)) {
300 const uint8_t *ocsp_staple;
301 size_t ocsp_staple_len;
302 SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
303 fprintf(stderr, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
304
305 const uint8_t *sct_list;
306 size_t sct_list_len;
307 SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
308 fprintf(stderr, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
309 }
310
311 fprintf(stderr, " Early data: %s\n",
312 SSL_early_data_accepted(ssl) ? "yes" : "no");
313
314 // Print the server cert subject and issuer names.
315 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
316 if (peer != nullptr) {
317 fprintf(stderr, " Cert subject: ");
318 X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer.get()), 0,
319 XN_FLAG_ONELINE);
320 fprintf(stderr, "\n Cert issuer: ");
321 X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer.get()), 0,
322 XN_FLAG_ONELINE);
323 fprintf(stderr, "\n");
324 }
325 }
326
SocketSetNonBlocking(int sock,bool is_non_blocking)327 bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
328 bool ok;
329
330 #if defined(OPENSSL_WINDOWS)
331 u_long arg = is_non_blocking;
332 ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
333 #else
334 int flags = fcntl(sock, F_GETFL, 0);
335 if (flags < 0) {
336 return false;
337 }
338 if (is_non_blocking) {
339 flags |= O_NONBLOCK;
340 } else {
341 flags &= ~O_NONBLOCK;
342 }
343 ok = 0 == fcntl(sock, F_SETFL, flags);
344 #endif
345 if (!ok) {
346 fprintf(stderr, "Failed to set socket non-blocking.\n");
347 }
348 return ok;
349 }
350
351 // PrintErrorCallback is a callback function from OpenSSL's
352 // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
PrintErrorCallback(const char * str,size_t len,void * ctx)353 int PrintErrorCallback(const char *str, size_t len, void *ctx) {
354 fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
355 return 1;
356 }
357
TransferData(SSL * ssl,int sock)358 bool TransferData(SSL *ssl, int sock) {
359 bool stdin_open = true;
360
361 fd_set read_fds;
362 FD_ZERO(&read_fds);
363
364 if (!SocketSetNonBlocking(sock, true)) {
365 return false;
366 }
367
368 for (;;) {
369 if (stdin_open) {
370 FD_SET(0, &read_fds);
371 }
372 FD_SET(sock, &read_fds);
373
374 int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
375 if (ret <= 0) {
376 perror("select");
377 return false;
378 }
379
380 if (FD_ISSET(0, &read_fds)) {
381 uint8_t buffer[512];
382 ssize_t n;
383
384 do {
385 n = BORINGSSL_READ(0, buffer, sizeof(buffer));
386 } while (n == -1 && errno == EINTR);
387
388 if (n == 0) {
389 FD_CLR(0, &read_fds);
390 stdin_open = false;
391 #if !defined(OPENSSL_WINDOWS)
392 shutdown(sock, SHUT_WR);
393 #else
394 shutdown(sock, SD_SEND);
395 #endif
396 continue;
397 } else if (n < 0) {
398 perror("read from stdin");
399 return false;
400 }
401
402 if (!SocketSetNonBlocking(sock, false)) {
403 return false;
404 }
405 int ssl_ret = SSL_write(ssl, buffer, n);
406 if (!SocketSetNonBlocking(sock, true)) {
407 return false;
408 }
409
410 if (ssl_ret <= 0) {
411 int ssl_err = SSL_get_error(ssl, ssl_ret);
412 fprintf(stderr, "Error while writing: %d\n", ssl_err);
413 ERR_print_errors_cb(PrintErrorCallback, stderr);
414 return false;
415 } else if (ssl_ret != n) {
416 fprintf(stderr, "Short write from SSL_write.\n");
417 return false;
418 }
419 }
420
421 if (FD_ISSET(sock, &read_fds)) {
422 uint8_t buffer[512];
423 int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
424
425 if (ssl_ret < 0) {
426 int ssl_err = SSL_get_error(ssl, ssl_ret);
427 if (ssl_err == SSL_ERROR_WANT_READ) {
428 continue;
429 }
430 fprintf(stderr, "Error while reading: %d\n", ssl_err);
431 ERR_print_errors_cb(PrintErrorCallback, stderr);
432 return false;
433 } else if (ssl_ret == 0) {
434 return true;
435 }
436
437 ssize_t n;
438 do {
439 n = BORINGSSL_WRITE(1, buffer, ssl_ret);
440 } while (n == -1 && errno == EINTR);
441
442 if (n != ssl_ret) {
443 fprintf(stderr, "Short write to stderr.\n");
444 return false;
445 }
446 }
447 }
448 }
449
450 // SocketLineReader wraps a small buffer around a socket for line-orientated
451 // protocols.
452 class SocketLineReader {
453 public:
SocketLineReader(int sock)454 explicit SocketLineReader(int sock) : sock_(sock) {}
455
456 // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
457 // success, sets |*out_line| to it and returns true. Otherwise it returns
458 // false.
Next(std::string * out_line)459 bool Next(std::string *out_line) {
460 for (;;) {
461 for (size_t i = 0; i < buf_len_; i++) {
462 if (buf_[i] != '\n') {
463 continue;
464 }
465
466 size_t length = i;
467 if (i > 0 && buf_[i - 1] == '\r') {
468 length--;
469 }
470
471 out_line->assign(buf_, length);
472 buf_len_ -= i + 1;
473 OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
474
475 return true;
476 }
477
478 if (buf_len_ == sizeof(buf_)) {
479 fprintf(stderr, "Received line too long!\n");
480 return false;
481 }
482
483 ssize_t n;
484 do {
485 n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
486 } while (n == -1 && errno == EINTR);
487
488 if (n < 0) {
489 fprintf(stderr, "Read error from socket\n");
490 return false;
491 }
492
493 buf_len_ += n;
494 }
495 }
496
497 // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
498 // success, it sets |*out_code| to the reply's code (e.g. 250) and
499 // |*out_content| to the body of the reply (e.g. "OK") and returns true.
500 // Otherwise it returns false.
501 //
502 // See https://tools.ietf.org/html/rfc821#page-48
ReadSMTPReply(unsigned * out_code,std::string * out_content)503 bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
504 out_content->clear();
505
506 // kMaxLines is the maximum number of lines that we'll accept in an SMTP
507 // reply.
508 static const unsigned kMaxLines = 512;
509 for (unsigned i = 0; i < kMaxLines; i++) {
510 std::string line;
511 if (!Next(&line)) {
512 return false;
513 }
514
515 if (line.size() < 4) {
516 fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
517 return false;
518 }
519
520 const std::string code_str = line.substr(0, 3);
521 char *endptr;
522 const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
523 if (*endptr || code > UINT_MAX) {
524 fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
525 return false;
526 }
527
528 if (i == 0) {
529 *out_code = code;
530 } else if (code != *out_code) {
531 fprintf(stderr,
532 "Reply code varied within a single reply: was %u, now %u\n",
533 *out_code, static_cast<unsigned>(code));
534 return false;
535 }
536
537 if (line[3] == ' ') {
538 // End of reply.
539 *out_content += line.substr(4, std::string::npos);
540 return true;
541 } else if (line[3] == '-') {
542 // Another line of reply will follow this one.
543 *out_content += line.substr(4, std::string::npos);
544 out_content->push_back('\n');
545 } else {
546 fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
547 line.c_str());
548 return false;
549 }
550 }
551
552 fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
553 return false;
554 }
555
556 private:
557 const int sock_;
558 char buf_[512];
559 size_t buf_len_ = 0;
560 };
561
562 // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
563 // success and false otherwise.
SendAll(int sock,const char * data,size_t data_len)564 static bool SendAll(int sock, const char *data, size_t data_len) {
565 size_t done = 0;
566
567 while (done < data_len) {
568 ssize_t n;
569 do {
570 n = send(sock, &data[done], data_len - done, 0);
571 } while (n == -1 && errno == EINTR);
572
573 if (n < 0) {
574 fprintf(stderr, "Error while writing to socket\n");
575 return false;
576 }
577
578 done += n;
579 }
580
581 return true;
582 }
583
DoSMTPStartTLS(int sock)584 bool DoSMTPStartTLS(int sock) {
585 SocketLineReader line_reader(sock);
586
587 unsigned code_220 = 0;
588 std::string reply_220;
589 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
590 return false;
591 }
592
593 if (code_220 != 220) {
594 fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
595 code_220);
596 return false;
597 }
598
599 static const char kHelloLine[] = "EHLO BoringSSL\r\n";
600 if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
601 return false;
602 }
603
604 unsigned code_250 = 0;
605 std::string reply_250;
606 if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
607 return false;
608 }
609
610 if (code_250 != 250) {
611 fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
612 return false;
613 }
614
615 // https://tools.ietf.org/html/rfc1869#section-4.3
616 if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
617 fprintf(stderr, "Server does not support STARTTLS\n");
618 return false;
619 }
620
621 static const char kSTARTTLSLine[] = "STARTTLS\r\n";
622 if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
623 return false;
624 }
625
626 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
627 return false;
628 }
629
630 if (code_220 != 220) {
631 fprintf(
632 stderr,
633 "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
634 code_220);
635 return false;
636 }
637
638 return true;
639 }
640
DoHTTPTunnel(int sock,const std::string & hostname_and_port)641 bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) {
642 std::string hostname, port;
643 SplitHostPort(&hostname, &port, hostname_and_port);
644
645 fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(),
646 port.c_str());
647 char buf[1024];
648 snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(),
649 port.c_str());
650 if (!SendAll(sock, buf, strlen(buf))) {
651 return false;
652 }
653
654 SocketLineReader line_reader(sock);
655
656 // Read until an empty line, signaling the end of the HTTP response.
657 std::string line;
658 for (;;) {
659 if (!line_reader.Next(&line)) {
660 return false;
661 }
662 if (line.empty()) {
663 return true;
664 }
665 fprintf(stderr, "%s\n", line.c_str());
666 }
667 }
668