xref: /aosp_15_r20/external/boringssl/src/ssl/test/handshaker.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (c) 2018, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <assert.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <unistd.h>
20 
21 #include <memory>
22 
23 #include <openssl/bytestring.h>
24 #include <openssl/rand.h>
25 #include <openssl/ssl.h>
26 
27 #include "handshake_util.h"
28 #include "test_config.h"
29 #include "test_state.h"
30 
31 using namespace bssl;
32 
33 namespace {
34 
read_eintr(int fd,void * out,size_t len)35 ssize_t read_eintr(int fd, void *out, size_t len) {
36   ssize_t ret;
37   do {
38     ret = read(fd, out, len);
39   } while (ret < 0 && errno == EINTR);
40   return ret;
41 }
42 
write_eintr(int fd,const void * in,size_t len)43 ssize_t write_eintr(int fd, const void *in, size_t len) {
44   ssize_t ret;
45   do {
46     ret = write(fd, in, len);
47   } while (ret < 0 && errno == EINTR);
48   return ret;
49 }
50 
HandbackReady(SSL * ssl,int ret)51 bool HandbackReady(SSL *ssl, int ret) {
52   return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDBACK;
53 }
54 
Handshaker(const TestConfig * config,int rfd,int wfd,Span<const uint8_t> input,int control)55 bool Handshaker(const TestConfig *config, int rfd, int wfd,
56                 Span<const uint8_t> input, int control) {
57   UniquePtr<SSL_CTX> ctx = config->SetupCtx(/*old_ctx=*/nullptr);
58   if (!ctx) {
59     return false;
60   }
61   UniquePtr<SSL> ssl =
62       config->NewSSL(ctx.get(), /*session=*/nullptr, /*test_state=*/nullptr);
63   if (!ssl) {
64     fprintf(stderr, "Error creating SSL object in handshaker.\n");
65     ERR_print_errors_fp(stderr);
66     return false;
67   }
68 
69   // Set |O_NONBLOCK| in order to break out of the loop when we hit
70   // |SSL_ERROR_WANT_READ|, so that we can send |kControlMsgWantRead| to the
71   // proxy.
72   if (fcntl(rfd, F_SETFL, O_NONBLOCK) != 0) {
73     perror("fcntl");
74     return false;
75   }
76   SSL_set_rfd(ssl.get(), rfd);
77   SSL_set_wfd(ssl.get(), wfd);
78 
79   CBS cbs, handoff;
80   CBS_init(&cbs, input.data(), input.size());
81   if (!CBS_get_asn1_element(&cbs, &handoff, CBS_ASN1_SEQUENCE) ||
82       !DeserializeContextState(&cbs, ctx.get()) ||
83       !SetTestState(ssl.get(), TestState::Deserialize(&cbs, ctx.get())) ||
84       !GetTestState(ssl.get()) ||
85       !SSL_apply_handoff(ssl.get(), handoff)) {
86     fprintf(stderr, "Handoff application failed.\n");
87     return false;
88   }
89 
90   int ret = 0;
91   for (;;) {
92     ret = CheckIdempotentError(
93         "SSL_do_handshake", ssl.get(),
94         [&]() -> int { return SSL_do_handshake(ssl.get()); });
95     if (SSL_get_error(ssl.get(), ret) == SSL_ERROR_WANT_READ) {
96       // Synchronize with the proxy, i.e. don't let the handshake continue until
97       // the proxy has sent more data.
98       char msg = kControlMsgWantRead;
99       if (write_eintr(control, &msg, 1) != 1 ||
100           read_eintr(control, &msg, 1) != 1 ||
101           msg != kControlMsgWriteCompleted) {
102         fprintf(stderr, "read via proxy failed\n");
103         return false;
104       }
105       continue;
106     }
107     if (!RetryAsync(ssl.get(), ret)) {
108       break;
109     }
110   }
111   if (!HandbackReady(ssl.get(), ret)) {
112     fprintf(stderr, "Handshaker: %s\n",
113             SSL_error_description(SSL_get_error(ssl.get(), ret)));
114     ERR_print_errors_fp(stderr);
115     return false;
116   }
117 
118   ScopedCBB output;
119   CBB handback;
120   if (!CBB_init(output.get(), 1024) ||
121       !CBB_add_u24_length_prefixed(output.get(), &handback) ||
122       !SSL_serialize_handback(ssl.get(), &handback) ||
123       !SerializeContextState(ctx.get(), output.get()) ||
124       !GetTestState(ssl.get())->Serialize(output.get())) {
125     fprintf(stderr, "Handback serialisation failed.\n");
126     return false;
127   }
128 
129   char msg = kControlMsgDone;
130   if (write_eintr(control, &msg, 1) == -1 ||
131       write_eintr(control, CBB_data(output.get()), CBB_len(output.get())) ==
132           -1) {
133     perror("write");
134     return false;
135   }
136   return true;
137 }
138 
GenerateHandshakeHint(const TestConfig * config,bssl::Span<const uint8_t> request,int control)139 bool GenerateHandshakeHint(const TestConfig *config,
140                            bssl::Span<const uint8_t> request, int control) {
141   // The handshake hint contains the ClientHello and the capabilities string.
142   CBS cbs = request;
143   CBS client_hello, capabilities;
144   if (!CBS_get_u24_length_prefixed(&cbs, &client_hello) ||
145       !CBS_get_u24_length_prefixed(&cbs, &capabilities) ||  //
146       CBS_len(&cbs) != 0) {
147     fprintf(stderr, "Handshaker: Could not parse hint request\n");
148     return false;
149   }
150 
151   UniquePtr<SSL_CTX> ctx = config->SetupCtx(/*old_ctx=*/nullptr);
152   if (!ctx) {
153     return false;
154   }
155 
156   UniquePtr<SSL> ssl = config->NewSSL(ctx.get(), /*session=*/nullptr,
157                                       std::make_unique<TestState>());
158   if (!ssl) {
159     fprintf(stderr, "Error creating SSL object in handshaker.\n");
160     ERR_print_errors_fp(stderr);
161     return false;
162   }
163 
164   // TODO(davidben): When split handshakes is replaced, move this into |NewSSL|.
165   assert(config->is_server);
166   SSL_set_accept_state(ssl.get());
167 
168   if (!SSL_request_handshake_hints(
169           ssl.get(), CBS_data(&client_hello), CBS_len(&client_hello),
170           CBS_data(&capabilities), CBS_len(&capabilities))) {
171     fprintf(stderr, "Handshaker: SSL_request_handshake_hints failed\n");
172     return false;
173   }
174 
175   int ret = 0;
176   do {
177     ret = CheckIdempotentError("SSL_do_handshake", ssl.get(),
178                                [&] { return SSL_do_handshake(ssl.get()); });
179   } while (RetryAsync(ssl.get(), ret));
180 
181   if (ret > 0) {
182     fprintf(stderr, "Handshaker: handshake unexpectedly succeeded.\n");
183     return false;
184   }
185 
186   if (SSL_get_error(ssl.get(), ret) != SSL_ERROR_HANDSHAKE_HINTS_READY) {
187     // Errors here may be expected if the test is testing a failing case. The
188     // shim should continue executing without a hint, so we report an error
189     // "successfully". This allows the shim to distinguish this from the other
190     // unexpected error cases.
191     //
192     // We intentionally avoid printing the error in this case, to avoid mixing
193     // up test expectations with errors from the shim.
194     char msg = kControlMsgError;
195     if (write_eintr(control, &msg, 1) == -1) {
196       return false;
197     }
198     return true;
199   }
200 
201   bssl::ScopedCBB hints;
202   if (!CBB_init(hints.get(), 256) ||
203       !SSL_serialize_handshake_hints(ssl.get(), hints.get())) {
204     fprintf(stderr, "Handshaker: failed to serialize handshake hints\n");
205     return false;
206   }
207 
208   char msg = kControlMsgDone;
209   if (write_eintr(control, &msg, 1) == -1 ||
210       write_eintr(control, CBB_data(hints.get()), CBB_len(hints.get())) == -1) {
211     perror("write");
212     return false;
213   }
214 
215   return true;
216 }
217 
SignalError()218 int SignalError() {
219   const char msg = kControlMsgError;
220   if (write_eintr(kFdControl, &msg, 1) != 1) {
221     return 2;
222   }
223   return 1;
224 }
225 
226 }  // namespace
227 
main(int argc,char ** argv)228 int main(int argc, char **argv) {
229   TestConfig initial_config, resume_config, retry_config;
230   if (!ParseConfig(argc - 1, argv + 1, /*is_shim=*/false, &initial_config,
231                    &resume_config, &retry_config)) {
232     return SignalError();
233   }
234   const TestConfig *config =
235       initial_config.handshaker_resume ? &resume_config : &initial_config;
236 #if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
237   if (initial_config.handshaker_resume) {
238     // If the PRNG returns exactly the same values when trying to resume then a
239     // "random" session ID will happen to exactly match the session ID
240     // "randomly" generated on the initial connection. The client will thus
241     // incorrectly believe that the server is resuming.
242     uint8_t byte;
243     RAND_bytes(&byte, 1);
244   }
245 #endif  // BORINGSSL_UNSAFE_DETERMINISTIC_MODE
246 
247   // read() will return the entire message in one go, because it's a datagram
248   // socket.
249   constexpr size_t kBufSize = 1024 * 1024;
250   std::vector<uint8_t> request(kBufSize);
251   ssize_t len = read_eintr(kFdControl, request.data(), request.size());
252   if (len == -1) {
253     perror("read");
254     return 2;
255   }
256   request.resize(static_cast<size_t>(len));
257 
258   if (config->handshake_hints) {
259     if (!GenerateHandshakeHint(config, request, kFdControl)) {
260       return SignalError();
261     }
262   } else {
263     if (!Handshaker(config, kFdProxyToHandshaker, kFdHandshakerToProxy,
264                     request, kFdControl)) {
265       return SignalError();
266     }
267   }
268   return 0;
269 }
270