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