Debian Codegraph @

src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc

raw
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/tsi/alts/handshaker/alts_tsi_handshaker.h"
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "upb/upb.hpp"
28
29 #include <grpc/grpc_security.h>
30 #include <grpc/support/alloc.h>
31 #include <grpc/support/log.h>
32 #include <grpc/support/string_util.h>
33 #include <grpc/support/sync.h>
34 #include <grpc/support/thd_id.h>
35
36 #include "src/core/lib/gprpp/memory.h"
37 #include "src/core/lib/gprpp/sync.h"
38 #include "src/core/lib/gprpp/thd.h"
39 #include "src/core/lib/iomgr/closure.h"
40 #include "src/core/lib/slice/slice_internal.h"
41 #include "src/core/lib/surface/channel.h"
42 #include "src/core/tsi/alts/frame_protector/alts_frame_protector.h"
43 #include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
44 #include "src/core/tsi/alts/handshaker/alts_shared_resource.h"
45 #include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
46 #include "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h"
47
48 /* Main struct for ALTS TSI handshaker. */
49 struct alts_tsi_handshaker {
50 tsi_handshaker base;
51 grpc_slice target_name;
52 bool is_client;
53 bool has_sent_start_message = false;
54 bool has_created_handshaker_client = false;
55 char* handshaker_service_url;
56 grpc_pollset_set* interested_parties;
57 grpc_alts_credentials_options* options;
58 alts_handshaker_client_vtable* client_vtable_for_testing = nullptr;
59 grpc_channel* channel = nullptr;
60 bool use_dedicated_cq;
61 // mu synchronizes all fields below. Note these are the
62 // only fields that can be concurrently accessed (due to
63 // potential concurrency of tsi_handshaker_shutdown and
64 // tsi_handshaker_next).
65 grpc_core::Mutex mu;
66 alts_handshaker_client* client = nullptr;
67 // shutdown effectively follows base.handshake_shutdown,
68 // but is synchronized by the mutex of this object.
69 bool shutdown = false;
70 // Maximum frame size used by frame protector.
71 size_t max_frame_size;
72 };
73
74 /* Main struct for ALTS TSI handshaker result. */
75 typedef struct alts_tsi_handshaker_result {
76 tsi_handshaker_result base;
77 char* peer_identity;
78 char* key_data;
79 unsigned char* unused_bytes;
80 size_t unused_bytes_size;
81 grpc_slice rpc_versions;
82 bool is_client;
83 grpc_slice serialized_context;
84 // Peer's maximum frame size.
85 size_t max_frame_size;
86 } alts_tsi_handshaker_result;
87
88 static tsi_result handshaker_result_extract_peer(
89 const tsi_handshaker_result* self, tsi_peer* peer) {
90 if (self == nullptr || peer == nullptr) {
91 gpr_log(GPR_ERROR, "Invalid argument to handshaker_result_extract_peer()");
92 return TSI_INVALID_ARGUMENT;
93 }
94 alts_tsi_handshaker_result* result =
95 reinterpret_cast<alts_tsi_handshaker_result*>(
96 const_cast<tsi_handshaker_result*>(self));
97 GPR_ASSERT(kTsiAltsNumOfPeerProperties == 5);
98 tsi_result ok = tsi_construct_peer(kTsiAltsNumOfPeerProperties, peer);
99 int index = 0;
100 if (ok != TSI_OK) {
101 gpr_log(GPR_ERROR, "Failed to construct tsi peer");
102 return ok;
103 }
104 GPR_ASSERT(&peer->properties[index] != nullptr);
105 ok = tsi_construct_string_peer_property_from_cstring(
106 TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_ALTS_CERTIFICATE_TYPE,
107 &peer->properties[index]);
108 if (ok != TSI_OK) {
109 tsi_peer_destruct(peer);
110 gpr_log(GPR_ERROR, "Failed to set tsi peer property");
111 return ok;
112 }
113 index++;
114 GPR_ASSERT(&peer->properties[index] != nullptr);
115 ok = tsi_construct_string_peer_property_from_cstring(
116 TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, result->peer_identity,
117 &peer->properties[index]);
118 if (ok != TSI_OK) {
119 tsi_peer_destruct(peer);
120 gpr_log(GPR_ERROR, "Failed to set tsi peer property");
121 }
122 index++;
123 GPR_ASSERT(&peer->properties[index] != nullptr);
124 ok = tsi_construct_string_peer_property(
125 TSI_ALTS_RPC_VERSIONS,
126 reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->rpc_versions)),
127 GRPC_SLICE_LENGTH(result->rpc_versions), &peer->properties[index]);
128 if (ok != TSI_OK) {
129 tsi_peer_destruct(peer);
130 gpr_log(GPR_ERROR, "Failed to set tsi peer property");
131 }
132 index++;
133 GPR_ASSERT(&peer->properties[index] != nullptr);
134 ok = tsi_construct_string_peer_property(
135 TSI_ALTS_CONTEXT,
136 reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->serialized_context)),
137 GRPC_SLICE_LENGTH(result->serialized_context), &peer->properties[index]);
138 if (ok != TSI_OK) {
139 tsi_peer_destruct(peer);
140 gpr_log(GPR_ERROR, "Failed to set tsi peer property");
141 }
142 index++;
143 GPR_ASSERT(&peer->properties[index] != nullptr);
144 ok = tsi_construct_string_peer_property_from_cstring(
145 TSI_SECURITY_LEVEL_PEER_PROPERTY,
146 tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY),
147 &peer->properties[index]);
148 if (ok != TSI_OK) {
149 tsi_peer_destruct(peer);
150 gpr_log(GPR_ERROR, "Failed to set tsi peer property");
151 }
152 GPR_ASSERT(++index == kTsiAltsNumOfPeerProperties);
153 return ok;
154 }
155
156 static tsi_result handshaker_result_get_frame_protector_type(
157 const tsi_handshaker_result* /*self*/,
158 tsi_frame_protector_type* frame_protector_type) {
159 *frame_protector_type = TSI_FRAME_PROTECTOR_NORMAL_OR_ZERO_COPY;
160 return TSI_OK;
161 }
162
163 static tsi_result handshaker_result_create_zero_copy_grpc_protector(
164 const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
165 tsi_zero_copy_grpc_protector** protector) {
166 if (self == nullptr || protector == nullptr) {
167 gpr_log(GPR_ERROR,
168 "Invalid arguments to create_zero_copy_grpc_protector()");
169 return TSI_INVALID_ARGUMENT;
170 }
171 alts_tsi_handshaker_result* result =
172 reinterpret_cast<alts_tsi_handshaker_result*>(
173 const_cast<tsi_handshaker_result*>(self));
174
175 // In case the peer does not send max frame size (e.g. peer is gRPC Go or
176 // peer uses an old binary), the negotiated frame size is set to
177 // kTsiAltsMinFrameSize (ignoring max_output_protected_frame_size value if
178 // present). Otherwise, it is based on peer and user specified max frame
179 // size (if present).
180 size_t max_frame_size = kTsiAltsMinFrameSize;
181 if (result->max_frame_size) {
182 size_t peer_max_frame_size = result->max_frame_size;
183 max_frame_size = std::min<size_t>(peer_max_frame_size,
184 max_output_protected_frame_size == nullptr
185 ? kTsiAltsMaxFrameSize
186 : *max_output_protected_frame_size);
187 max_frame_size = std::max<size_t>(max_frame_size, kTsiAltsMinFrameSize);
188 }
189 max_output_protected_frame_size = &max_frame_size;
190 gpr_log(GPR_DEBUG,
191 "After Frame Size Negotiation, maximum frame size used by frame "
192 "protector equals %zu",
193 *max_output_protected_frame_size);
194 tsi_result ok = alts_zero_copy_grpc_protector_create(
195 reinterpret_cast<const uint8_t*>(result->key_data),
196 kAltsAes128GcmRekeyKeyLength, /*is_rekey=*/true, result->is_client,
197 /*is_integrity_only=*/false, /*enable_extra_copy=*/false,
198 max_output_protected_frame_size, protector);
199 if (ok != TSI_OK) {
200 gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector");
201 }
202 return ok;
203 }
204
205 static tsi_result handshaker_result_create_frame_protector(
206 const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
207 tsi_frame_protector** protector) {
208 if (self == nullptr || protector == nullptr) {
209 gpr_log(GPR_ERROR,
210 "Invalid arguments to handshaker_result_create_frame_protector()");
211 return TSI_INVALID_ARGUMENT;
212 }
213 alts_tsi_handshaker_result* result =
214 reinterpret_cast<alts_tsi_handshaker_result*>(
215 const_cast<tsi_handshaker_result*>(self));
216 tsi_result ok = alts_create_frame_protector(
217 reinterpret_cast<const uint8_t*>(result->key_data),
218 kAltsAes128GcmRekeyKeyLength, result->is_client, /*is_rekey=*/true,
219 max_output_protected_frame_size, protector);
220 if (ok != TSI_OK) {
221 gpr_log(GPR_ERROR, "Failed to create frame protector");
222 }
223 return ok;
224 }
225
226 static tsi_result handshaker_result_get_unused_bytes(
227 const tsi_handshaker_result* self, const unsigned char** bytes,
228 size_t* bytes_size) {
229 if (self == nullptr || bytes == nullptr || bytes_size == nullptr) {
230 gpr_log(GPR_ERROR,
231 "Invalid arguments to handshaker_result_get_unused_bytes()");
232 return TSI_INVALID_ARGUMENT;
233 }
234 alts_tsi_handshaker_result* result =
235 reinterpret_cast<alts_tsi_handshaker_result*>(
236 const_cast<tsi_handshaker_result*>(self));
237 *bytes = result->unused_bytes;
238 *bytes_size = result->unused_bytes_size;
239 return TSI_OK;
240 }
241
242 static void handshaker_result_destroy(tsi_handshaker_result* self) {
243 if (self == nullptr) {
244 return;
245 }
246 alts_tsi_handshaker_result* result =
247 reinterpret_cast<alts_tsi_handshaker_result*>(
248 const_cast<tsi_handshaker_result*>(self));
249 gpr_free(result->peer_identity);
250 gpr_free(result->key_data);
251 gpr_free(result->unused_bytes);
252 grpc_core::CSliceUnref(result->rpc_versions);
253 grpc_core::CSliceUnref(result->serialized_context);
254 gpr_free(result);
255 }
256
257 static const tsi_handshaker_result_vtable result_vtable = {
258 handshaker_result_extract_peer,
259 handshaker_result_get_frame_protector_type,
260 handshaker_result_create_zero_copy_grpc_protector,
261 handshaker_result_create_frame_protector,
262 handshaker_result_get_unused_bytes,
263 handshaker_result_destroy};
264
265 tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
266 bool is_client,
267 tsi_handshaker_result** result) {
268 if (result == nullptr || resp == nullptr) {
269 gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()");
270 return TSI_INVALID_ARGUMENT;
271 }
272 const grpc_gcp_HandshakerResult* hresult =
273 grpc_gcp_HandshakerResp_result(resp);
274 const grpc_gcp_Identity* identity =
275 grpc_gcp_HandshakerResult_peer_identity(hresult);
276 if (identity == nullptr) {
277 gpr_log(GPR_ERROR, "Invalid identity");
278 return TSI_FAILED_PRECONDITION;
279 }
280 upb_StringView peer_service_account =
281 grpc_gcp_Identity_service_account(identity);
282 if (peer_service_account.size == 0) {
283 gpr_log(GPR_ERROR, "Invalid peer service account");
284 return TSI_FAILED_PRECONDITION;
285 }
286 upb_StringView key_data = grpc_gcp_HandshakerResult_key_data(hresult);
287 if (key_data.size < kAltsAes128GcmRekeyKeyLength) {
288 gpr_log(GPR_ERROR, "Bad key length");
289 return TSI_FAILED_PRECONDITION;
290 }
291 const grpc_gcp_RpcProtocolVersions* peer_rpc_version =
292 grpc_gcp_HandshakerResult_peer_rpc_versions(hresult);
293 if (peer_rpc_version == nullptr) {
294 gpr_log(GPR_ERROR, "Peer does not set RPC protocol versions.");
295 return TSI_FAILED_PRECONDITION;
296 }
297 upb_StringView application_protocol =
298 grpc_gcp_HandshakerResult_application_protocol(hresult);
299 if (application_protocol.size == 0) {
300 gpr_log(GPR_ERROR, "Invalid application protocol");
301 return TSI_FAILED_PRECONDITION;
302 }
303 upb_StringView record_protocol =
304 grpc_gcp_HandshakerResult_record_protocol(hresult);
305 if (record_protocol.size == 0) {
306 gpr_log(GPR_ERROR, "Invalid record protocol");
307 return TSI_FAILED_PRECONDITION;
308 }
309 const grpc_gcp_Identity* local_identity =
310 grpc_gcp_HandshakerResult_local_identity(hresult);
311 if (local_identity == nullptr) {
312 gpr_log(GPR_ERROR, "Invalid local identity");
313 return TSI_FAILED_PRECONDITION;
314 }
315 upb_StringView local_service_account =
316 grpc_gcp_Identity_service_account(local_identity);
317 // We don't check if local service account is empty here
318 // because local identity could be empty in certain situations.
319 alts_tsi_handshaker_result* sresult =
320 grpc_core::Zalloc<alts_tsi_handshaker_result>();
321 sresult->key_data =
322 static_cast<char*>(gpr_zalloc(kAltsAes128GcmRekeyKeyLength));
323 memcpy(sresult->key_data, key_data.data, kAltsAes128GcmRekeyKeyLength);
324 sresult->peer_identity =
325 static_cast<char*>(gpr_zalloc(peer_service_account.size + 1));
326 memcpy(sresult->peer_identity, peer_service_account.data,
327 peer_service_account.size);
328 sresult->max_frame_size = grpc_gcp_HandshakerResult_max_frame_size(hresult);
329 upb::Arena rpc_versions_arena;
330 bool serialized = grpc_gcp_rpc_protocol_versions_encode(
331 peer_rpc_version, rpc_versions_arena.ptr(), &sresult->rpc_versions);
332 if (!serialized) {
333 gpr_log(GPR_ERROR, "Failed to serialize peer's RPC protocol versions.");
334 return TSI_FAILED_PRECONDITION;
335 }
336 upb::Arena context_arena;
337 grpc_gcp_AltsContext* context = grpc_gcp_AltsContext_new(context_arena.ptr());
338 grpc_gcp_AltsContext_set_application_protocol(context, application_protocol);
339 grpc_gcp_AltsContext_set_record_protocol(context, record_protocol);
340 // ALTS currently only supports the security level of 2,
341 // which is "grpc_gcp_INTEGRITY_AND_PRIVACY".
342 grpc_gcp_AltsContext_set_security_level(context, 2);
343 grpc_gcp_AltsContext_set_peer_service_account(context, peer_service_account);
344 grpc_gcp_AltsContext_set_local_service_account(context,
345 local_service_account);
346 grpc_gcp_AltsContext_set_peer_rpc_versions(
347 context, const_cast<grpc_gcp_RpcProtocolVersions*>(peer_rpc_version));
348 grpc_gcp_Identity* peer_identity = const_cast<grpc_gcp_Identity*>(identity);
349 if (peer_identity == nullptr) {
350 gpr_log(GPR_ERROR, "Null peer identity in ALTS context.");
351 return TSI_FAILED_PRECONDITION;
352 }
353 if (grpc_gcp_Identity_has_attributes(identity)) {
354 size_t iter = kUpb_Map_Begin;
355 grpc_gcp_Identity_AttributesEntry* peer_attributes_entry =
356 grpc_gcp_Identity_attributes_nextmutable(peer_identity, &iter);
357 while (peer_attributes_entry != nullptr) {
358 upb_StringView key = grpc_gcp_Identity_AttributesEntry_key(
359 const_cast<grpc_gcp_Identity_AttributesEntry*>(
360 peer_attributes_entry));
361 upb_StringView val = grpc_gcp_Identity_AttributesEntry_value(
362 const_cast<grpc_gcp_Identity_AttributesEntry*>(
363 peer_attributes_entry));
364 grpc_gcp_AltsContext_peer_attributes_set(context, key, val,
365 context_arena.ptr());
366 peer_attributes_entry =
367 grpc_gcp_Identity_attributes_nextmutable(peer_identity, &iter);
368 }
369 }
370 size_t serialized_ctx_length;
371 char* serialized_ctx = grpc_gcp_AltsContext_serialize(
372 context, context_arena.ptr(), &serialized_ctx_length);
373 if (serialized_ctx == nullptr) {
374 gpr_log(GPR_ERROR, "Failed to serialize peer's ALTS context.");
375 return TSI_FAILED_PRECONDITION;
376 }
377 sresult->serialized_context =
378 grpc_slice_from_copied_buffer(serialized_ctx, serialized_ctx_length);
379 sresult->is_client = is_client;
380 sresult->base.vtable = &result_vtable;
381 *result = &sresult->base;
382 return TSI_OK;
383 }
384
385 /* gRPC provided callback used when gRPC thread model is applied. */
386 static void on_handshaker_service_resp_recv(void* arg,
387 grpc_error_handle error) {
388 alts_handshaker_client* client = static_cast<alts_handshaker_client*>(arg);
389 if (client == nullptr) {
390 gpr_log(GPR_ERROR, "ALTS handshaker client is nullptr");
391 return;
392 }
393 bool success = true;
394 if (!error.ok()) {
395 gpr_log(GPR_INFO,
396 "ALTS handshaker on_handshaker_service_resp_recv error: %s",
397 grpc_core::StatusToString(error).c_str());
398 success = false;
399 }
400 alts_handshaker_client_handle_response(client, success);
401 }
402
403 /* gRPC provided callback used when dedicatd CQ and thread are used.
404 * It serves to safely bring the control back to application. */
405 static void on_handshaker_service_resp_recv_dedicated(
406 void* arg, grpc_error_handle /*error*/) {
407 alts_shared_resource_dedicated* resource =
408 grpc_alts_get_shared_resource_dedicated();
409 grpc_cq_end_op(
410 resource->cq, arg, absl::OkStatus(),
411 [](void* /*done_arg*/, grpc_cq_completion* /*storage*/) {}, nullptr,
412 &resource->storage);
413 }
414
415 /* Returns TSI_OK if and only if no error is encountered. */
416 static tsi_result alts_tsi_handshaker_continue_handshaker_next(
417 alts_tsi_handshaker* handshaker, const unsigned char* received_bytes,
418 size_t received_bytes_size, tsi_handshaker_on_next_done_cb cb,
419 void* user_data, std::string* error) {
420 if (!handshaker->has_created_handshaker_client) {
421 if (handshaker->channel == nullptr) {
422 grpc_alts_shared_resource_dedicated_start(
423 handshaker->handshaker_service_url);
424 handshaker->interested_parties =
425 grpc_alts_get_shared_resource_dedicated()->interested_parties;
426 GPR_ASSERT(handshaker->interested_parties != nullptr);
427 }
428 grpc_iomgr_cb_func grpc_cb = handshaker->channel == nullptr
429 ? on_handshaker_service_resp_recv_dedicated
430 : on_handshaker_service_resp_recv;
431 grpc_channel* channel =
432 handshaker->channel == nullptr
433 ? grpc_alts_get_shared_resource_dedicated()->channel
434 : handshaker->channel;
435 alts_handshaker_client* client = alts_grpc_handshaker_client_create(
436 handshaker, channel, handshaker->handshaker_service_url,
437 handshaker->interested_parties, handshaker->options,
438 handshaker->target_name, grpc_cb, cb, user_data,
439 handshaker->client_vtable_for_testing, handshaker->is_client,
440 handshaker->max_frame_size, error);
441 if (client == nullptr) {
442 gpr_log(GPR_ERROR, "Failed to create ALTS handshaker client");
443 if (error != nullptr) *error = "Failed to create ALTS handshaker client";
444 return TSI_FAILED_PRECONDITION;
445 }
446 {
447 grpc_core::MutexLock lock(&handshaker->mu);
448 GPR_ASSERT(handshaker->client == nullptr);
449 handshaker->client = client;
450 if (handshaker->shutdown) {
451 gpr_log(GPR_INFO, "TSI handshake shutdown");
452 if (error != nullptr) *error = "TSI handshaker shutdown";
453 return TSI_HANDSHAKE_SHUTDOWN;
454 }
455 }
456 handshaker->has_created_handshaker_client = true;
457 }
458 if (handshaker->channel == nullptr &&
459 handshaker->client_vtable_for_testing == nullptr) {
460 GPR_ASSERT(grpc_cq_begin_op(grpc_alts_get_shared_resource_dedicated()->cq,
461 handshaker->client));
462 }
463 grpc_slice slice = (received_bytes == nullptr || received_bytes_size == 0)
464 ? grpc_empty_slice()
465 : grpc_slice_from_copied_buffer(
466 reinterpret_cast<const char*>(received_bytes),
467 received_bytes_size);
468 tsi_result ok = TSI_OK;
469 if (!handshaker->has_sent_start_message) {
470 handshaker->has_sent_start_message = true;
471 ok = handshaker->is_client
472 ? alts_handshaker_client_start_client(handshaker->client)
473 : alts_handshaker_client_start_server(handshaker->client, &slice);
474 // It's unsafe for the current thread to access any state in handshaker
475 // at this point, since alts_handshaker_client_start_client/server
476 // have potentially just started an op batch on the handshake call.
477 // The completion callback for that batch is unsynchronized and so
478 // can invoke the TSI next API callback from any thread, at which point
479 // there is nothing taking ownership of this handshaker to prevent it
480 // from being destroyed.
481 } else {
482 ok = alts_handshaker_client_next(handshaker->client, &slice);
483 }
484 grpc_core::CSliceUnref(slice);
485 return ok;
486 }
487
488 struct alts_tsi_handshaker_continue_handshaker_next_args {
489 alts_tsi_handshaker* handshaker;
490 std::unique_ptr<unsigned char> received_bytes;
491 size_t received_bytes_size;
492 tsi_handshaker_on_next_done_cb cb;
493 void* user_data;
494 grpc_closure closure;
495 std::string* error = nullptr;
496 };
497
498 static void alts_tsi_handshaker_create_channel(
499 void* arg, grpc_error_handle /* unused_error */) {
500 alts_tsi_handshaker_continue_handshaker_next_args* next_args =
501 static_cast<alts_tsi_handshaker_continue_handshaker_next_args*>(arg);
502 alts_tsi_handshaker* handshaker = next_args->handshaker;
503 GPR_ASSERT(handshaker->channel == nullptr);
504 grpc_channel_credentials* creds = grpc_insecure_credentials_create();
505 // Disable retries so that we quickly get a signal when the
506 // handshake server is not reachable.
507 grpc_arg disable_retries_arg = grpc_channel_arg_integer_create(
508 const_cast<char*>(GRPC_ARG_ENABLE_RETRIES), 0);
509 grpc_channel_args args = {1, &disable_retries_arg};
510 handshaker->channel = grpc_channel_create(
511 next_args->handshaker->handshaker_service_url, creds, &args);
512 grpc_channel_credentials_release(creds);
513 tsi_result continue_next_result =
514 alts_tsi_handshaker_continue_handshaker_next(
515 handshaker, next_args->received_bytes.get(),
516 next_args->received_bytes_size, next_args->cb, next_args->user_data,
517 next_args->error);
518 if (continue_next_result != TSI_OK) {
519 next_args->cb(continue_next_result, next_args->user_data, nullptr, 0,
520 nullptr);
521 }
522 delete next_args;
523 }
524
525 static tsi_result handshaker_next(
526 tsi_handshaker* self, const unsigned char* received_bytes,
527 size_t received_bytes_size, const unsigned char** /*bytes_to_send*/,
528 size_t* /*bytes_to_send_size*/, tsi_handshaker_result** /*result*/,
529 tsi_handshaker_on_next_done_cb cb, void* user_data, std::string* error) {
530 if (self == nullptr || cb == nullptr) {
531 gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()");
532 if (error != nullptr) *error = "invalid argument";
533 return TSI_INVALID_ARGUMENT;
534 }
535 alts_tsi_handshaker* handshaker =
536 reinterpret_cast<alts_tsi_handshaker*>(self);
537 {
538 grpc_core::MutexLock lock(&handshaker->mu);
539 if (handshaker->shutdown) {
540 gpr_log(GPR_INFO, "TSI handshake shutdown");
541 if (error != nullptr) *error = "handshake shutdown";
542 return TSI_HANDSHAKE_SHUTDOWN;
543 }
544 }
545 if (handshaker->channel == nullptr && !handshaker->use_dedicated_cq) {
546 alts_tsi_handshaker_continue_handshaker_next_args* args =
547 new alts_tsi_handshaker_continue_handshaker_next_args();
548 args->handshaker = handshaker;
549 args->received_bytes = nullptr;
550 args->received_bytes_size = received_bytes_size;
551 args->error = error;
552 if (received_bytes_size > 0) {
553 args->received_bytes = std::unique_ptr<unsigned char>(
554 static_cast<unsigned char*>(gpr_zalloc(received_bytes_size)));
555 memcpy(args->received_bytes.get(), received_bytes, received_bytes_size);
556 }
557 args->cb = cb;
558 args->user_data = user_data;
559 GRPC_CLOSURE_INIT(&args->closure, alts_tsi_handshaker_create_channel, args,
560 grpc_schedule_on_exec_ctx);
561 // We continue this handshaker_next call at the bottom of the ExecCtx just
562 // so that we can invoke grpc_channel_create at the bottom of the call
563 // stack. Doing so avoids potential lock cycles between g_init_mu and other
564 // mutexes within core that might be held on the current call stack
565 // (note that g_init_mu gets acquired during channel creation).
566 grpc_core::ExecCtx::Run(DEBUG_LOCATION, &args->closure, absl::OkStatus());
567 } else {
568 tsi_result ok = alts_tsi_handshaker_continue_handshaker_next(
569 handshaker, received_bytes, received_bytes_size, cb, user_data, error);
570 if (ok != TSI_OK) {
571 gpr_log(GPR_ERROR, "Failed to schedule ALTS handshaker requests");
572 return ok;
573 }
574 }
575 return TSI_ASYNC;
576 }
577
578 /*
579 * This API will be invoked by a non-gRPC application, and an ExecCtx needs
580 * to be explicitly created in order to invoke ALTS handshaker client API's
581 * that assumes the caller is inside gRPC core.
582 */
583 static tsi_result handshaker_next_dedicated(
584 tsi_handshaker* self, const unsigned char* received_bytes,
585 size_t received_bytes_size, const unsigned char** bytes_to_send,
586 size_t* bytes_to_send_size, tsi_handshaker_result** result,
587 tsi_handshaker_on_next_done_cb cb, void* user_data, std::string* error) {
588 grpc_core::ExecCtx exec_ctx;
589 return handshaker_next(self, received_bytes, received_bytes_size,
590 bytes_to_send, bytes_to_send_size, result, cb,
591 user_data, error);
592 }
593
594 static void handshaker_shutdown(tsi_handshaker* self) {
595 GPR_ASSERT(self != nullptr);
596 alts_tsi_handshaker* handshaker =
597 reinterpret_cast<alts_tsi_handshaker*>(self);
598 grpc_core::MutexLock lock(&handshaker->mu);
599 if (handshaker->shutdown) {
600 return;
601 }
602 if (handshaker->client != nullptr) {
603 alts_handshaker_client_shutdown(handshaker->client);
604 }
605 handshaker->shutdown = true;
606 }
607
608 static void handshaker_destroy(tsi_handshaker* self) {
609 if (self == nullptr) {
610 return;
611 }
612 alts_tsi_handshaker* handshaker =
613 reinterpret_cast<alts_tsi_handshaker*>(self);
614 alts_handshaker_client_destroy(handshaker->client);
615 grpc_core::CSliceUnref(handshaker->target_name);
616 grpc_alts_credentials_options_destroy(handshaker->options);
617 if (handshaker->channel != nullptr) {
618 grpc_channel_destroy_internal(handshaker->channel);
619 }
620 gpr_free(handshaker->handshaker_service_url);
621 delete handshaker;
622 }
623
624 static const tsi_handshaker_vtable handshaker_vtable = {
625 nullptr, nullptr,
626 nullptr, nullptr,
627 nullptr, handshaker_destroy,
628 handshaker_next, handshaker_shutdown};
629
630 static const tsi_handshaker_vtable handshaker_vtable_dedicated = {
631 nullptr,
632 nullptr,
633 nullptr,
634 nullptr,
635 nullptr,
636 handshaker_destroy,
637 handshaker_next_dedicated,
638 handshaker_shutdown};
639
640 bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker) {
641 GPR_ASSERT(handshaker != nullptr);
642 grpc_core::MutexLock lock(&handshaker->mu);
643 return handshaker->shutdown;
644 }
645
646 tsi_result alts_tsi_handshaker_create(
647 const grpc_alts_credentials_options* options, const char* target_name,
648 const char* handshaker_service_url, bool is_client,
649 grpc_pollset_set* interested_parties, tsi_handshaker** self,
650 size_t user_specified_max_frame_size) {
651 if (handshaker_service_url == nullptr || self == nullptr ||
652 options == nullptr || (is_client && target_name == nullptr)) {
653 gpr_log(GPR_ERROR, "Invalid arguments to alts_tsi_handshaker_create()");
654 return TSI_INVALID_ARGUMENT;
655 }
656 bool use_dedicated_cq = interested_parties == nullptr;
657 alts_tsi_handshaker* handshaker = new alts_tsi_handshaker();
658 memset(&handshaker->base, 0, sizeof(handshaker->base));
659 handshaker->base.vtable =
660 use_dedicated_cq ? &handshaker_vtable_dedicated : &handshaker_vtable;
661 handshaker->target_name = target_name == nullptr
662 ? grpc_empty_slice()
663 : grpc_slice_from_static_string(target_name);
664 handshaker->is_client = is_client;
665 handshaker->handshaker_service_url = gpr_strdup(handshaker_service_url);
666 handshaker->interested_parties = interested_parties;
667 handshaker->options = grpc_alts_credentials_options_copy(options);
668 handshaker->use_dedicated_cq = use_dedicated_cq;
669 handshaker->max_frame_size = user_specified_max_frame_size != 0
670 ? user_specified_max_frame_size
671 : kTsiAltsMaxFrameSize;
672 *self = &handshaker->base;
673 return TSI_OK;
674 }
675
676 void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* result,
677 grpc_slice* recv_bytes,
678 size_t bytes_consumed) {
679 GPR_ASSERT(recv_bytes != nullptr && result != nullptr);
680 if (GRPC_SLICE_LENGTH(*recv_bytes) == bytes_consumed) {
681 return;
682 }
683 alts_tsi_handshaker_result* sresult =
684 reinterpret_cast<alts_tsi_handshaker_result*>(result);
685 sresult->unused_bytes_size = GRPC_SLICE_LENGTH(*recv_bytes) - bytes_consumed;
686 sresult->unused_bytes =
687 static_cast<unsigned char*>(gpr_zalloc(sresult->unused_bytes_size));
688 memcpy(sresult->unused_bytes,
689 GRPC_SLICE_START_PTR(*recv_bytes) + bytes_consumed,
690 sresult->unused_bytes_size);
691 }
692
693 namespace grpc_core {
694 namespace internal {
695
696 bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
697 alts_tsi_handshaker* handshaker) {
698 GPR_ASSERT(handshaker != nullptr);
699 return handshaker->has_sent_start_message;
700 }
701
702 void alts_tsi_handshaker_set_client_vtable_for_testing(
703 alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable) {
704 GPR_ASSERT(handshaker != nullptr);
705 handshaker->client_vtable_for_testing = vtable;
706 }
707
708 bool alts_tsi_handshaker_get_is_client_for_testing(
709 alts_tsi_handshaker* handshaker) {
710 GPR_ASSERT(handshaker != nullptr);
711 return handshaker->is_client;
712 }
713
714 alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing(
715 alts_tsi_handshaker* handshaker) {
716 return handshaker->client;
717 }
718
719 } // namespace internal
720 } // namespace grpc_core