Debian Codegraph @

test/core/handshake/server_ssl_common.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 "test/core/handshake/server_ssl_common.h"
20
21 #include <netinet/in.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/socket.h>
27 #include <unistd.h>
28
29 #include <string>
30
31 #include <openssl/crypto.h>
32 #include <openssl/err.h>
33 #include <openssl/evp.h>
34 #include <openssl/ssl.h>
35
36 #include "absl/base/thread_annotations.h"
37 #include "absl/strings/str_cat.h"
38
39 #include <grpc/grpc.h>
40 #include <grpc/grpc_security.h>
41 #include <grpc/slice.h>
42 #include <grpc/support/alloc.h>
43 #include <grpc/support/log.h>
44 #include <grpc/support/sync.h>
45
46 #include "src/core/lib/gprpp/sync.h"
47 #include "src/core/lib/gprpp/thd.h"
48 #include "src/core/lib/iomgr/error.h"
49 #include "src/core/lib/iomgr/load_file.h"
50 #include "test/core/util/port.h"
51 #include "test/core/util/test_config.h"
52
53 // IWYU pragma: no_include <arpa/inet.h>
54
55 #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
56 #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
57 #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
58
59 namespace {
60
61 // Handshake completed signal to server thread.
62 gpr_event client_handshake_complete;
63
64 int create_socket(int port) {
65 int s;
66 struct sockaddr_in addr;
67
68 addr.sin_family = AF_INET;
69 addr.sin_port = htons(static_cast<uint16_t>(port));
70 addr.sin_addr.s_addr = htonl(INADDR_ANY);
71
72 s = socket(AF_INET, SOCK_STREAM, 0);
73 if (s < 0) {
74 perror("Unable to create socket");
75 return -1;
76 }
77
78 if (connect(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
79 perror("Unable to connect");
80 return -1;
81 }
82
83 return s;
84 }
85
86 class ServerInfo {
87 public:
88 explicit ServerInfo(int p) : port_(p) {}
89
90 int port() const { return port_; }
91
92 void Activate() {
93 grpc_core::MutexLock lock(&mu_);
94 ready_ = true;
95 cv_.Signal();
96 }
97
98 void Await() {
99 grpc_core::MutexLock lock(&mu_);
100 while (!ready_) {
101 cv_.Wait(&mu_);
102 }
103 }
104
105 private:
106 const int port_;
107 grpc_core::Mutex mu_;
108 grpc_core::CondVar cv_;
109 bool ready_ ABSL_GUARDED_BY(mu_) = false;
110 };
111
112 // Simple gRPC server. This listens until client_handshake_complete occurs.
113 void server_thread(void* arg) {
114 ServerInfo* s = static_cast<ServerInfo*>(arg);
115 const int port = s->port();
116
117 // Load key pair and establish server SSL credentials.
118 grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
119 grpc_slice ca_slice, cert_slice, key_slice;
120 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
121 grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
122 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
123 grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
124 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
125 grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
126 const char* ca_cert =
127 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
128 pem_key_cert_pair.private_key =
129 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
130 pem_key_cert_pair.cert_chain =
131 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
132 grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create(
133 ca_cert, &pem_key_cert_pair, 1, 0, nullptr);
134
135 // Start server listening on local port.
136 std::string addr = absl::StrCat("127.0.0.1:", port);
137 grpc_server* server = grpc_server_create(nullptr, nullptr);
138 GPR_ASSERT(grpc_server_add_http2_port(server, addr.c_str(), ssl_creds));
139
140 grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
141
142 grpc_server_register_completion_queue(server, cq, nullptr);
143 grpc_server_start(server);
144
145 // Notify the other side that it is now ok to start working since SSL is
146 // definitely already started.
147 s->Activate();
148
149 // Wait a bounded number of time until client_handshake_complete is set,
150 // sleeping between polls.
151 int retries = 10;
152 while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) {
153 const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1);
154 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
155 GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT);
156 }
157
158 gpr_log(GPR_INFO, "Shutting down server");
159 grpc_server_shutdown_and_notify(server, cq, nullptr);
160 grpc_completion_queue_shutdown(cq);
161
162 const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
163 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
164 GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
165
166 grpc_server_destroy(server);
167 grpc_completion_queue_destroy(cq);
168 grpc_server_credentials_release(ssl_creds);
169 grpc_slice_unref(cert_slice);
170 grpc_slice_unref(key_slice);
171 grpc_slice_unref(ca_slice);
172 }
173
174 } // namespace
175
176 // This test launches a gRPC server on a separate thread and then establishes a
177 // TLS handshake via a minimal TLS client. The TLS client has configurable (via
178 // alpn_list) ALPN settings and can probe at the supported ALPN preferences
179 // using this (via alpn_expected).
180 bool server_ssl_test(const char* alpn_list[], unsigned int alpn_list_len,
181 const char* alpn_expected) {
182 bool success = true;
183
184 grpc_init();
185 ServerInfo s(grpc_pick_unused_port_or_die());
186 gpr_event_init(&client_handshake_complete);
187
188 // Launch the gRPC server thread.
189 bool ok;
190 grpc_core::Thread thd("grpc_ssl_test", server_thread, &s, &ok);
191 GPR_ASSERT(ok);
192 thd.Start();
193
194 // The work in server_thread will cause the SSL initialization to take place
195 // so long as we wait for it to reach beyond the point of adding a secure
196 // server port.
197 s.Await();
198
199 const SSL_METHOD* method = TLSv1_2_client_method();
200 SSL_CTX* ctx = SSL_CTX_new(method);
201 if (!ctx) {
202 perror("Unable to create SSL context");
203 ERR_print_errors_fp(stderr);
204 abort();
205 }
206
207 // Load key pair.
208 if (SSL_CTX_use_certificate_file(ctx, SSL_CERT_PATH, SSL_FILETYPE_PEM) < 0) {
209 ERR_print_errors_fp(stderr);
210 abort();
211 }
212 if (SSL_CTX_use_PrivateKey_file(ctx, SSL_KEY_PATH, SSL_FILETYPE_PEM) < 0) {
213 ERR_print_errors_fp(stderr);
214 abort();
215 }
216
217 // Set the cipher list to match the one expressed in
218 // src/core/tsi/ssl_transport_security.c.
219 const char* cipher_list =
220 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-"
221 "SHA384:ECDHE-RSA-AES256-GCM-SHA384";
222 if (!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
223 ERR_print_errors_fp(stderr);
224 gpr_log(GPR_ERROR, "Couldn't set server cipher list.");
225 abort();
226 }
227
228 // Configure ALPN list the client will send to the server. This must match the
229 // wire format, see documentation for SSL_CTX_set_alpn_protos.
230 unsigned int alpn_protos_len = alpn_list_len;
231 for (unsigned int i = 0; i < alpn_list_len; ++i) {
232 alpn_protos_len += static_cast<unsigned int>(strlen(alpn_list[i]));
233 }
234 unsigned char* alpn_protos =
235 static_cast<unsigned char*>(gpr_malloc(alpn_protos_len));
236 unsigned char* p = alpn_protos;
237 for (unsigned int i = 0; i < alpn_list_len; ++i) {
238 const uint8_t len = static_cast<uint8_t>(strlen(alpn_list[i]));
239 *p++ = len;
240 memcpy(p, alpn_list[i], len);
241 p += len;
242 }
243 GPR_ASSERT(SSL_CTX_set_alpn_protos(ctx, alpn_protos, alpn_protos_len) == 0);
244
245 // Try and connect to server. We allow a bounded number of retries as we might
246 // be racing with the server setup on its separate thread.
247 int retries = 10;
248 int sock = -1;
249 while (sock == -1 && retries-- > 0) {
250 sock = create_socket(s.port());
251 if (sock < 0) {
252 sleep(1);
253 }
254 }
255 GPR_ASSERT(sock > 0);
256 gpr_log(GPR_INFO, "Connected to server on port %d", s.port());
257
258 // Establish a SSL* and connect at SSL layer.
259 SSL* ssl = SSL_new(ctx);
260 GPR_ASSERT(ssl);
261 SSL_set_fd(ssl, sock);
262 if (SSL_connect(ssl) <= 0) {
263 ERR_print_errors_fp(stderr);
264 gpr_log(GPR_ERROR, "Handshake failed.");
265 success = false;
266 } else {
267 gpr_log(GPR_INFO, "Handshake successful.");
268 // Validate ALPN preferred by server matches alpn_expected.
269 const unsigned char* alpn_selected;
270 unsigned int alpn_selected_len;
271 SSL_get0_alpn_selected(ssl, &alpn_selected, &alpn_selected_len);
272 if (strlen(alpn_expected) != alpn_selected_len ||
273 strncmp(reinterpret_cast<const char*>(alpn_selected), alpn_expected,
274 alpn_selected_len) != 0) {
275 gpr_log(GPR_ERROR, "Unexpected ALPN protocol preference");
276 success = false;
277 }
278 }
279 gpr_event_set(&client_handshake_complete, &client_handshake_complete);
280
281 SSL_free(ssl);
282 gpr_free(alpn_protos);
283 SSL_CTX_free(ctx);
284 close(sock);
285
286 thd.Join();
287
288 grpc_shutdown();
289
290 return success;
291 }
292
293 void CleanupSslLibrary() { EVP_cleanup(); }