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 <string.h>
23 #include <sys/socket.h>
24 #include <unistd.h>
25
26 #include <string>
27
28 #include <openssl/err.h>
29 #include <openssl/ssl.h>
30
31 #include "absl/strings/str_cat.h"
32
33 #include <grpc/grpc.h>
34 #include <grpc/grpc_security.h>
35 #include <grpc/support/alloc.h>
36 #include <grpc/support/log.h>
37 #include <grpc/support/sync.h>
38
39 #include "src/core/lib/gprpp/sync.h"
40 #include "src/core/lib/gprpp/thd.h"
41 #include "src/core/lib/iomgr/load_file.h"
42 #include "test/core/util/port.h"
43 #include "test/core/util/test_config.h"
44
45 #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
46 #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
47 #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
48
49 namespace {
50
51 // Handshake completed signal to server thread.
52 gpr_event client_handshake_complete;
53
create_socket(int port)54 int create_socket(int port) {
55 int s;
56 struct sockaddr_in addr;
57
58 addr.sin_family = AF_INET;
59 addr.sin_port = htons(static_cast<uint16_t>(port));
60 addr.sin_addr.s_addr = htonl(INADDR_ANY);
61
62 s = socket(AF_INET, SOCK_STREAM, 0);
63 if (s < 0) {
64 perror("Unable to create socket");
65 return -1;
66 }
67
68 if (connect(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
69 perror("Unable to connect");
70 return -1;
71 }
72
73 return s;
74 }
75
76 class ServerInfo {
77 public:
ServerInfo(int p)78 explicit ServerInfo(int p) : port_(p) {}
79
port() const80 int port() const { return port_; }
81
Activate()82 void Activate() {
83 grpc_core::MutexLock lock(&mu_);
84 ready_ = true;
85 cv_.Signal();
86 }
87
Await()88 void Await() {
89 grpc_core::MutexLock lock(&mu_);
90 while (!ready_) {
91 cv_.Wait(&mu_);
92 }
93 }
94
95 private:
96 const int port_;
97 grpc_core::Mutex mu_;
98 grpc_core::CondVar cv_;
99 bool ready_ ABSL_GUARDED_BY(mu_) = false;
100 };
101
102 // Simple gRPC server. This listens until client_handshake_complete occurs.
server_thread(void * arg)103 void server_thread(void* arg) {
104 ServerInfo* s = static_cast<ServerInfo*>(arg);
105 const int port = s->port();
106
107 // Load key pair and establish server SSL credentials.
108 grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
109 grpc_slice ca_slice, cert_slice, key_slice;
110 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
111 grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
112 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
113 grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
114 GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
115 grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
116 const char* ca_cert =
117 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
118 pem_key_cert_pair.private_key =
119 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
120 pem_key_cert_pair.cert_chain =
121 reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
122 grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create(
123 ca_cert, &pem_key_cert_pair, 1, 0, nullptr);
124
125 // Start server listening on local port.
126 std::string addr = absl::StrCat("127.0.0.1:", port);
127 grpc_server* server = grpc_server_create(nullptr, nullptr);
128 GPR_ASSERT(
129 grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds));
130
131 grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
132
133 grpc_server_register_completion_queue(server, cq, nullptr);
134 grpc_server_start(server);
135
136 // Notify the other side that it is now ok to start working since SSL is
137 // definitely already started.
138 s->Activate();
139
140 // Wait a bounded number of time until client_handshake_complete is set,
141 // sleeping between polls.
142 int retries = 10;
143 while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) {
144 const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1);
145 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
146 GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT);
147 }
148
149 gpr_log(GPR_INFO, "Shutting down server");
150 grpc_server_shutdown_and_notify(server, cq, nullptr);
151 grpc_completion_queue_shutdown(cq);
152
153 const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
154 grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
155 GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
156
157 grpc_server_destroy(server);
158 grpc_completion_queue_destroy(cq);
159 grpc_server_credentials_release(ssl_creds);
160 grpc_slice_unref(cert_slice);
161 grpc_slice_unref(key_slice);
162 grpc_slice_unref(ca_slice);
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 GPR_ASSERT(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 gpr_log(GPR_ERROR, "Couldn't set server cipher list.");
216 abort();
217 }
218
219 // Configure ALPN list the client will send to the server. This must match the
220 // wire format, see documentation for SSL_CTX_set_alpn_protos.
221 unsigned int alpn_protos_len = alpn_list_len;
222 for (unsigned int i = 0; i < alpn_list_len; ++i) {
223 alpn_protos_len += static_cast<unsigned int>(strlen(alpn_list[i]));
224 }
225 unsigned char* alpn_protos =
226 static_cast<unsigned char*>(gpr_malloc(alpn_protos_len));
227 unsigned char* p = alpn_protos;
228 for (unsigned int i = 0; i < alpn_list_len; ++i) {
229 const uint8_t len = static_cast<uint8_t>(strlen(alpn_list[i]));
230 *p++ = len;
231 memcpy(p, alpn_list[i], len);
232 p += len;
233 }
234 GPR_ASSERT(SSL_CTX_set_alpn_protos(ctx, alpn_protos, alpn_protos_len) == 0);
235
236 // Try and connect to server. We allow a bounded number of retries as we might
237 // be racing with the server setup on its separate thread.
238 int retries = 10;
239 int sock = -1;
240 while (sock == -1 && retries-- > 0) {
241 sock = create_socket(s.port());
242 if (sock < 0) {
243 sleep(1);
244 }
245 }
246 GPR_ASSERT(sock > 0);
247 gpr_log(GPR_INFO, "Connected to server on port %d", s.port());
248
249 // Establish a SSL* and connect at SSL layer.
250 SSL* ssl = SSL_new(ctx);
251 GPR_ASSERT(ssl);
252 SSL_set_fd(ssl, sock);
253 if (SSL_connect(ssl) <= 0) {
254 ERR_print_errors_fp(stderr);
255 gpr_log(GPR_ERROR, "Handshake failed.");
256 success = false;
257 } else {
258 gpr_log(GPR_INFO, "Handshake successful.");
259 // Validate ALPN preferred by server matches alpn_expected.
260 const unsigned char* alpn_selected;
261 unsigned int alpn_selected_len;
262 SSL_get0_alpn_selected(ssl, &alpn_selected, &alpn_selected_len);
263 if (strlen(alpn_expected) != alpn_selected_len ||
264 strncmp(reinterpret_cast<const char*>(alpn_selected), alpn_expected,
265 alpn_selected_len) != 0) {
266 gpr_log(GPR_ERROR, "Unexpected ALPN protocol preference");
267 success = false;
268 }
269 }
270 gpr_event_set(&client_handshake_complete, &client_handshake_complete);
271
272 SSL_free(ssl);
273 gpr_free(alpn_protos);
274 SSL_CTX_free(ctx);
275 close(sock);
276
277 thd.Join();
278
279 grpc_shutdown();
280
281 return success;
282 }
283
CleanupSslLibrary()284 void CleanupSslLibrary() { EVP_cleanup(); }
285