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