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