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