Debian Codegraph @

test/core/handshake/client_ssl.cc

raw
1 /*
2 *
3 * Copyright 2016 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <netinet/in.h>
20 #include <stdint.h>
21 #include <stdio.h>
22
23 #include <openssl/crypto.h>
24 #include <openssl/evp.h>
25
26 #include "absl/base/thread_annotations.h"
27 #include "gtest/gtest.h"
28
29 #include <grpc/slice.h>
30
31 #include "src/core/lib/iomgr/error.h"
32 #include "src/core/lib/iomgr/port.h"
33 #include "test/core/util/test_config.h"
34
35 // IWYU pragma: no_include <arpa/inet.h>
36
37 // This test won't work except with posix sockets enabled
38 #ifdef GRPC_POSIX_SOCKET_TCP
39
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/socket.h>
43 #include <unistd.h>
44
45 #include <string>
46
47 #include <openssl/err.h>
48 #include <openssl/ssl.h>
49
50 #include "absl/strings/str_cat.h"
51
52 #include <grpc/grpc.h>
53 #include <grpc/grpc_security.h>
54 #include <grpc/support/log.h>
55
56 #include "src/core/lib/debug/trace.h"
57 #include "src/core/lib/gprpp/sync.h"
58 #include "src/core/lib/gprpp/thd.h"
59 #include "src/core/lib/iomgr/load_file.h"
60
61 #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
62 #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
63 #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
64
65 grpc_core::TraceFlag client_ssl_tsi_tracing_enabled(false, "tsi");
66
67 class SslLibraryInfo {
68 public:
69 SslLibraryInfo() {}
70
71 void Notify() {
72 grpc_core::MutexLock lock(&mu_);
73 ready_ = true;
74 cv_.Signal();
75 }
76
77 void Await() {
78 grpc_core::MutexLock lock(&mu_);
79 while (!ready_) {
80 cv_.Wait(&mu_);
81 }
82 }
83
84 private:
85 grpc_core::Mutex mu_;
86 grpc_core::CondVar cv_;
87 bool ready_ ABSL_GUARDED_BY(mu_) = false;
88 };
89
90 // Arguments for TLS server thread.
91 typedef struct {
92 int socket;
93 char* alpn_preferred;
94 SslLibraryInfo* ssl_library_info;
95 } server_args;
96
97 // Based on https://wiki.openssl.org/index.php/Simple_TLS_Server.
98 // Pick an arbitrary unused port and return it in *out_port. Return
99 // an fd>=0 on success.
100 static int create_socket(int* out_port) {
101 int s;
102 struct sockaddr_in addr;
103 socklen_t addr_len;
104 *out_port = -1;
105
106 addr.sin_family = AF_INET;
107 addr.sin_port = 0;
108 addr.sin_addr.s_addr = htonl(INADDR_ANY);
109
110 s = socket(AF_INET, SOCK_STREAM, 0);
111 if (s < 0) {
112 perror("Unable to create socket");
113 return -1;
114 }
115
116 if (bind(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
117 perror("Unable to bind");
118 gpr_log(GPR_ERROR, "%s", "Unable to bind to any port");
119 close(s);
120 return -1;
121 }
122
123 if (listen(s, 1) < 0) {
124 perror("Unable to listen");
125 close(s);
126 return -1;
127 }
128
129 addr_len = sizeof(addr);
130 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&addr), &addr_len) !=
131 0 ||
132 addr_len > sizeof(addr)) {
133 perror("getsockname");
134 gpr_log(GPR_ERROR, "%s", "Unable to get socket local address");
135 close(s);
136 return -1;
137 }
138
139 *out_port = ntohs(addr.sin_port);
140 return s;
141 }
142
143 // Server callback during ALPN negotiation. See man page for
144 // SSL_CTX_set_alpn_select_cb.
145 static int alpn_select_cb(SSL* /*ssl*/, const uint8_t** out, uint8_t* out_len,
146 const uint8_t* in, unsigned in_len, void* arg) {
147 const uint8_t* alpn_preferred = static_cast<const uint8_t*>(arg);
148
149 *out = alpn_preferred;
150 *out_len = static_cast<uint8_t>(
151 strlen(reinterpret_cast<const char*>(alpn_preferred)));
152
153 // Validate that the ALPN list includes "h2" and "grpc-exp", that "grpc-exp"
154 // precedes "h2".
155 bool grpc_exp_seen = false;
156 bool h2_seen = false;
157 const char* inp = reinterpret_cast<const char*>(in);
158 const char* in_end = inp + in_len;
159 while (inp < in_end) {
160 const size_t length = static_cast<size_t>(*inp++);
161 if (length == strlen("grpc-exp") && strncmp(inp, "grpc-exp", length) == 0) {
162 grpc_exp_seen = true;
163 EXPECT_FALSE(h2_seen);
164 }
165 if (length == strlen("h2") && strncmp(inp, "h2", length) == 0) {
166 h2_seen = true;
167 EXPECT_TRUE(grpc_exp_seen);
168 }
169 inp += length;
170 }
171
172 EXPECT_EQ(inp, in_end);
173 EXPECT_TRUE(grpc_exp_seen);
174 EXPECT_TRUE(h2_seen);
175
176 return SSL_TLSEXT_ERR_OK;
177 }
178
179 static void ssl_log_where_info(const SSL* ssl, int where, int flag,
180 const char* msg) {
181 if ((where & flag) &&
182 GRPC_TRACE_FLAG_ENABLED(client_ssl_tsi_tracing_enabled)) {
183 gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
184 SSL_state_string_long(ssl), SSL_state_string(ssl));
185 }
186 }
187
188 static void ssl_server_info_callback(const SSL* ssl, int where, int ret) {
189 if (ret == 0) {
190 gpr_log(GPR_ERROR, "ssl_server_info_callback: error occurred.\n");
191 return;
192 }
193
194 ssl_log_where_info(ssl, where, SSL_CB_LOOP, "Server: LOOP");
195 ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START,
196 "Server: HANDSHAKE START");
197 ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE,
198 "Server: HANDSHAKE DONE");
199 }
200
201 // Minimal TLS server. This is largely based on the example at
202 // https://wiki.openssl.org/index.php/Simple_TLS_Server and the gRPC core
203 // internals in src/core/tsi/ssl_transport_security.c.
204 static void server_thread(void* arg) {
205 const server_args* args = static_cast<server_args*>(arg);
206
207 SSL_load_error_strings();
208 OpenSSL_add_ssl_algorithms();
209 args->ssl_library_info->Notify();
210
211 const SSL_METHOD* method = TLSv1_2_server_method();
212 SSL_CTX* ctx = SSL_CTX_new(method);
213 if (!ctx) {
214 perror("Unable to create SSL context");
215 ERR_print_errors_fp(stderr);
216 abort();
217 }
218
219 // Load key pair.
220 if (SSL_CTX_use_certificate_file(ctx, SSL_CERT_PATH, SSL_FILETYPE_PEM) < 0) {
221 perror("Unable to use certificate file.");
222 ERR_print_errors_fp(stderr);
223 abort();
224 }
225 if (SSL_CTX_use_PrivateKey_file(ctx, SSL_KEY_PATH, SSL_FILETYPE_PEM) < 0) {
226 perror("Unable to use private key file.");
227 ERR_print_errors_fp(stderr);
228 abort();
229 }
230 if (SSL_CTX_check_private_key(ctx) != 1) {
231 perror("Check private key failed.");
232 ERR_print_errors_fp(stderr);
233 abort();
234 }
235
236 // Set the cipher list to match the one expressed in
237 // src/core/tsi/ssl_transport_security.cc.
238 const char* cipher_list =
239 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-"
240 "SHA384:ECDHE-RSA-AES256-GCM-SHA384";
241 if (!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
242 ERR_print_errors_fp(stderr);
243 gpr_log(GPR_ERROR, "Couldn't set server cipher list.");
244 abort();
245 }
246
247 // Enable automatic curve selection. This is a NO-OP when using OpenSSL
248 // versions > 1.0.2.
249 if (!SSL_CTX_set_ecdh_auto(ctx, /*onoff=*/1)) {
250 ERR_print_errors_fp(stderr);
251 gpr_log(GPR_ERROR, "Couldn't set automatic curve selection.");
252 abort();
253 }
254
255 // Register the ALPN selection callback.
256 SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, args->alpn_preferred);
257
258 // bind/listen/accept at TCP layer.
259 const int sock = args->socket;
260 gpr_log(GPR_INFO, "Server listening");
261 struct sockaddr_in addr;
262 socklen_t len = sizeof(addr);
263 const int client =
264 accept(sock, reinterpret_cast<struct sockaddr*>(&addr), &len);
265 if (client < 0) {
266 perror("Unable to accept");
267 abort();
268 }
269
270 // Establish a SSL* and accept at SSL layer.
271 SSL* ssl = SSL_new(ctx);
272 SSL_set_info_callback(ssl, ssl_server_info_callback);
273 ASSERT_TRUE(ssl);
274 SSL_set_fd(ssl, client);
275 if (SSL_accept(ssl) <= 0) {
276 ERR_print_errors_fp(stderr);
277 gpr_log(GPR_ERROR, "Handshake failed.");
278 } else {
279 gpr_log(GPR_INFO, "Handshake successful.");
280 }
281
282 // Send out the settings frame.
283 const char settings_frame[] = "\x00\x00\x00\x04\x00\x00\x00\x00\x00";
284 SSL_write(ssl, settings_frame, sizeof(settings_frame) - 1);
285
286 // Wait until the client drops its connection.
287 char buf;
288 while (SSL_read(ssl, &buf, sizeof(buf)) > 0) {
289 }
290
291 SSL_free(ssl);
292 close(client);
293 close(sock);
294 SSL_CTX_free(ctx);
295 }
296
297 // This test launches a minimal TLS server on a separate thread and then
298 // establishes a TLS handshake via the core library to the server. The TLS
299 // server validates ALPN aspects of the handshake and supplies the protocol
300 // specified in the server_alpn_preferred argument to the client.
301 static bool client_ssl_test(char* server_alpn_preferred) {
302 bool success = true;
303
304 grpc_init();
305
306 // Find a port we can bind to. Retries added to handle flakes in port server
307 // and port picking.
308 int port = -1;
309 int server_socket = -1;
310 int socket_retries = 30;
311 while (server_socket == -1 && socket_retries-- > 0) {
312 server_socket = create_socket(&port);
313 if (server_socket == -1) {
314 sleep(1);
315 }
316 }
317 EXPECT_GT(server_socket, 0);
318 EXPECT_GT(port, 0);
319
320 // Launch the TLS server thread.
321 SslLibraryInfo ssl_library_info;
322 server_args args = {server_socket, server_alpn_preferred, &ssl_library_info};
323 bool ok;
324 grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &args, &ok);
325 EXPECT_TRUE(ok);
326 thd.Start();
327 ssl_library_info.Await();
328
329 // Load key pair and establish client SSL credentials.
330 grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
331 grpc_slice ca_slice, cert_slice, key_slice;
332 EXPECT_TRUE(GRPC_LOG_IF_ERROR("load_file",
333 grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
334 EXPECT_TRUE(GRPC_LOG_IF_ERROR("load_file",
335 grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
336 EXPECT_TRUE(GRPC_LOG_IF_ERROR("load_file",
337 grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
338 const char* ca_cert =
339 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
340 pem_key_cert_pair.private_key =
341 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
342 pem_key_cert_pair.cert_chain =
343 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
344 grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create(
345 ca_cert, &pem_key_cert_pair, nullptr, nullptr);
346
347 // Establish a channel pointing at the TLS server. Since the gRPC runtime is
348 // lazy, this won't necessarily establish a connection yet.
349 std::string target = absl::StrCat("127.0.0.1:", port);
350 grpc_arg ssl_name_override = {
351 GRPC_ARG_STRING,
352 const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG),
353 {const_cast<char*>("foo.test.google.fr")}};
354 grpc_channel_args grpc_args;
355 grpc_args.num_args = 1;
356 grpc_args.args = &ssl_name_override;
357 grpc_channel* channel =
358 grpc_channel_create(target.c_str(), ssl_creds, &grpc_args);
359 EXPECT_TRUE(channel);
360
361 // Initially the channel will be idle, the
362 // grpc_channel_check_connectivity_state triggers an attempt to connect.
363 EXPECT_EQ(
364 grpc_channel_check_connectivity_state(channel, 1 /* try_to_connect */),
365 GRPC_CHANNEL_IDLE);
366
367 // Wait a bounded number of times for the channel to be ready. When the
368 // channel is ready, the initial TLS handshake will have successfully
369 // completed and we know that the client's ALPN list satisfied the server.
370 int retries = 10;
371 grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
372 grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
373
374 while (state != GRPC_CHANNEL_READY && retries-- > 0) {
375 grpc_channel_watch_connectivity_state(
376 channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr);
377 gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
378 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
379 EXPECT_EQ(ev.type, GRPC_OP_COMPLETE);
380 state =
381 grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
382 }
383 grpc_completion_queue_destroy(cq);
384 if (retries < 0) {
385 success = false;
386 }
387
388 grpc_channel_destroy(channel);
389 grpc_channel_credentials_release(ssl_creds);
390 grpc_slice_unref(cert_slice);
391 grpc_slice_unref(key_slice);
392 grpc_slice_unref(ca_slice);
393
394 thd.Join();
395
396 grpc_shutdown();
397
398 return success;
399 }
400
401 TEST(ClientSslTest, MainTest) {
402 // Handshake succeeeds when the server has grpc-exp as the ALPN preference.
403 ASSERT_TRUE(client_ssl_test(const_cast<char*>("grpc-exp")));
404 // Handshake succeeeds when the server has h2 as the ALPN preference. This
405 // covers legacy gRPC servers which don't support grpc-exp.
406 ASSERT_TRUE(client_ssl_test(const_cast<char*>("h2")));
407 // Handshake fails when the server uses a fake protocol as its ALPN
408 // preference. This validates the client is correctly validating ALPN returns
409 // and sanity checks the client_ssl_test.
410 ASSERT_FALSE(client_ssl_test(const_cast<char*>("foo")));
411 // Clean up the SSL libraries.
412 EVP_cleanup();
413 }
414
415 #endif /* GRPC_POSIX_SOCKET_TCP */
416
417 int main(int argc, char** argv) {
418 grpc::testing::TestEnvironment env(&argc, argv);
419 ::testing::InitGoogleTest(&argc, argv);
420 return RUN_ALL_TESTS();
421 }