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