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 "src/core/lib/iomgr/port.h"
20
21 // This test won't work except with posix sockets enabled
22 #ifdef GRPC_POSIX_SOCKET_TCP
23
24 #include <arpa/inet.h>
25 #include <openssl/err.h>
26 #include <openssl/ssl.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/socket.h>
30 #include <unistd.h>
31
32 #include <string>
33
34 #include "absl/strings/str_cat.h"
35
36 #include <grpc/grpc.h>
37 #include <grpc/grpc_security.h>
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/log.h>
40
41 #include "src/core/lib/gprpp/thd.h"
42 #include "src/core/lib/iomgr/load_file.h"
43 #include "test/core/util/port.h"
44 #include "test/core/util/test_config.h"
45
46 #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
47 #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
48 #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
49
50 // Arguments for TLS server thread.
51 typedef struct {
52 int socket;
53 char* alpn_preferred;
54 } server_args;
55
56 // Based on https://wiki.openssl.org/index.php/Simple_TLS_Server.
57 // Pick an arbitrary unused port and return it in *out_port. Return
58 // an fd>=0 on success.
create_socket(int * out_port)59 static int create_socket(int* out_port) {
60 int s;
61 struct sockaddr_in addr;
62 socklen_t addr_len;
63 *out_port = -1;
64
65 addr.sin_family = AF_INET;
66 addr.sin_port = 0;
67 addr.sin_addr.s_addr = htonl(INADDR_ANY);
68
69 s = socket(AF_INET, SOCK_STREAM, 0);
70 if (s < 0) {
71 perror("Unable to create socket");
72 return -1;
73 }
74
75 if (bind(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
76 perror("Unable to bind");
77 gpr_log(GPR_ERROR, "%s", "Unable to bind to any port");
78 close(s);
79 return -1;
80 }
81
82 if (listen(s, 1) < 0) {
83 perror("Unable to listen");
84 close(s);
85 return -1;
86 }
87
88 addr_len = sizeof(addr);
89 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&addr), &addr_len) !=
90 0 ||
91 addr_len > sizeof(addr)) {
92 perror("getsockname");
93 gpr_log(GPR_ERROR, "%s", "Unable to get socket local address");
94 close(s);
95 return -1;
96 }
97
98 *out_port = ntohs(addr.sin_port);
99 return s;
100 }
101
102 // Server callback during ALPN negotiation. See man page for
103 // SSL_CTX_set_alpn_select_cb.
alpn_select_cb(SSL *,const uint8_t ** out,uint8_t * out_len,const uint8_t * in,unsigned in_len,void * arg)104 static int alpn_select_cb(SSL* /*ssl*/, const uint8_t** out, uint8_t* out_len,
105 const uint8_t* in, unsigned in_len, void* arg) {
106 const uint8_t* alpn_preferred = static_cast<const uint8_t*>(arg);
107
108 *out = alpn_preferred;
109 *out_len = static_cast<uint8_t>(strlen((char*)alpn_preferred));
110
111 // Validate that the ALPN list includes "h2" and "grpc-exp", that "grpc-exp"
112 // precedes "h2".
113 bool grpc_exp_seen = false;
114 bool h2_seen = false;
115 const char* inp = reinterpret_cast<const char*>(in);
116 const char* in_end = inp + in_len;
117 while (inp < in_end) {
118 const size_t length = static_cast<size_t>(*inp++);
119 if (length == strlen("grpc-exp") && strncmp(inp, "grpc-exp", length) == 0) {
120 grpc_exp_seen = true;
121 GPR_ASSERT(!h2_seen);
122 }
123 if (length == strlen("h2") && strncmp(inp, "h2", length) == 0) {
124 h2_seen = true;
125 GPR_ASSERT(grpc_exp_seen);
126 }
127 inp += length;
128 }
129
130 GPR_ASSERT(inp == in_end);
131 GPR_ASSERT(grpc_exp_seen);
132 GPR_ASSERT(h2_seen);
133
134 return SSL_TLSEXT_ERR_OK;
135 }
136
137 // Minimal TLS server. This is largely based on the example at
138 // https://wiki.openssl.org/index.php/Simple_TLS_Server and the gRPC core
139 // internals in src/core/tsi/ssl_transport_security.c.
server_thread(void * arg)140 static void server_thread(void* arg) {
141 const server_args* args = static_cast<server_args*>(arg);
142
143 SSL_load_error_strings();
144 OpenSSL_add_ssl_algorithms();
145
146 const SSL_METHOD* method = TLSv1_2_server_method();
147 SSL_CTX* ctx = SSL_CTX_new(method);
148 if (!ctx) {
149 perror("Unable to create SSL context");
150 ERR_print_errors_fp(stderr);
151 abort();
152 }
153
154 // Load key pair.
155 if (SSL_CTX_use_certificate_file(ctx, SSL_CERT_PATH, SSL_FILETYPE_PEM) < 0) {
156 ERR_print_errors_fp(stderr);
157 abort();
158 }
159 if (SSL_CTX_use_PrivateKey_file(ctx, SSL_KEY_PATH, SSL_FILETYPE_PEM) < 0) {
160 ERR_print_errors_fp(stderr);
161 abort();
162 }
163
164 // Set the cipher list to match the one expressed in
165 // src/core/tsi/ssl_transport_security.c.
166 const char* cipher_list =
167 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-"
168 "SHA384:ECDHE-RSA-AES256-GCM-SHA384";
169 if (!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
170 ERR_print_errors_fp(stderr);
171 gpr_log(GPR_ERROR, "Couldn't set server cipher list.");
172 abort();
173 }
174
175 // Register the ALPN selection callback.
176 SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, args->alpn_preferred);
177
178 // bind/listen/accept at TCP layer.
179 const int sock = args->socket;
180 gpr_log(GPR_INFO, "Server listening");
181 struct sockaddr_in addr;
182 socklen_t len = sizeof(addr);
183 const int client =
184 accept(sock, reinterpret_cast<struct sockaddr*>(&addr), &len);
185 if (client < 0) {
186 perror("Unable to accept");
187 abort();
188 }
189
190 // Establish a SSL* and accept at SSL layer.
191 SSL* ssl = SSL_new(ctx);
192 GPR_ASSERT(ssl);
193 SSL_set_fd(ssl, client);
194 if (SSL_accept(ssl) <= 0) {
195 ERR_print_errors_fp(stderr);
196 gpr_log(GPR_ERROR, "Handshake failed.");
197 } else {
198 gpr_log(GPR_INFO, "Handshake successful.");
199 }
200
201 // Wait until the client drops its connection.
202 char buf;
203 while (SSL_read(ssl, &buf, sizeof(buf)) > 0)
204 ;
205
206 SSL_free(ssl);
207 close(client);
208 close(sock);
209 SSL_CTX_free(ctx);
210 EVP_cleanup();
211 }
212
213 // This test launches a minimal TLS server on a separate thread and then
214 // establishes a TLS handshake via the core library to the server. The TLS
215 // server validates ALPN aspects of the handshake and supplies the protocol
216 // specified in the server_alpn_preferred argument to the client.
client_ssl_test(char * server_alpn_preferred)217 static bool client_ssl_test(char* server_alpn_preferred) {
218 bool success = true;
219
220 grpc_init();
221
222 // Find a port we can bind to. Retries added to handle flakes in port server
223 // and port picking.
224 int port = -1;
225 int server_socket = -1;
226 int socket_retries = 30;
227 while (server_socket == -1 && socket_retries-- > 0) {
228 server_socket = create_socket(&port);
229 if (server_socket == -1) {
230 sleep(1);
231 }
232 }
233 GPR_ASSERT(server_socket > 0 && port > 0);
234
235 // Launch the TLS server thread.
236 server_args args = {server_socket, server_alpn_preferred};
237 bool ok;
238 grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &args, &ok);
239 GPR_ASSERT(ok);
240 thd.Start();
241
242 // Load key pair and establish client SSL credentials.
243 grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
244 grpc_slice ca_slice, cert_slice, key_slice;
245 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
246 grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
247 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
248 grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
249 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
250 grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
251 const char* ca_cert =
252 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
253 pem_key_cert_pair.private_key =
254 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
255 pem_key_cert_pair.cert_chain =
256 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
257 grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create(
258 ca_cert, &pem_key_cert_pair, nullptr, nullptr);
259
260 // Establish a channel pointing at the TLS server. Since the gRPC runtime is
261 // lazy, this won't necessarily establish a connection yet.
262 std::string target = absl::StrCat("127.0.0.1:", port);
263 grpc_arg ssl_name_override = {
264 GRPC_ARG_STRING,
265 const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG),
266 {const_cast<char*>("foo.test.google.fr")}};
267 grpc_channel_args grpc_args;
268 grpc_args.num_args = 1;
269 grpc_args.args = &ssl_name_override;
270 grpc_channel* channel = grpc_secure_channel_create(ssl_creds, target.c_str(),
271 &grpc_args, nullptr);
272 GPR_ASSERT(channel);
273
274 // Initially the channel will be idle, the
275 // grpc_channel_check_connectivity_state triggers an attempt to connect.
276 GPR_ASSERT(grpc_channel_check_connectivity_state(
277 channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE);
278
279 // Wait a bounded number of times for the channel to be ready. When the
280 // channel is ready, the initial TLS handshake will have successfully
281 // completed and we know that the client's ALPN list satisfied the server.
282 int retries = 10;
283 grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
284 grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
285
286 while (state != GRPC_CHANNEL_READY && retries-- > 0) {
287 grpc_channel_watch_connectivity_state(
288 channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr);
289 gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
290 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
291 GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
292 state =
293 grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
294 }
295 grpc_completion_queue_destroy(cq);
296 if (retries < 0) {
297 success = false;
298 }
299
300 grpc_channel_destroy(channel);
301 grpc_channel_credentials_release(ssl_creds);
302 grpc_slice_unref(cert_slice);
303 grpc_slice_unref(key_slice);
304 grpc_slice_unref(ca_slice);
305
306 thd.Join();
307
308 grpc_shutdown();
309
310 return success;
311 }
312
main(int argc,char * argv[])313 int main(int argc, char* argv[]) {
314 grpc::testing::TestEnvironment env(argc, argv);
315 // Handshake succeeeds when the server has grpc-exp as the ALPN preference.
316 GPR_ASSERT(client_ssl_test(const_cast<char*>("grpc-exp")));
317 // Handshake succeeeds when the server has h2 as the ALPN preference. This
318 // covers legacy gRPC servers which don't support grpc-exp.
319 GPR_ASSERT(client_ssl_test(const_cast<char*>("h2")));
320 // Handshake fails when the server uses a fake protocol as its ALPN
321 // preference. This validates the client is correctly validating ALPN returns
322 // and sanity checks the client_ssl_test.
323 GPR_ASSERT(!client_ssl_test(const_cast<char*>("foo")));
324 return 0;
325 }
326
327 #else /* GRPC_POSIX_SOCKET_TCP */
328
main(int argc,char ** argv)329 int main(int argc, char** argv) { return 1; }
330
331 #endif /* GRPC_POSIX_SOCKET_TCP */
332