3 * Copyright 2016 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "test/core/handshake/server_ssl_common.h"
21 #include <arpa/inet.h>
22 #include <openssl/err.h>
23 #include <openssl/ssl.h>
25 #include <sys/socket.h>
30 #include "absl/strings/str_cat.h"
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>
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"
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"
50 // Handshake completed signal to server thread.
51 gpr_event client_handshake_complete;
53 int create_socket(int port) {
55 struct sockaddr_in addr;
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);
61 s = socket(AF_INET, SOCK_STREAM, 0);
63 perror("Unable to create socket");
67 if (connect(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
68 perror("Unable to connect");
77 explicit ServerInfo(int p) : port_(p) {}
79 int port() const { return port_; }
82 grpc_core::MutexLock lock(&mu_);
88 grpc_core::MutexLock lock(&mu_);
89 grpc_core::WaitUntil(&cv_, &mu_, [this] { return ready_; });
95 grpc_core::CondVar cv_;
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();
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);
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);
126 grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds));
128 grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
130 grpc_server_register_completion_queue(server, cq, nullptr);
131 grpc_server_start(server);
133 // Notify the other side that it is now ok to start working since SSL is
134 // definitely already started.
137 // Wait a bounded number of time until client_handshake_complete is set,
138 // sleeping between polls.
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);
146 gpr_log(GPR_INFO, "Shutting down server");
147 grpc_server_shutdown_and_notify(server, cq, nullptr);
148 grpc_completion_queue_shutdown(cq);
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);
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);
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) {
173 ServerInfo s(grpc_pick_unused_port_or_die());
174 gpr_event_init(&client_handshake_complete);
176 // Launch the gRPC server thread.
178 grpc_core::Thread thd("grpc_ssl_test", server_thread, &s, &ok);
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
187 const SSL_METHOD* method = TLSv1_2_client_method();
188 SSL_CTX* ctx = SSL_CTX_new(method);
190 perror("Unable to create SSL context");
191 ERR_print_errors_fp(stderr);
196 if (SSL_CTX_use_certificate_file(ctx, SSL_CERT_PATH, SSL_FILETYPE_PEM) < 0) {
197 ERR_print_errors_fp(stderr);
200 if (SSL_CTX_use_PrivateKey_file(ctx, SSL_KEY_PATH, SSL_FILETYPE_PEM) < 0) {
201 ERR_print_errors_fp(stderr);
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.");
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]));
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]));
228 memcpy(p, alpn_list[i], len);
231 GPR_ASSERT(SSL_CTX_set_alpn_protos(ctx, alpn_protos, alpn_protos_len) == 0);
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.
237 while (sock == -1 && retries-- > 0) {
238 sock = create_socket(s.port());
243 GPR_ASSERT(sock > 0);
244 gpr_log(GPR_INFO, "Connected to server on port %d", s.port());
246 // Establish a SSL* and connect at SSL layer.
247 SSL* ssl = SSL_new(ctx);
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.");
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");
267 gpr_event_set(&client_handshake_complete, &client_handshake_complete);
270 gpr_free(alpn_protos);