• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //
3 // Copyright 2018 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 <grpc/credentials.h>
26 #include <grpc/grpc.h>
27 #include <grpc/grpc_security.h>
28 #include <grpc/support/alloc.h>
29 #include <openssl/err.h>
30 #include <openssl/ssl.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/socket.h>
34 #include <unistd.h>
35 
36 #include <string>
37 
38 #include "absl/log/check.h"
39 #include "absl/log/log.h"
40 #include "absl/strings/str_cat.h"
41 #include "src/core/util/crash.h"
42 #include "src/core/util/thd.h"
43 #include "test/core/test_util/port.h"
44 #include "test/core/test_util/test_config.h"
45 #include "test/core/test_util/tls_utils.h"
46 
47 #define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
48 #define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
49 #define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
50 
51 // Simple gRPC server. This listens until client_handshake_complete occurs.
52 static gpr_event client_handshake_complete;
53 
server_thread(void * arg)54 static void server_thread(void* arg) {
55   const int port = *static_cast<int*>(arg);
56 
57   // Load key pair and establish server SSL credentials.
58   std::string ca_cert = grpc_core::testing::GetFileContents(SSL_CA_PATH);
59   std::string cert = grpc_core::testing::GetFileContents(SSL_CERT_PATH);
60   std::string key = grpc_core::testing::GetFileContents(SSL_KEY_PATH);
61 
62   grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
63   pem_key_cert_pair.private_key = key.c_str();
64   pem_key_cert_pair.cert_chain = cert.c_str();
65   grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create(
66       ca_cert.c_str(), &pem_key_cert_pair, 1, 0, nullptr);
67 
68   // Start server listening on local port.
69   std::string addr = absl::StrCat("127.0.0.1:", port);
70   grpc_server* server = grpc_server_create(nullptr, nullptr);
71   CHECK(grpc_server_add_http2_port(server, addr.c_str(), ssl_creds));
72 
73   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
74 
75   grpc_server_register_completion_queue(server, cq, nullptr);
76   grpc_server_start(server);
77 
78   // Wait a bounded number of time until client_handshake_complete is set,
79   // sleeping between polls. The total time spent (deadline * retries)
80   // should be strictly greater than the client retry limit so that the
81   // client will always timeout first.
82   int retries = 60;
83   while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) {
84     const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1);
85     grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
86     CHECK(ev.type == GRPC_QUEUE_TIMEOUT);
87   }
88 
89   LOG(INFO) << "Shutting down server";
90   grpc_server_shutdown_and_notify(server, cq, nullptr);
91   grpc_server_cancel_all_calls(server);
92   grpc_completion_queue_shutdown(cq);
93 
94   const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(60);
95   grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
96   CHECK(ev.type == GRPC_OP_COMPLETE);
97 
98   grpc_server_destroy(server);
99   grpc_completion_queue_destroy(cq);
100   grpc_server_credentials_release(ssl_creds);
101 }
102 
103 // This test launches a minimal TLS grpc server on a separate thread and then
104 // establishes a TLS handshake via the core library to the server. The client
105 // uses the supplied verify options.
verify_peer_options_test(verify_peer_options * verify_options)106 static bool verify_peer_options_test(verify_peer_options* verify_options) {
107   bool success = true;
108 
109   grpc_init();
110   int port = grpc_pick_unused_port_or_die();
111   gpr_event_init(&client_handshake_complete);
112 
113   // Load key pair and establish client SSL credentials.
114   // NOTE: we intentionally load the credential files before starting
115   // the server thread because loading the file can experience trouble
116   // when two threads attempt to load the same file concurrently
117   // and server thread also reads the same files as soon as it starts.
118   // See https://github.com/grpc/grpc/issues/23503 for details.
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_channel_credentials* ssl_creds = grpc_ssl_credentials_create(
127       ca_cert.c_str(), &pem_key_cert_pair, verify_options, nullptr);
128 
129   // Launch the gRPC server thread.
130   bool ok;
131   grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &port, &ok);
132   CHECK(ok);
133   thd.Start();
134 
135   // Establish a channel pointing at the TLS server. Since the gRPC runtime is
136   // lazy, this won't necessarily establish a connection yet.
137   std::string target = absl::StrCat("127.0.0.1:", port);
138   grpc_arg ssl_name_override = {
139       GRPC_ARG_STRING,
140       const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG),
141       {const_cast<char*>("foo.test.google.fr")}};
142   grpc_channel_args grpc_args;
143   grpc_args.num_args = 1;
144   grpc_args.args = &ssl_name_override;
145   grpc_channel* channel =
146       grpc_channel_create(target.c_str(), ssl_creds, &grpc_args);
147   CHECK(channel);
148 
149   // Initially the channel will be idle, the
150   // grpc_channel_check_connectivity_state triggers an attempt to connect.
151   CHECK(grpc_channel_check_connectivity_state(
152             channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE);
153 
154   // Wait a bounded number of times for the channel to be ready. When the
155   // channel is ready, the initial TLS handshake will have successfully
156   // completed. The total time spent on the client side (retries * deadline)
157   // should be greater than the server side time limit.
158   int retries = 10;
159   grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
160   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
161 
162   while (state != GRPC_CHANNEL_READY && retries-- > 0) {
163     grpc_channel_watch_connectivity_state(
164         channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr);
165     gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
166     grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
167     CHECK(ev.type == GRPC_OP_COMPLETE);
168     state =
169         grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
170   }
171   grpc_completion_queue_destroy(cq);
172   if (retries < 0) {
173     success = false;
174   }
175 
176   grpc_channel_destroy(channel);
177   grpc_channel_credentials_release(ssl_creds);
178 
179   // Now that the client is completely cleaned up, trigger the server to
180   // shutdown
181   gpr_event_set(&client_handshake_complete, &client_handshake_complete);
182   // Wait for the server to completely shutdown
183   thd.Join();
184 
185   grpc_shutdown();
186 
187   return success;
188 }
189 
190 static int callback_return_value = 0;
191 static char callback_target_host[4096];
192 static char callback_target_pem[4096];
193 static void* callback_userdata = nullptr;
194 static void* destruct_userdata = nullptr;
195 
verify_callback(const char * target_host,const char * target_pem,void * userdata)196 static int verify_callback(const char* target_host, const char* target_pem,
197                            void* userdata) {
198   if (target_host != nullptr) {
199     snprintf(callback_target_host, sizeof(callback_target_host), "%s",
200              target_host);
201   } else {
202     callback_target_host[0] = '\0';
203   }
204   if (target_pem != nullptr) {
205     snprintf(callback_target_pem, sizeof(callback_target_pem), "%s",
206              target_pem);
207   } else {
208     callback_target_pem[0] = '\0';
209   }
210   callback_userdata = userdata;
211   return callback_return_value;
212 }
213 
verify_destruct(void * userdata)214 static void verify_destruct(void* userdata) { destruct_userdata = userdata; }
215 
main(int argc,char * argv[])216 int main(int argc, char* argv[]) {
217   grpc::testing::TestEnvironment env(&argc, argv);
218   grpc_init();
219 
220   int userdata = 42;
221   verify_peer_options verify_options;
222 
223   // Load the server's cert so that we can assert it gets passed to the callback
224   std::string server_cert = grpc_core::testing::GetFileContents(SSL_CERT_PATH);
225 
226   // Running with all-null values should have no effect
227   verify_options.verify_peer_callback = nullptr;
228   verify_options.verify_peer_callback_userdata = nullptr;
229   verify_options.verify_peer_destruct = nullptr;
230   CHECK(verify_peer_options_test(&verify_options));
231   CHECK_EQ(strlen(callback_target_host), 0);
232   CHECK_EQ(strlen(callback_target_pem), 0);
233   CHECK_EQ(callback_userdata, nullptr);
234   CHECK_EQ(destruct_userdata, nullptr);
235 
236   // Running with the callbacks and verify we get the expected values
237   verify_options.verify_peer_callback = verify_callback;
238   verify_options.verify_peer_callback_userdata = static_cast<void*>(&userdata);
239   verify_options.verify_peer_destruct = verify_destruct;
240   CHECK(verify_peer_options_test(&verify_options));
241   CHECK_EQ(strcmp(callback_target_host, "foo.test.google.fr"), 0);
242   CHECK_EQ(strcmp(callback_target_pem, server_cert.c_str()), 0);
243   CHECK(callback_userdata == static_cast<void*>(&userdata));
244   CHECK(destruct_userdata == static_cast<void*>(&userdata));
245 
246   // If the callback returns non-zero, initializing the channel should fail.
247   callback_return_value = 1;
248   CHECK(!verify_peer_options_test(&verify_options));
249 
250   grpc_shutdown();
251   return 0;
252 }
253 
254 #else  // GRPC_POSIX_SOCKET_TCP
255 
main(int argc,char ** argv)256 int main(int argc, char** argv) { return 1; }
257 
258 #endif  // GRPC_POSIX_SOCKET_TCP
259