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