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