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 <grpc/support/port_platform.h>
20
21 #include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h"
22
23 #include <stdbool.h>
24
25 #include "absl/strings/str_cat.h"
26 #include "absl/strings/str_format.h"
27 #include "absl/strings/string_view.h"
28
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31
32 #include "src/core/ext/transport/chttp2/alpn/alpn.h"
33 #include "src/core/lib/channel/handshaker.h"
34 #include "src/core/lib/gpr/string.h"
35 #include "src/core/lib/gprpp/host_port.h"
36 #include "src/core/lib/gprpp/ref_counted_ptr.h"
37 #include "src/core/lib/gprpp/sync.h"
38 #include "src/core/lib/security/context/security_context.h"
39 #include "src/core/lib/security/credentials/credentials.h"
40 #include "src/core/lib/security/credentials/ssl/ssl_credentials.h"
41 #include "src/core/lib/security/security_connector/load_system_roots.h"
42 #include "src/core/lib/security/security_connector/ssl_utils.h"
43 #include "src/core/lib/security/transport/security_handshaker.h"
44 #include "src/core/tsi/ssl_transport_security.h"
45 #include "src/core/tsi/transport_security.h"
46
47 namespace {
ssl_check_peer(const char * peer_name,const tsi_peer * peer,grpc_core::RefCountedPtr<grpc_auth_context> * auth_context)48 grpc_error* ssl_check_peer(
49 const char* peer_name, const tsi_peer* peer,
50 grpc_core::RefCountedPtr<grpc_auth_context>* auth_context) {
51 grpc_error* error = grpc_ssl_check_alpn(peer);
52 if (error != GRPC_ERROR_NONE) {
53 return error;
54 }
55 /* Check the peer name if specified. */
56 if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) {
57 return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
58 absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
59 .c_str());
60 }
61 *auth_context =
62 grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE);
63 return GRPC_ERROR_NONE;
64 }
65
66 class grpc_ssl_channel_security_connector final
67 : public grpc_channel_security_connector {
68 public:
grpc_ssl_channel_security_connector(grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,const grpc_ssl_config * config,const char * target_name,const char * overridden_target_name)69 grpc_ssl_channel_security_connector(
70 grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
71 grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
72 const grpc_ssl_config* config, const char* target_name,
73 const char* overridden_target_name)
74 : grpc_channel_security_connector(GRPC_SSL_URL_SCHEME,
75 std::move(channel_creds),
76 std::move(request_metadata_creds)),
77 overridden_target_name_(
78 overridden_target_name == nullptr ? "" : overridden_target_name),
79 verify_options_(&config->verify_options) {
80 absl::string_view host;
81 absl::string_view port;
82 grpc_core::SplitHostPort(target_name, &host, &port);
83 target_name_ = std::string(host);
84 }
85
~grpc_ssl_channel_security_connector()86 ~grpc_ssl_channel_security_connector() override {
87 tsi_ssl_client_handshaker_factory_unref(client_handshaker_factory_);
88 }
89
InitializeHandshakerFactory(const grpc_ssl_config * config,const char * pem_root_certs,const tsi_ssl_root_certs_store * root_store,tsi_ssl_session_cache * ssl_session_cache)90 grpc_security_status InitializeHandshakerFactory(
91 const grpc_ssl_config* config, const char* pem_root_certs,
92 const tsi_ssl_root_certs_store* root_store,
93 tsi_ssl_session_cache* ssl_session_cache) {
94 bool has_key_cert_pair =
95 config->pem_key_cert_pair != nullptr &&
96 config->pem_key_cert_pair->private_key != nullptr &&
97 config->pem_key_cert_pair->cert_chain != nullptr;
98 tsi_ssl_client_handshaker_options options;
99 GPR_DEBUG_ASSERT(pem_root_certs != nullptr);
100 options.pem_root_certs = pem_root_certs;
101 options.root_store = root_store;
102 options.alpn_protocols =
103 grpc_fill_alpn_protocol_strings(&options.num_alpn_protocols);
104 if (has_key_cert_pair) {
105 options.pem_key_cert_pair = config->pem_key_cert_pair;
106 }
107 options.cipher_suites = grpc_get_ssl_cipher_suites();
108 options.session_cache = ssl_session_cache;
109 options.min_tls_version = grpc_get_tsi_tls_version(config->min_tls_version);
110 options.max_tls_version = grpc_get_tsi_tls_version(config->max_tls_version);
111 const tsi_result result =
112 tsi_create_ssl_client_handshaker_factory_with_options(
113 &options, &client_handshaker_factory_);
114 gpr_free(options.alpn_protocols);
115 if (result != TSI_OK) {
116 gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
117 tsi_result_to_string(result));
118 return GRPC_SECURITY_ERROR;
119 }
120 return GRPC_SECURITY_OK;
121 }
122
add_handshakers(const grpc_channel_args * args,grpc_pollset_set *,grpc_core::HandshakeManager * handshake_mgr)123 void add_handshakers(const grpc_channel_args* args,
124 grpc_pollset_set* /*interested_parties*/,
125 grpc_core::HandshakeManager* handshake_mgr) override {
126 // Instantiate TSI handshaker.
127 tsi_handshaker* tsi_hs = nullptr;
128 tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker(
129 client_handshaker_factory_,
130 overridden_target_name_.empty() ? target_name_.c_str()
131 : overridden_target_name_.c_str(),
132 &tsi_hs);
133 if (result != TSI_OK) {
134 gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.",
135 tsi_result_to_string(result));
136 return;
137 }
138 // Create handshakers.
139 handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
140 }
141
check_peer(tsi_peer peer,grpc_endpoint *,grpc_core::RefCountedPtr<grpc_auth_context> * auth_context,grpc_closure * on_peer_checked)142 void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
143 grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
144 grpc_closure* on_peer_checked) override {
145 const char* target_name = overridden_target_name_.empty()
146 ? target_name_.c_str()
147 : overridden_target_name_.c_str();
148 grpc_error* error = ssl_check_peer(target_name, &peer, auth_context);
149 if (error == GRPC_ERROR_NONE &&
150 verify_options_->verify_peer_callback != nullptr) {
151 const tsi_peer_property* p =
152 tsi_peer_get_property_by_name(&peer, TSI_X509_PEM_CERT_PROPERTY);
153 if (p == nullptr) {
154 error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
155 "Cannot check peer: missing pem cert property.");
156 } else {
157 char* peer_pem = static_cast<char*>(gpr_malloc(p->value.length + 1));
158 memcpy(peer_pem, p->value.data, p->value.length);
159 peer_pem[p->value.length] = '\0';
160 int callback_status = verify_options_->verify_peer_callback(
161 target_name, peer_pem,
162 verify_options_->verify_peer_callback_userdata);
163 gpr_free(peer_pem);
164 if (callback_status) {
165 error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
166 absl::StrFormat("Verify peer callback returned a failure (%d)",
167 callback_status)
168 .c_str());
169 }
170 }
171 }
172 grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
173 tsi_peer_destruct(&peer);
174 }
175
cmp(const grpc_security_connector * other_sc) const176 int cmp(const grpc_security_connector* other_sc) const override {
177 auto* other =
178 reinterpret_cast<const grpc_ssl_channel_security_connector*>(other_sc);
179 int c = channel_security_connector_cmp(other);
180 if (c != 0) return c;
181 c = target_name_.compare(other->target_name_);
182 if (c != 0) return c;
183 return overridden_target_name_.compare(other->overridden_target_name_);
184 }
185
check_call_host(absl::string_view host,grpc_auth_context * auth_context,grpc_closure *,grpc_error ** error)186 bool check_call_host(absl::string_view host, grpc_auth_context* auth_context,
187 grpc_closure* /*on_call_host_checked*/,
188 grpc_error** error) override {
189 return grpc_ssl_check_call_host(host, target_name_.c_str(),
190 overridden_target_name_.c_str(),
191 auth_context, error);
192 }
193
cancel_check_call_host(grpc_closure *,grpc_error * error)194 void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
195 grpc_error* error) override {
196 GRPC_ERROR_UNREF(error);
197 }
198
199 private:
200 tsi_ssl_client_handshaker_factory* client_handshaker_factory_;
201 std::string target_name_;
202 std::string overridden_target_name_;
203 const verify_peer_options* verify_options_;
204 };
205
206 class grpc_ssl_server_security_connector
207 : public grpc_server_security_connector {
208 public:
grpc_ssl_server_security_connector(grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)209 explicit grpc_ssl_server_security_connector(
210 grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)
211 : grpc_server_security_connector(GRPC_SSL_URL_SCHEME,
212 std::move(server_creds)) {}
213
~grpc_ssl_server_security_connector()214 ~grpc_ssl_server_security_connector() override {
215 tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_);
216 }
217
has_cert_config_fetcher() const218 bool has_cert_config_fetcher() const {
219 return static_cast<const grpc_ssl_server_credentials*>(server_creds())
220 ->has_cert_config_fetcher();
221 }
222
server_handshaker_factory() const223 const tsi_ssl_server_handshaker_factory* server_handshaker_factory() const {
224 return server_handshaker_factory_;
225 }
226
InitializeHandshakerFactory()227 grpc_security_status InitializeHandshakerFactory() {
228 if (has_cert_config_fetcher()) {
229 // Load initial credentials from certificate_config_fetcher:
230 if (!try_fetch_ssl_server_credentials()) {
231 gpr_log(GPR_ERROR,
232 "Failed loading SSL server credentials from fetcher.");
233 return GRPC_SECURITY_ERROR;
234 }
235 } else {
236 auto* server_credentials =
237 static_cast<const grpc_ssl_server_credentials*>(server_creds());
238 size_t num_alpn_protocols = 0;
239 const char** alpn_protocol_strings =
240 grpc_fill_alpn_protocol_strings(&num_alpn_protocols);
241 tsi_ssl_server_handshaker_options options;
242 options.pem_key_cert_pairs =
243 server_credentials->config().pem_key_cert_pairs;
244 options.num_key_cert_pairs =
245 server_credentials->config().num_key_cert_pairs;
246 options.pem_client_root_certs =
247 server_credentials->config().pem_root_certs;
248 options.client_certificate_request =
249 grpc_get_tsi_client_certificate_request_type(
250 server_credentials->config().client_certificate_request);
251 options.cipher_suites = grpc_get_ssl_cipher_suites();
252 options.alpn_protocols = alpn_protocol_strings;
253 options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
254 options.min_tls_version = grpc_get_tsi_tls_version(
255 server_credentials->config().min_tls_version);
256 options.max_tls_version = grpc_get_tsi_tls_version(
257 server_credentials->config().max_tls_version);
258 const tsi_result result =
259 tsi_create_ssl_server_handshaker_factory_with_options(
260 &options, &server_handshaker_factory_);
261 gpr_free(alpn_protocol_strings);
262 if (result != TSI_OK) {
263 gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
264 tsi_result_to_string(result));
265 return GRPC_SECURITY_ERROR;
266 }
267 }
268 return GRPC_SECURITY_OK;
269 }
270
add_handshakers(const grpc_channel_args * args,grpc_pollset_set *,grpc_core::HandshakeManager * handshake_mgr)271 void add_handshakers(const grpc_channel_args* args,
272 grpc_pollset_set* /*interested_parties*/,
273 grpc_core::HandshakeManager* handshake_mgr) override {
274 // Instantiate TSI handshaker.
275 try_fetch_ssl_server_credentials();
276 tsi_handshaker* tsi_hs = nullptr;
277 tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker(
278 server_handshaker_factory_, &tsi_hs);
279 if (result != TSI_OK) {
280 gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.",
281 tsi_result_to_string(result));
282 return;
283 }
284 // Create handshakers.
285 handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
286 }
287
check_peer(tsi_peer peer,grpc_endpoint *,grpc_core::RefCountedPtr<grpc_auth_context> * auth_context,grpc_closure * on_peer_checked)288 void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
289 grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
290 grpc_closure* on_peer_checked) override {
291 grpc_error* error = ssl_check_peer(nullptr, &peer, auth_context);
292 tsi_peer_destruct(&peer);
293 grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
294 }
295
cmp(const grpc_security_connector * other) const296 int cmp(const grpc_security_connector* other) const override {
297 return server_security_connector_cmp(
298 static_cast<const grpc_server_security_connector*>(other));
299 }
300
301 private:
302 /* Attempts to fetch the server certificate config if a callback is available.
303 * Current certificate config will continue to be used if the callback returns
304 * an error. Returns true if new credentials were successfully loaded. */
try_fetch_ssl_server_credentials()305 bool try_fetch_ssl_server_credentials() {
306 grpc_ssl_server_certificate_config* certificate_config = nullptr;
307 bool status;
308 if (!has_cert_config_fetcher()) return false;
309
310 grpc_core::MutexLock lock(&mu_);
311 grpc_ssl_server_credentials* server_creds =
312 static_cast<grpc_ssl_server_credentials*>(this->mutable_server_creds());
313 grpc_ssl_certificate_config_reload_status cb_result =
314 server_creds->FetchCertConfig(&certificate_config);
315 if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED) {
316 gpr_log(GPR_DEBUG, "No change in SSL server credentials.");
317 status = false;
318 } else if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW) {
319 status = try_replace_server_handshaker_factory(certificate_config);
320 } else {
321 // Log error, continue using previously-loaded credentials.
322 gpr_log(GPR_ERROR,
323 "Failed fetching new server credentials, continuing to "
324 "use previously-loaded credentials.");
325 status = false;
326 }
327
328 if (certificate_config != nullptr) {
329 grpc_ssl_server_certificate_config_destroy(certificate_config);
330 }
331 return status;
332 }
333
334 /* Attempts to replace the server_handshaker_factory with a new factory using
335 * the provided grpc_ssl_server_certificate_config. Should new factory
336 * creation fail, the existing factory will not be replaced. Returns true on
337 * success (new factory created). */
try_replace_server_handshaker_factory(const grpc_ssl_server_certificate_config * config)338 bool try_replace_server_handshaker_factory(
339 const grpc_ssl_server_certificate_config* config) {
340 if (config == nullptr) {
341 gpr_log(GPR_ERROR,
342 "Server certificate config callback returned invalid (NULL) "
343 "config.");
344 return false;
345 }
346 gpr_log(GPR_DEBUG, "Using new server certificate config (%p).", config);
347
348 size_t num_alpn_protocols = 0;
349 const char** alpn_protocol_strings =
350 grpc_fill_alpn_protocol_strings(&num_alpn_protocols);
351 tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr;
352 const grpc_ssl_server_credentials* server_creds =
353 static_cast<const grpc_ssl_server_credentials*>(this->server_creds());
354 GPR_DEBUG_ASSERT(config->pem_root_certs != nullptr);
355 tsi_ssl_server_handshaker_options options;
356 options.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(
357 config->pem_key_cert_pairs, config->num_key_cert_pairs);
358 options.num_key_cert_pairs = config->num_key_cert_pairs;
359 options.pem_client_root_certs = config->pem_root_certs;
360 options.client_certificate_request =
361 grpc_get_tsi_client_certificate_request_type(
362 server_creds->config().client_certificate_request);
363 options.cipher_suites = grpc_get_ssl_cipher_suites();
364 options.alpn_protocols = alpn_protocol_strings;
365 options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
366 tsi_result result = tsi_create_ssl_server_handshaker_factory_with_options(
367 &options, &new_handshaker_factory);
368 grpc_tsi_ssl_pem_key_cert_pairs_destroy(
369 const_cast<tsi_ssl_pem_key_cert_pair*>(options.pem_key_cert_pairs),
370 options.num_key_cert_pairs);
371 gpr_free(alpn_protocol_strings);
372
373 if (result != TSI_OK) {
374 gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
375 tsi_result_to_string(result));
376 return false;
377 }
378 set_server_handshaker_factory(new_handshaker_factory);
379 return true;
380 }
381
set_server_handshaker_factory(tsi_ssl_server_handshaker_factory * new_factory)382 void set_server_handshaker_factory(
383 tsi_ssl_server_handshaker_factory* new_factory) {
384 if (server_handshaker_factory_) {
385 tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_);
386 }
387 server_handshaker_factory_ = new_factory;
388 }
389
390 grpc_core::Mutex mu_;
391 tsi_ssl_server_handshaker_factory* server_handshaker_factory_ = nullptr;
392 };
393 } // namespace
394
395 grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_ssl_channel_security_connector_create(grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,const grpc_ssl_config * config,const char * target_name,const char * overridden_target_name,tsi_ssl_session_cache * ssl_session_cache)396 grpc_ssl_channel_security_connector_create(
397 grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
398 grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
399 const grpc_ssl_config* config, const char* target_name,
400 const char* overridden_target_name,
401 tsi_ssl_session_cache* ssl_session_cache) {
402 if (config == nullptr || target_name == nullptr) {
403 gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name.");
404 return nullptr;
405 }
406
407 const char* pem_root_certs;
408 const tsi_ssl_root_certs_store* root_store;
409 if (config->pem_root_certs == nullptr) {
410 // Use default root certificates.
411 pem_root_certs = grpc_core::DefaultSslRootStore::GetPemRootCerts();
412 if (pem_root_certs == nullptr) {
413 gpr_log(GPR_ERROR, "Could not get default pem root certs.");
414 return nullptr;
415 }
416 root_store = grpc_core::DefaultSslRootStore::GetRootStore();
417 } else {
418 pem_root_certs = config->pem_root_certs;
419 root_store = nullptr;
420 }
421
422 grpc_core::RefCountedPtr<grpc_ssl_channel_security_connector> c =
423 grpc_core::MakeRefCounted<grpc_ssl_channel_security_connector>(
424 std::move(channel_creds), std::move(request_metadata_creds), config,
425 target_name, overridden_target_name);
426 const grpc_security_status result = c->InitializeHandshakerFactory(
427 config, pem_root_certs, root_store, ssl_session_cache);
428 if (result != GRPC_SECURITY_OK) {
429 return nullptr;
430 }
431 return c;
432 }
433
434 grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_ssl_server_security_connector_create(grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials)435 grpc_ssl_server_security_connector_create(
436 grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) {
437 GPR_ASSERT(server_credentials != nullptr);
438 grpc_core::RefCountedPtr<grpc_ssl_server_security_connector> c =
439 grpc_core::MakeRefCounted<grpc_ssl_server_security_connector>(
440 std::move(server_credentials));
441 const grpc_security_status retval = c->InitializeHandshakerFactory();
442 if (retval != GRPC_SECURITY_OK) {
443 return nullptr;
444 }
445 return c;
446 }
447