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 // Suppress MSVC's STL warnings. It flags |std::copy| calls with a raw output
16 // pointer, on grounds that MSVC cannot check them. Unfortunately, there is no
17 // way to suppress the warning just on one line. The warning is flagged inside
18 // the STL itself, so suppressing at the |std::copy| call does not work.
19 #define _SCL_SECURE_NO_WARNINGS
20
21 #include <openssl/base.h>
22
23 #include <string>
24 #include <vector>
25
26 #include <errno.h>
27 #include <limits.h>
28 #include <stddef.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32
33 #if !defined(OPENSSL_WINDOWS)
34 #include <arpa/inet.h>
35 #include <fcntl.h>
36 #include <netdb.h>
37 #include <netinet/in.h>
38 #include <sys/select.h>
39 #include <sys/socket.h>
40 #include <unistd.h>
41 #else
42 #include <algorithm>
43 #include <condition_variable>
44 #include <deque>
45 #include <memory>
46 #include <mutex>
47 #include <thread>
48 #include <utility>
49
50 #include <io.h>
51 OPENSSL_MSVC_PRAGMA(warning(push, 3))
52 #include <winsock2.h>
53 #include <ws2tcpip.h>
54 OPENSSL_MSVC_PRAGMA(warning(pop))
55
56 typedef int ssize_t;
57 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
58 #endif
59
60 #include <openssl/err.h>
61 #include <openssl/ssl.h>
62 #include <openssl/x509.h>
63
64 #include "../crypto/internal.h"
65 #include "internal.h"
66 #include "transport_common.h"
67
68
69 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)70 static int closesocket(int sock) {
71 return close(sock);
72 }
73 #endif
74
InitSocketLibrary()75 bool InitSocketLibrary() {
76 #if defined(OPENSSL_WINDOWS)
77 WSADATA wsaData;
78 int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
79 if (err != 0) {
80 fprintf(stderr, "WSAStartup failed with error %d\n", err);
81 return false;
82 }
83 #endif
84 return true;
85 }
86
SplitHostPort(std::string * out_hostname,std::string * out_port,const std::string & hostname_and_port)87 static void SplitHostPort(std::string *out_hostname, std::string *out_port,
88 const std::string &hostname_and_port) {
89 size_t colon_offset = hostname_and_port.find_last_of(':');
90 const size_t bracket_offset = hostname_and_port.find_last_of(']');
91 std::string hostname, port;
92
93 // An IPv6 literal may have colons internally, guarded by square brackets.
94 if (bracket_offset != std::string::npos &&
95 colon_offset != std::string::npos && bracket_offset > colon_offset) {
96 colon_offset = std::string::npos;
97 }
98
99 if (colon_offset == std::string::npos) {
100 *out_hostname = hostname_and_port;
101 *out_port = "443";
102 } else {
103 *out_hostname = hostname_and_port.substr(0, colon_offset);
104 *out_port = hostname_and_port.substr(colon_offset + 1);
105 }
106 }
107
GetLastSocketErrorString()108 static std::string GetLastSocketErrorString() {
109 #if defined(OPENSSL_WINDOWS)
110 int error = WSAGetLastError();
111 char *buffer;
112 DWORD len = FormatMessageA(
113 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, error, 0,
114 reinterpret_cast<char *>(&buffer), 0, nullptr);
115 if (len == 0) {
116 char buf[256];
117 snprintf(buf, sizeof(buf), "unknown error (0x%x)", error);
118 return buf;
119 }
120 std::string ret(buffer, len);
121 LocalFree(buffer);
122 return ret;
123 #else
124 return strerror(errno);
125 #endif
126 }
127
PrintSocketError(const char * function)128 static void PrintSocketError(const char *function) {
129 // On Windows, |perror| and |errno| are part of the C runtime, while sockets
130 // are separate, so we must print errors manually.
131 std::string error = GetLastSocketErrorString();
132 fprintf(stderr, "%s: %s\n", function, error.c_str());
133 }
134
135 // Connect sets |*out_sock| to be a socket connected to the destination given
136 // in |hostname_and_port|, which should be of the form "www.example.com:123".
137 // It returns true on success and false otherwise.
Connect(int * out_sock,const std::string & hostname_and_port)138 bool Connect(int *out_sock, const std::string &hostname_and_port) {
139 std::string hostname, port;
140 SplitHostPort(&hostname, &port, hostname_and_port);
141
142 // Handle IPv6 literals.
143 if (hostname.size() >= 2 && hostname[0] == '[' &&
144 hostname[hostname.size() - 1] == ']') {
145 hostname = hostname.substr(1, hostname.size() - 2);
146 }
147
148 struct addrinfo hint, *result;
149 OPENSSL_memset(&hint, 0, sizeof(hint));
150 hint.ai_family = AF_UNSPEC;
151 hint.ai_socktype = SOCK_STREAM;
152
153 int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
154 if (ret != 0) {
155 fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
156 return false;
157 }
158
159 bool ok = false;
160 char buf[256];
161
162 *out_sock =
163 socket(result->ai_family, result->ai_socktype, result->ai_protocol);
164 if (*out_sock < 0) {
165 PrintSocketError("socket");
166 goto out;
167 }
168
169 switch (result->ai_family) {
170 case AF_INET: {
171 struct sockaddr_in *sin =
172 reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
173 fprintf(stderr, "Connecting to %s:%d\n",
174 inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
175 ntohs(sin->sin_port));
176 break;
177 }
178 case AF_INET6: {
179 struct sockaddr_in6 *sin6 =
180 reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
181 fprintf(stderr, "Connecting to [%s]:%d\n",
182 inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
183 ntohs(sin6->sin6_port));
184 break;
185 }
186 }
187
188 if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
189 PrintSocketError("connect");
190 goto out;
191 }
192 ok = true;
193
194 out:
195 freeaddrinfo(result);
196 return ok;
197 }
198
~Listener()199 Listener::~Listener() {
200 if (server_sock_ >= 0) {
201 closesocket(server_sock_);
202 }
203 }
204
Init(const std::string & port)205 bool Listener::Init(const std::string &port) {
206 if (server_sock_ >= 0) {
207 return false;
208 }
209
210 struct sockaddr_in6 addr;
211 OPENSSL_memset(&addr, 0, sizeof(addr));
212
213 addr.sin6_family = AF_INET6;
214 // Windows' IN6ADDR_ANY_INIT does not have enough curly braces for clang-cl
215 // (https://crbug.com/772108), while other platforms like NaCl are missing
216 // in6addr_any, so use a mix of both.
217 #if defined(OPENSSL_WINDOWS)
218 addr.sin6_addr = in6addr_any;
219 #else
220 addr.sin6_addr = IN6ADDR_ANY_INIT;
221 #endif
222 addr.sin6_port = htons(atoi(port.c_str()));
223
224 #if defined(OPENSSL_WINDOWS)
225 const BOOL enable = TRUE;
226 #else
227 const int enable = 1;
228 #endif
229
230 server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0);
231 if (server_sock_ < 0) {
232 PrintSocketError("socket");
233 return false;
234 }
235
236 if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
237 sizeof(enable)) < 0) {
238 PrintSocketError("setsockopt");
239 return false;
240 }
241
242 if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
243 PrintSocketError("connect");
244 return false;
245 }
246
247 listen(server_sock_, SOMAXCONN);
248 return true;
249 }
250
Accept(int * out_sock)251 bool Listener::Accept(int *out_sock) {
252 struct sockaddr_in6 addr;
253 socklen_t addr_len = sizeof(addr);
254 *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len);
255 return *out_sock >= 0;
256 }
257
VersionFromString(uint16_t * out_version,const std::string & version)258 bool VersionFromString(uint16_t *out_version, const std::string &version) {
259 if (version == "tls1" || version == "tls1.0") {
260 *out_version = TLS1_VERSION;
261 return true;
262 } else if (version == "tls1.1") {
263 *out_version = TLS1_1_VERSION;
264 return true;
265 } else if (version == "tls1.2") {
266 *out_version = TLS1_2_VERSION;
267 return true;
268 } else if (version == "tls1.3") {
269 *out_version = TLS1_3_VERSION;
270 return true;
271 }
272 return false;
273 }
274
PrintConnectionInfo(BIO * bio,const SSL * ssl)275 void PrintConnectionInfo(BIO *bio, const SSL *ssl) {
276 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
277
278 BIO_printf(bio, " Version: %s\n", SSL_get_version(ssl));
279 BIO_printf(bio, " Resumed session: %s\n",
280 SSL_session_reused(ssl) ? "yes" : "no");
281 BIO_printf(bio, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
282 uint16_t curve = SSL_get_curve_id(ssl);
283 if (curve != 0) {
284 BIO_printf(bio, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
285 }
286 uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
287 if (sigalg != 0) {
288 BIO_printf(bio, " Signature algorithm: %s\n",
289 SSL_get_signature_algorithm_name(
290 sigalg, SSL_version(ssl) != TLS1_2_VERSION));
291 }
292 BIO_printf(bio, " Secure renegotiation: %s\n",
293 SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
294 BIO_printf(bio, " Extended master secret: %s\n",
295 SSL_get_extms_support(ssl) ? "yes" : "no");
296
297 const uint8_t *next_proto;
298 unsigned next_proto_len;
299 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
300 BIO_printf(bio, " Next protocol negotiated: %.*s\n", next_proto_len,
301 next_proto);
302
303 const uint8_t *alpn;
304 unsigned alpn_len;
305 SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
306 BIO_printf(bio, " ALPN protocol: %.*s\n", alpn_len, alpn);
307
308 const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
309 if (host_name != nullptr && SSL_is_server(ssl)) {
310 BIO_printf(bio, " Client sent SNI: %s\n", host_name);
311 }
312
313 if (!SSL_is_server(ssl)) {
314 const uint8_t *ocsp_staple;
315 size_t ocsp_staple_len;
316 SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
317 BIO_printf(bio, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
318
319 const uint8_t *sct_list;
320 size_t sct_list_len;
321 SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
322 BIO_printf(bio, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
323 }
324
325 BIO_printf(
326 bio, " Early data: %s\n",
327 (SSL_early_data_accepted(ssl) || SSL_in_early_data(ssl)) ? "yes" : "no");
328
329 // Print the server cert subject and issuer names.
330 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
331 if (peer != nullptr) {
332 BIO_printf(bio, " Cert subject: ");
333 X509_NAME_print_ex(bio, X509_get_subject_name(peer.get()), 0,
334 XN_FLAG_ONELINE);
335 BIO_printf(bio, "\n Cert issuer: ");
336 X509_NAME_print_ex(bio, X509_get_issuer_name(peer.get()), 0,
337 XN_FLAG_ONELINE);
338 BIO_printf(bio, "\n");
339 }
340 }
341
SocketSetNonBlocking(int sock,bool is_non_blocking)342 bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
343 bool ok;
344
345 #if defined(OPENSSL_WINDOWS)
346 u_long arg = is_non_blocking;
347 ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
348 #else
349 int flags = fcntl(sock, F_GETFL, 0);
350 if (flags < 0) {
351 return false;
352 }
353 if (is_non_blocking) {
354 flags |= O_NONBLOCK;
355 } else {
356 flags &= ~O_NONBLOCK;
357 }
358 ok = 0 == fcntl(sock, F_SETFL, flags);
359 #endif
360 if (!ok) {
361 PrintSocketError("Failed to set socket non-blocking");
362 }
363 return ok;
364 }
365
366 enum class StdinWait {
367 kStdinRead,
368 kSocketWrite,
369 };
370
371 #if !defined(OPENSSL_WINDOWS)
372
373 // SocketWaiter abstracts waiting for either the socket or stdin to be readable
374 // between Windows and POSIX.
375 class SocketWaiter {
376 public:
SocketWaiter(int sock)377 explicit SocketWaiter(int sock) : sock_(sock) {}
378 SocketWaiter(const SocketWaiter &) = delete;
379 SocketWaiter &operator=(const SocketWaiter &) = delete;
380
381 // Init initializes the SocketWaiter. It returns whether it succeeded.
Init()382 bool Init() { return true; }
383
384 // Wait waits for at least on of the socket or stdin or be ready. On success,
385 // it sets |*socket_ready| and |*stdin_ready| to whether the respective
386 // objects are readable and returns true. On error, it returns false. stdin's
387 // readiness may either be the socket being writable or stdin being readable,
388 // depending on |stdin_wait|.
Wait(StdinWait stdin_wait,bool * socket_ready,bool * stdin_ready)389 bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
390 *socket_ready = true;
391 *stdin_ready = false;
392
393 fd_set read_fds, write_fds;
394 FD_ZERO(&read_fds);
395 FD_ZERO(&write_fds);
396 if (stdin_wait == StdinWait::kSocketWrite) {
397 FD_SET(sock_, &write_fds);
398 } else if (stdin_open_) {
399 FD_SET(STDIN_FILENO, &read_fds);
400 }
401 FD_SET(sock_, &read_fds);
402 if (select(sock_ + 1, &read_fds, &write_fds, NULL, NULL) <= 0) {
403 perror("select");
404 return false;
405 }
406
407 if (FD_ISSET(STDIN_FILENO, &read_fds) || FD_ISSET(sock_, &write_fds)) {
408 *stdin_ready = true;
409 }
410 if (FD_ISSET(sock_, &read_fds)) {
411 *socket_ready = true;
412 }
413
414 return true;
415 }
416
417 // ReadStdin reads at most |max_out| bytes from stdin. On success, it writes
418 // them to |out| and sets |*out_len| to the number of bytes written. On error,
419 // it returns false. This method may only be called after |Wait| returned
420 // stdin was ready.
ReadStdin(void * out,size_t * out_len,size_t max_out)421 bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
422 ssize_t n;
423 do {
424 n = read(STDIN_FILENO, out, max_out);
425 } while (n == -1 && errno == EINTR);
426 if (n <= 0) {
427 stdin_open_ = false;
428 }
429 if (n < 0) {
430 perror("read from stdin");
431 return false;
432 }
433 *out_len = static_cast<size_t>(n);
434 return true;
435 }
436
437 private:
438 bool stdin_open_ = true;
439 int sock_;
440 };
441
442 #else // OPENSSL_WINDOWs
443
444 class ScopedWSAEVENT {
445 public:
446 ScopedWSAEVENT() = default;
ScopedWSAEVENT(WSAEVENT event)447 ScopedWSAEVENT(WSAEVENT event) { reset(event); }
448 ScopedWSAEVENT(const ScopedWSAEVENT &) = delete;
ScopedWSAEVENT(ScopedWSAEVENT && other)449 ScopedWSAEVENT(ScopedWSAEVENT &&other) { *this = std::move(other); }
450
~ScopedWSAEVENT()451 ~ScopedWSAEVENT() { reset(); }
452
453 ScopedWSAEVENT &operator=(const ScopedWSAEVENT &) = delete;
operator =(ScopedWSAEVENT && other)454 ScopedWSAEVENT &operator=(ScopedWSAEVENT &&other) {
455 reset(other.release());
456 return *this;
457 }
458
operator bool() const459 explicit operator bool() const { return event_ != WSA_INVALID_EVENT; }
get() const460 WSAEVENT get() const { return event_; }
461
release()462 WSAEVENT release() {
463 WSAEVENT ret = event_;
464 event_ = WSA_INVALID_EVENT;
465 return ret;
466 }
467
reset(WSAEVENT event=WSA_INVALID_EVENT)468 void reset(WSAEVENT event = WSA_INVALID_EVENT) {
469 if (event_ != WSA_INVALID_EVENT) {
470 WSACloseEvent(event_);
471 }
472 event_ = event;
473 }
474
475 private:
476 WSAEVENT event_ = WSA_INVALID_EVENT;
477 };
478
479 // SocketWaiter, on Windows, is more complicated. While |WaitForMultipleObjects|
480 // works for both sockets and stdin, the latter is often a line-buffered
481 // console. The |HANDLE| is considered readable if there are any console events
482 // available, but reading blocks until a full line is available.
483 //
484 // So that |Wait| reflects final stdin read, we spawn a stdin reader thread that
485 // writes to an in-memory buffer and signals a |WSAEVENT| to coordinate with the
486 // socket.
487 class SocketWaiter {
488 public:
SocketWaiter(int sock)489 explicit SocketWaiter(int sock) : sock_(sock) {}
490 SocketWaiter(const SocketWaiter &) = delete;
491 SocketWaiter &operator=(const SocketWaiter &) = delete;
492
Init()493 bool Init() {
494 stdin_ = std::make_shared<StdinState>();
495 stdin_->event.reset(WSACreateEvent());
496 if (!stdin_->event) {
497 PrintSocketError("Error in WSACreateEvent");
498 return false;
499 }
500
501 // Spawn a thread to block on stdin.
502 std::shared_ptr<StdinState> state = stdin_;
503 std::thread thread([state]() {
504 for (;;) {
505 uint8_t buf[512];
506 int ret = _read(0 /* stdin */, buf, sizeof(buf));
507 if (ret <= 0) {
508 if (ret < 0) {
509 perror("read from stdin");
510 }
511 // Report the error or EOF to the caller.
512 std::lock_guard<std::mutex> lock(state->lock);
513 state->error = ret < 0;
514 state->open = false;
515 WSASetEvent(state->event.get());
516 return;
517 }
518
519 size_t len = static_cast<size_t>(ret);
520 size_t written = 0;
521 while (written < len) {
522 std::unique_lock<std::mutex> lock(state->lock);
523 // Wait for there to be room in the buffer.
524 state->cond.wait(lock, [&] { return !state->buffer_full(); });
525
526 // Copy what we can and signal to the caller.
527 size_t todo = std::min(len - written, state->buffer_remaining());
528 state->buffer.insert(state->buffer.end(), buf + written,
529 buf + written + todo);
530 written += todo;
531 WSASetEvent(state->event.get());
532 }
533 }
534 });
535 thread.detach();
536 return true;
537 }
538
Wait(StdinWait stdin_wait,bool * socket_ready,bool * stdin_ready)539 bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
540 *socket_ready = true;
541 *stdin_ready = false;
542
543 ScopedWSAEVENT sock_read_event(WSACreateEvent());
544 if (!sock_read_event ||
545 WSAEventSelect(sock_, sock_read_event.get(), FD_READ | FD_CLOSE) != 0) {
546 PrintSocketError("Error waiting for socket read");
547 return false;
548 }
549
550 DWORD count = 1;
551 WSAEVENT events[3] = {sock_read_event.get(), WSA_INVALID_EVENT};
552 ScopedWSAEVENT sock_write_event;
553 if (stdin_wait == StdinWait::kSocketWrite) {
554 sock_write_event.reset(WSACreateEvent());
555 if (!sock_write_event || WSAEventSelect(sock_, sock_write_event.get(),
556 FD_WRITE | FD_CLOSE) != 0) {
557 PrintSocketError("Error waiting for socket write");
558 return false;
559 }
560 events[1] = sock_write_event.get();
561 count++;
562 } else if (listen_stdin_) {
563 events[1] = stdin_->event.get();
564 count++;
565 }
566
567 switch (WSAWaitForMultipleEvents(count, events, FALSE /* wait all */,
568 WSA_INFINITE, FALSE /* alertable */)) {
569 case WSA_WAIT_EVENT_0 + 0:
570 *socket_ready = true;
571 return true;
572 case WSA_WAIT_EVENT_0 + 1:
573 *stdin_ready = true;
574 return true;
575 case WSA_WAIT_TIMEOUT:
576 return true;
577 default:
578 PrintSocketError("Error waiting for events");
579 return false;
580 }
581 }
582
ReadStdin(void * out,size_t * out_len,size_t max_out)583 bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
584 std::lock_guard<std::mutex> locked(stdin_->lock);
585
586 if (stdin_->buffer.empty()) {
587 // |ReadStdin| may only be called when |Wait| signals it is ready, so
588 // stdin must have reached EOF or error.
589 assert(!stdin_->open);
590 listen_stdin_ = false;
591 if (stdin_->error) {
592 return false;
593 }
594 *out_len = 0;
595 return true;
596 }
597
598 bool was_full = stdin_->buffer_full();
599 // Copy as many bytes as well fit.
600 *out_len = std::min(max_out, stdin_->buffer.size());
601 auto begin = stdin_->buffer.begin();
602 auto end = stdin_->buffer.begin() + *out_len;
603 std::copy(begin, end, static_cast<uint8_t *>(out));
604 stdin_->buffer.erase(begin, end);
605 // Notify the stdin thread if there is more space.
606 if (was_full && !stdin_->buffer_full()) {
607 stdin_->cond.notify_one();
608 }
609 // If stdin is now waiting for input, clear the event.
610 if (stdin_->buffer.empty() && stdin_->open) {
611 WSAResetEvent(stdin_->event.get());
612 }
613 return true;
614 }
615
616 private:
617 struct StdinState {
618 static constexpr size_t kMaxBuffer = 1024;
619
620 StdinState() = default;
621 StdinState(const StdinState &) = delete;
622 StdinState &operator=(const StdinState &) = delete;
623
buffer_remainingSocketWaiter::StdinState624 size_t buffer_remaining() const { return kMaxBuffer - buffer.size(); }
buffer_fullSocketWaiter::StdinState625 bool buffer_full() const { return buffer_remaining() == 0; }
626
627 ScopedWSAEVENT event;
628 // lock protects the following fields.
629 std::mutex lock;
630 // cond notifies the stdin thread that |buffer| is no longer full.
631 std::condition_variable cond;
632 std::deque<uint8_t> buffer;
633 bool open = true;
634 bool error = false;
635 };
636
637 int sock_;
638 std::shared_ptr<StdinState> stdin_;
639 // listen_stdin_ is set to false when we have consumed an EOF or error from
640 // |stdin_|. This is separate from |stdin_->open| because the signal may not
641 // have been consumed yet.
642 bool listen_stdin_ = true;
643 };
644
645 #endif // OPENSSL_WINDOWS
646
PrintSSLError(FILE * file,const char * msg,int ssl_err,int ret)647 void PrintSSLError(FILE *file, const char *msg, int ssl_err, int ret) {
648 switch (ssl_err) {
649 case SSL_ERROR_SSL:
650 fprintf(file, "%s: %s\n", msg, ERR_reason_error_string(ERR_peek_error()));
651 break;
652 case SSL_ERROR_SYSCALL:
653 if (ret == 0) {
654 fprintf(file, "%s: peer closed connection\n", msg);
655 } else {
656 std::string error = GetLastSocketErrorString();
657 fprintf(file, "%s: %s\n", msg, error.c_str());
658 }
659 break;
660 case SSL_ERROR_ZERO_RETURN:
661 fprintf(file, "%s: received close_notify\n", msg);
662 break;
663 default:
664 fprintf(file, "%s: unknown error type (%d)\n", msg, ssl_err);
665 }
666 ERR_print_errors_fp(file);
667 }
668
TransferData(SSL * ssl,int sock)669 bool TransferData(SSL *ssl, int sock) {
670 if (!SocketSetNonBlocking(sock, true)) {
671 return false;
672 }
673
674 SocketWaiter waiter(sock);
675 if (!waiter.Init()) {
676 return false;
677 }
678
679 uint8_t pending_write[512];
680 size_t pending_write_len = 0;
681 for (;;) {
682 bool socket_ready = false;
683 bool stdin_ready = false;
684 if (!waiter.Wait(pending_write_len == 0 ? StdinWait::kStdinRead
685 : StdinWait::kSocketWrite,
686 &socket_ready, &stdin_ready)) {
687 return false;
688 }
689
690 if (stdin_ready) {
691 if (pending_write_len == 0) {
692 if (!waiter.ReadStdin(pending_write, &pending_write_len,
693 sizeof(pending_write))) {
694 return false;
695 }
696 if (pending_write_len == 0) {
697 #if !defined(OPENSSL_WINDOWS)
698 shutdown(sock, SHUT_WR);
699 #else
700 shutdown(sock, SD_SEND);
701 #endif
702 continue;
703 }
704 }
705
706 int ssl_ret =
707 SSL_write(ssl, pending_write, static_cast<int>(pending_write_len));
708 if (ssl_ret <= 0) {
709 int ssl_err = SSL_get_error(ssl, ssl_ret);
710 if (ssl_err == SSL_ERROR_WANT_WRITE) {
711 continue;
712 }
713 PrintSSLError(stderr, "Error while writing", ssl_err, ssl_ret);
714 return false;
715 }
716 if (ssl_ret != static_cast<int>(pending_write_len)) {
717 fprintf(stderr, "Short write from SSL_write.\n");
718 return false;
719 }
720 pending_write_len = 0;
721 }
722
723 if (socket_ready) {
724 for (;;) {
725 uint8_t buffer[512];
726 int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
727
728 if (ssl_ret < 0) {
729 int ssl_err = SSL_get_error(ssl, ssl_ret);
730 if (ssl_err == SSL_ERROR_WANT_READ) {
731 break;
732 }
733 PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
734 return false;
735 } else if (ssl_ret == 0) {
736 return true;
737 }
738
739 ssize_t n;
740 do {
741 n = BORINGSSL_WRITE(1, buffer, ssl_ret);
742 } while (n == -1 && errno == EINTR);
743
744 if (n != ssl_ret) {
745 fprintf(stderr, "Short write to stderr.\n");
746 return false;
747 }
748 }
749 }
750 }
751 }
752
753 // SocketLineReader wraps a small buffer around a socket for line-orientated
754 // protocols.
755 class SocketLineReader {
756 public:
SocketLineReader(int sock)757 explicit SocketLineReader(int sock) : sock_(sock) {}
758
759 // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
760 // success, sets |*out_line| to it and returns true. Otherwise it returns
761 // false.
Next(std::string * out_line)762 bool Next(std::string *out_line) {
763 for (;;) {
764 for (size_t i = 0; i < buf_len_; i++) {
765 if (buf_[i] != '\n') {
766 continue;
767 }
768
769 size_t length = i;
770 if (i > 0 && buf_[i - 1] == '\r') {
771 length--;
772 }
773
774 out_line->assign(buf_, length);
775 buf_len_ -= i + 1;
776 OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
777
778 return true;
779 }
780
781 if (buf_len_ == sizeof(buf_)) {
782 fprintf(stderr, "Received line too long!\n");
783 return false;
784 }
785
786 ssize_t n;
787 do {
788 n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
789 } while (n == -1 && errno == EINTR);
790
791 if (n < 0) {
792 fprintf(stderr, "Read error from socket\n");
793 return false;
794 }
795
796 buf_len_ += n;
797 }
798 }
799
800 // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
801 // success, it sets |*out_code| to the reply's code (e.g. 250) and
802 // |*out_content| to the body of the reply (e.g. "OK") and returns true.
803 // Otherwise it returns false.
804 //
805 // See https://tools.ietf.org/html/rfc821#page-48
ReadSMTPReply(unsigned * out_code,std::string * out_content)806 bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
807 out_content->clear();
808
809 // kMaxLines is the maximum number of lines that we'll accept in an SMTP
810 // reply.
811 static const unsigned kMaxLines = 512;
812 for (unsigned i = 0; i < kMaxLines; i++) {
813 std::string line;
814 if (!Next(&line)) {
815 return false;
816 }
817
818 if (line.size() < 4) {
819 fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
820 return false;
821 }
822
823 const std::string code_str = line.substr(0, 3);
824 char *endptr;
825 const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
826 if (*endptr || code > UINT_MAX) {
827 fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
828 return false;
829 }
830
831 if (i == 0) {
832 *out_code = code;
833 } else if (code != *out_code) {
834 fprintf(stderr,
835 "Reply code varied within a single reply: was %u, now %u\n",
836 *out_code, static_cast<unsigned>(code));
837 return false;
838 }
839
840 if (line[3] == ' ') {
841 // End of reply.
842 *out_content += line.substr(4, std::string::npos);
843 return true;
844 } else if (line[3] == '-') {
845 // Another line of reply will follow this one.
846 *out_content += line.substr(4, std::string::npos);
847 out_content->push_back('\n');
848 } else {
849 fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
850 line.c_str());
851 return false;
852 }
853 }
854
855 fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
856 return false;
857 }
858
859 private:
860 const int sock_;
861 char buf_[512];
862 size_t buf_len_ = 0;
863 };
864
865 // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
866 // success and false otherwise.
SendAll(int sock,const char * data,size_t data_len)867 static bool SendAll(int sock, const char *data, size_t data_len) {
868 size_t done = 0;
869
870 while (done < data_len) {
871 ssize_t n;
872 do {
873 n = send(sock, &data[done], data_len - done, 0);
874 } while (n == -1 && errno == EINTR);
875
876 if (n < 0) {
877 fprintf(stderr, "Error while writing to socket\n");
878 return false;
879 }
880
881 done += n;
882 }
883
884 return true;
885 }
886
DoSMTPStartTLS(int sock)887 bool DoSMTPStartTLS(int sock) {
888 SocketLineReader line_reader(sock);
889
890 unsigned code_220 = 0;
891 std::string reply_220;
892 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
893 return false;
894 }
895
896 if (code_220 != 220) {
897 fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
898 code_220);
899 return false;
900 }
901
902 static const char kHelloLine[] = "EHLO BoringSSL\r\n";
903 if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
904 return false;
905 }
906
907 unsigned code_250 = 0;
908 std::string reply_250;
909 if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
910 return false;
911 }
912
913 if (code_250 != 250) {
914 fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
915 return false;
916 }
917
918 // https://tools.ietf.org/html/rfc1869#section-4.3
919 if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
920 fprintf(stderr, "Server does not support STARTTLS\n");
921 return false;
922 }
923
924 static const char kSTARTTLSLine[] = "STARTTLS\r\n";
925 if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
926 return false;
927 }
928
929 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
930 return false;
931 }
932
933 if (code_220 != 220) {
934 fprintf(
935 stderr,
936 "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
937 code_220);
938 return false;
939 }
940
941 return true;
942 }
943
DoHTTPTunnel(int sock,const std::string & hostname_and_port)944 bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) {
945 std::string hostname, port;
946 SplitHostPort(&hostname, &port, hostname_and_port);
947
948 fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(),
949 port.c_str());
950 char buf[1024];
951 snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(),
952 port.c_str());
953 if (!SendAll(sock, buf, strlen(buf))) {
954 return false;
955 }
956
957 SocketLineReader line_reader(sock);
958
959 // Read until an empty line, signaling the end of the HTTP response.
960 std::string line;
961 for (;;) {
962 if (!line_reader.Next(&line)) {
963 return false;
964 }
965 if (line.empty()) {
966 return true;
967 }
968 fprintf(stderr, "%s\n", line.c_str());
969 }
970 }
971