1 //
2 //
3 // Copyright 2015 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/cpp/client/secure_credentials.h"
20
21 #include <grpc/event_engine/event_engine.h>
22 #include <grpc/grpc.h>
23 #include <grpc/grpc_security_constants.h>
24 #include <grpc/slice.h>
25 #include <grpc/support/json.h>
26 #include <grpc/support/string_util.h>
27 #include <grpc/support/time.h>
28 #include <grpcpp/channel.h>
29 #include <grpcpp/impl/grpc_library.h>
30 #include <grpcpp/security/tls_credentials_options.h>
31 #include <grpcpp/support/channel_arguments.h>
32 #include <grpcpp/support/config.h>
33 #include <grpcpp/support/slice.h>
34 #include <grpcpp/support/status.h>
35 #include <string.h>
36
37 #include <map>
38 #include <memory>
39 #include <utility>
40
41 #include "absl/log/check.h"
42 #include "absl/log/log.h"
43 #include "absl/status/status.h"
44 #include "absl/status/statusor.h"
45 #include "absl/strings/str_join.h"
46 #include "absl/types/optional.h"
47 #include "src/core/lib/event_engine/default_event_engine.h"
48 #include "src/core/lib/security/util/json_util.h"
49 #include "src/core/util/env.h"
50 #include "src/core/util/json/json.h"
51 #include "src/core/util/json/json_reader.h"
52 #include "src/core/util/load_file.h"
53 #include "src/cpp/common/secure_auth_context.h"
54 #include "src/cpp/server/thread_pool_interface.h"
55
56 namespace grpc {
57
58 namespace {
59 class WrappedCallCredentials : public CallCredentials {
60 public:
WrappedCallCredentials(grpc_call_credentials * creds)61 explicit WrappedCallCredentials(grpc_call_credentials* creds)
62 : CallCredentials(creds) {}
63 };
64
WrapCallCredentials(grpc_call_credentials * creds)65 std::shared_ptr<WrappedCallCredentials> WrapCallCredentials(
66 grpc_call_credentials* creds) {
67 return creds == nullptr ? nullptr
68 : std::make_shared<WrappedCallCredentials>(creds);
69 }
70
71 class WrappedChannelCredentials final : public ChannelCredentials {
72 public:
WrappedChannelCredentials(grpc_channel_credentials * c_creds)73 explicit WrappedChannelCredentials(grpc_channel_credentials* c_creds)
74 : ChannelCredentials(c_creds) {}
75 };
76
WrapChannelCredentials(grpc_channel_credentials * creds)77 std::shared_ptr<WrappedChannelCredentials> WrapChannelCredentials(
78 grpc_channel_credentials* creds) {
79 return creds == nullptr ? nullptr
80 : std::make_shared<WrappedChannelCredentials>(creds);
81 }
82
83 } // namespace
84
GoogleDefaultCredentials()85 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
86 grpc::internal::GrpcLibrary init; // To call grpc_init().
87 return WrapChannelCredentials(
88 grpc_google_default_credentials_create(nullptr));
89 }
90
ExternalAccountCredentials(const grpc::string & json_string,const std::vector<grpc::string> & scopes)91 std::shared_ptr<CallCredentials> ExternalAccountCredentials(
92 const grpc::string& json_string, const std::vector<grpc::string>& scopes) {
93 grpc::internal::GrpcLibrary init; // To call grpc_init().
94 return WrapCallCredentials(grpc_external_account_credentials_create(
95 json_string.c_str(), absl::StrJoin(scopes, ",").c_str()));
96 }
97
98 // Builds SSL Credentials given SSL specific options
SslCredentials(const SslCredentialsOptions & options)99 std::shared_ptr<ChannelCredentials> SslCredentials(
100 const SslCredentialsOptions& options) {
101 grpc::internal::GrpcLibrary init; // To call grpc_init().
102 grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
103 options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};
104 return WrapChannelCredentials(grpc_ssl_credentials_create(
105 options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
106 options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr,
107 nullptr));
108 }
109
110 namespace experimental {
111
112 namespace {
113
ClearStsCredentialsOptions(StsCredentialsOptions * options)114 void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
115 if (options == nullptr) return;
116 options->token_exchange_service_uri.clear();
117 options->resource.clear();
118 options->audience.clear();
119 options->scope.clear();
120 options->requested_token_type.clear();
121 options->subject_token_path.clear();
122 options->subject_token_type.clear();
123 options->actor_token_path.clear();
124 options->actor_token_type.clear();
125 }
126
127 } // namespace
128
129 // Builds STS credentials options from JSON.
StsCredentialsOptionsFromJson(const std::string & json_string,StsCredentialsOptions * options)130 grpc::Status StsCredentialsOptionsFromJson(const std::string& json_string,
131 StsCredentialsOptions* options) {
132 if (options == nullptr) {
133 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
134 "options cannot be nullptr.");
135 }
136 ClearStsCredentialsOptions(options);
137 auto json = grpc_core::JsonParse(json_string.c_str());
138 if (!json.ok() || json->type() != grpc_core::Json::Type::kObject) {
139 return grpc::Status(
140 grpc::StatusCode::INVALID_ARGUMENT,
141 absl::StrCat("Invalid json: ", json.status().ToString()));
142 }
143
144 // Required fields.
145 const char* value = grpc_json_get_string_property(
146 *json, "token_exchange_service_uri", nullptr);
147 if (value == nullptr) {
148 ClearStsCredentialsOptions(options);
149 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
150 "token_exchange_service_uri must be specified.");
151 }
152 options->token_exchange_service_uri.assign(value);
153 value = grpc_json_get_string_property(*json, "subject_token_path", nullptr);
154 if (value == nullptr) {
155 ClearStsCredentialsOptions(options);
156 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
157 "subject_token_path must be specified.");
158 }
159 options->subject_token_path.assign(value);
160 value = grpc_json_get_string_property(*json, "subject_token_type", nullptr);
161 if (value == nullptr) {
162 ClearStsCredentialsOptions(options);
163 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
164 "subject_token_type must be specified.");
165 }
166 options->subject_token_type.assign(value);
167
168 // Optional fields.
169 value = grpc_json_get_string_property(*json, "resource", nullptr);
170 if (value != nullptr) options->resource.assign(value);
171 value = grpc_json_get_string_property(*json, "audience", nullptr);
172 if (value != nullptr) options->audience.assign(value);
173 value = grpc_json_get_string_property(*json, "scope", nullptr);
174 if (value != nullptr) options->scope.assign(value);
175 value = grpc_json_get_string_property(*json, "requested_token_type", nullptr);
176 if (value != nullptr) options->requested_token_type.assign(value);
177 value = grpc_json_get_string_property(*json, "actor_token_path", nullptr);
178 if (value != nullptr) options->actor_token_path.assign(value);
179 value = grpc_json_get_string_property(*json, "actor_token_type", nullptr);
180 if (value != nullptr) options->actor_token_type.assign(value);
181
182 return grpc::Status();
183 }
184
185 // Builds STS credentials Options from the $STS_CREDENTIALS env var.
StsCredentialsOptionsFromEnv(StsCredentialsOptions * options)186 grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options) {
187 if (options == nullptr) {
188 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
189 "options cannot be nullptr.");
190 }
191 ClearStsCredentialsOptions(options);
192 auto sts_creds_path = grpc_core::GetEnv("STS_CREDENTIALS");
193 if (!sts_creds_path.has_value()) {
194 return grpc::Status(grpc::StatusCode::NOT_FOUND,
195 "STS_CREDENTIALS environment variable not set.");
196 }
197 auto json_slice =
198 grpc_core::LoadFile(*sts_creds_path, /*add_null_terminator=*/true);
199 if (!json_slice.ok()) {
200 return grpc::Status(grpc::StatusCode::NOT_FOUND,
201 json_slice.status().ToString());
202 }
203 return StsCredentialsOptionsFromJson(json_slice->as_string_view().data(),
204 options);
205 }
206
207 // C++ to Core STS Credentials options.
StsCredentialsCppToCoreOptions(const StsCredentialsOptions & options)208 grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
209 const StsCredentialsOptions& options) {
210 grpc_sts_credentials_options opts;
211 memset(&opts, 0, sizeof(opts));
212 opts.token_exchange_service_uri = options.token_exchange_service_uri.c_str();
213 opts.resource = options.resource.c_str();
214 opts.audience = options.audience.c_str();
215 opts.scope = options.scope.c_str();
216 opts.requested_token_type = options.requested_token_type.c_str();
217 opts.subject_token_path = options.subject_token_path.c_str();
218 opts.subject_token_type = options.subject_token_type.c_str();
219 opts.actor_token_path = options.actor_token_path.c_str();
220 opts.actor_token_type = options.actor_token_type.c_str();
221 return opts;
222 }
223
224 // Builds STS credentials.
StsCredentials(const StsCredentialsOptions & options)225 std::shared_ptr<CallCredentials> StsCredentials(
226 const StsCredentialsOptions& options) {
227 auto opts = StsCredentialsCppToCoreOptions(options);
228 return WrapCallCredentials(grpc_sts_credentials_create(&opts, nullptr));
229 }
230
231 // Builds ALTS Credentials given ALTS specific options
AltsCredentials(const AltsCredentialsOptions & options)232 std::shared_ptr<ChannelCredentials> AltsCredentials(
233 const AltsCredentialsOptions& options) {
234 grpc::internal::GrpcLibrary init; // To call grpc_init().
235 grpc_alts_credentials_options* c_options =
236 grpc_alts_credentials_client_options_create();
237 for (const auto& service_account : options.target_service_accounts) {
238 grpc_alts_credentials_client_options_add_target_service_account(
239 c_options, service_account.c_str());
240 }
241 grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
242 grpc_alts_credentials_options_destroy(c_options);
243 return WrapChannelCredentials(c_creds);
244 }
245
246 // Builds Local Credentials
LocalCredentials(grpc_local_connect_type type)247 std::shared_ptr<ChannelCredentials> LocalCredentials(
248 grpc_local_connect_type type) {
249 grpc::internal::GrpcLibrary init; // To call grpc_init().
250 return WrapChannelCredentials(grpc_local_credentials_create(type));
251 }
252
253 // Builds TLS Credentials given TLS options.
TlsCredentials(const TlsChannelCredentialsOptions & options)254 std::shared_ptr<ChannelCredentials> TlsCredentials(
255 const TlsChannelCredentialsOptions& options) {
256 return WrapChannelCredentials(
257 grpc_tls_credentials_create(options.c_credentials_options()));
258 }
259
260 } // namespace experimental
261
262 // Builds credentials for use when running in GCE
GoogleComputeEngineCredentials()263 std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
264 grpc::internal::GrpcLibrary init; // To call grpc_init().
265 return WrapCallCredentials(
266 grpc_google_compute_engine_credentials_create(nullptr));
267 }
268
269 // Builds JWT credentials.
ServiceAccountJWTAccessCredentials(const std::string & json_key,long token_lifetime_seconds)270 std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
271 const std::string& json_key, long token_lifetime_seconds) {
272 grpc::internal::GrpcLibrary init; // To call grpc_init().
273 if (token_lifetime_seconds <= 0) {
274 LOG(ERROR) << "Trying to create JWTCredentials with non-positive lifetime";
275 return WrapCallCredentials(nullptr);
276 }
277 gpr_timespec lifetime =
278 gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
279 return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create(
280 json_key.c_str(), lifetime, nullptr));
281 }
282
283 // Builds refresh token credentials.
GoogleRefreshTokenCredentials(const std::string & json_refresh_token)284 std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
285 const std::string& json_refresh_token) {
286 grpc::internal::GrpcLibrary init; // To call grpc_init().
287 return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
288 json_refresh_token.c_str(), nullptr));
289 }
290
291 // Builds access token credentials.
AccessTokenCredentials(const std::string & access_token)292 std::shared_ptr<CallCredentials> AccessTokenCredentials(
293 const std::string& access_token) {
294 grpc::internal::GrpcLibrary init; // To call grpc_init().
295 return WrapCallCredentials(
296 grpc_access_token_credentials_create(access_token.c_str(), nullptr));
297 }
298
299 // Builds IAM credentials.
GoogleIAMCredentials(const std::string & authorization_token,const std::string & authority_selector)300 std::shared_ptr<CallCredentials> GoogleIAMCredentials(
301 const std::string& authorization_token,
302 const std::string& authority_selector) {
303 grpc::internal::GrpcLibrary init; // To call grpc_init().
304 return WrapCallCredentials(grpc_google_iam_credentials_create(
305 authorization_token.c_str(), authority_selector.c_str(), nullptr));
306 }
307
308 // Combines one channel credentials and one call credentials into a channel
309 // composite credentials.
CompositeChannelCredentials(const std::shared_ptr<ChannelCredentials> & channel_creds,const std::shared_ptr<CallCredentials> & call_creds)310 std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
311 const std::shared_ptr<ChannelCredentials>& channel_creds,
312 const std::shared_ptr<CallCredentials>& call_creds) {
313 // Note that we are not saving shared_ptrs to the two credentials passed in
314 // here. This is OK because the underlying C objects (i.e., channel_creds and
315 // call_creds) into grpc_composite_credentials_create will see their refcounts
316 // incremented.
317 return channel_creds->c_creds_ == nullptr
318 ? nullptr
319 : WrapChannelCredentials(grpc_composite_channel_credentials_create(
320 channel_creds->c_creds_, call_creds->c_creds_, nullptr));
321 }
322
323 class CompositeCallCredentialsImpl : public CallCredentials {
324 public:
CompositeCallCredentialsImpl(const std::shared_ptr<CallCredentials> & creds1,const std::shared_ptr<CallCredentials> & creds2)325 CompositeCallCredentialsImpl(const std::shared_ptr<CallCredentials>& creds1,
326 const std::shared_ptr<CallCredentials>& creds2)
327 : CallCredentials(grpc_composite_call_credentials_create(
328 creds1->c_creds_, creds2->c_creds_, nullptr)) {}
329 };
330
CompositeCallCredentials(const std::shared_ptr<CallCredentials> & creds1,const std::shared_ptr<CallCredentials> & creds2)331 std::shared_ptr<CallCredentials> CompositeCallCredentials(
332 const std::shared_ptr<CallCredentials>& creds1,
333 const std::shared_ptr<CallCredentials>& creds2) {
334 return std::make_shared<CompositeCallCredentialsImpl>(creds1, creds2);
335 }
336
337 namespace {
338
UnrefMetadata(const std::vector<grpc_metadata> & md)339 void UnrefMetadata(const std::vector<grpc_metadata>& md) {
340 for (const auto& metadatum : md) {
341 grpc_slice_unref(metadatum.key);
342 grpc_slice_unref(metadatum.value);
343 }
344 }
345
346 class MetadataCredentialsPluginWrapper final : private internal::GrpcLibrary {
347 public:
Destroy(void * wrapper)348 static void Destroy(void* wrapper) {
349 if (wrapper == nullptr) return;
350 grpc_event_engine::experimental::GetDefaultEventEngine()->Run([wrapper] {
351 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
352 grpc_core::ExecCtx exec_ctx;
353 delete static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
354 });
355 }
356
GetMetadata(void * wrapper,grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],size_t * num_creds_md,grpc_status_code * status,const char ** error_details)357 static int GetMetadata(
358 void* wrapper, grpc_auth_metadata_context context,
359 grpc_credentials_plugin_metadata_cb cb, void* user_data,
360 grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
361 size_t* num_creds_md, grpc_status_code* status,
362 const char** error_details) {
363 CHECK(wrapper);
364 MetadataCredentialsPluginWrapper* w =
365 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
366 if (!w->plugin_) {
367 *num_creds_md = 0;
368 *status = GRPC_STATUS_OK;
369 *error_details = nullptr;
370 return 1;
371 }
372 if (w->plugin_->IsBlocking()) {
373 // The internals of context may be destroyed if GetMetadata is cancelled.
374 // Make a copy for InvokePlugin.
375 grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
376 grpc_auth_metadata_context_copy(&context, &context_copy);
377 // Asynchronous return.
378 // TODO(hork): replace with EventEngine::Run
379 w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
380 w->MetadataCredentialsPluginWrapper::InvokePlugin(
381 context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
382 grpc_auth_metadata_context_reset(&context_copy);
383 });
384 return 0;
385 } else {
386 // Synchronous return.
387 w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
388 error_details);
389 return 1;
390 }
391 }
392
DebugString(void * wrapper)393 static char* DebugString(void* wrapper) {
394 CHECK(wrapper);
395 MetadataCredentialsPluginWrapper* w =
396 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
397 return gpr_strdup(w->plugin_->DebugString().c_str());
398 }
399
MetadataCredentialsPluginWrapper(std::unique_ptr<MetadataCredentialsPlugin> plugin)400 explicit MetadataCredentialsPluginWrapper(
401 std::unique_ptr<MetadataCredentialsPlugin> plugin)
402 : plugin_(std::move(plugin)) {
403 if (plugin_->IsBlocking()) {
404 thread_pool_.reset(CreateDefaultThreadPool());
405 }
406 }
407
408 private:
InvokePlugin(grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],size_t * num_creds_md,grpc_status_code * status_code,const char ** error_details)409 void InvokePlugin(
410 grpc_auth_metadata_context context,
411 grpc_credentials_plugin_metadata_cb cb, void* user_data,
412 grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
413 size_t* num_creds_md, grpc_status_code* status_code,
414 const char** error_details) {
415 std::multimap<std::string, std::string> metadata;
416
417 // const_cast is safe since the SecureAuthContext only inc/dec the refcount
418 // and the object is passed as a const ref to plugin_->GetMetadata.
419 SecureAuthContext cpp_channel_auth_context(
420 const_cast<grpc_auth_context*>(context.channel_auth_context));
421
422 Status status =
423 plugin_->GetMetadata(context.service_url, context.method_name,
424 cpp_channel_auth_context, &metadata);
425 std::vector<grpc_metadata> md;
426 for (auto& metadatum : metadata) {
427 grpc_metadata md_entry;
428 md_entry.key = SliceFromCopiedString(metadatum.first);
429 md_entry.value = SliceFromCopiedString(metadatum.second);
430 md.push_back(md_entry);
431 }
432 if (creds_md != nullptr) {
433 // Synchronous return.
434 if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
435 *num_creds_md = 0;
436 *status_code = GRPC_STATUS_INTERNAL;
437 *error_details = gpr_strdup(
438 "blocking plugin credentials returned too many metadata keys");
439 UnrefMetadata(md);
440 } else {
441 for (const auto& elem : md) {
442 creds_md[*num_creds_md].key = elem.key;
443 creds_md[*num_creds_md].value = elem.value;
444 ++(*num_creds_md);
445 }
446 *status_code = static_cast<grpc_status_code>(status.error_code());
447 *error_details =
448 status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
449 }
450 } else {
451 // Asynchronous return.
452 cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
453 static_cast<grpc_status_code>(status.error_code()),
454 status.error_message().c_str());
455 UnrefMetadata(md);
456 }
457 }
458
459 std::unique_ptr<ThreadPoolInterface> thread_pool_;
460 std::unique_ptr<MetadataCredentialsPlugin> plugin_;
461 };
462
463 } // namespace
464
465 namespace experimental {
MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin> plugin,grpc_security_level min_security_level)466 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
467 std::unique_ptr<MetadataCredentialsPlugin> plugin,
468 grpc_security_level min_security_level) {
469 grpc::internal::GrpcLibrary init; // To call grpc_init().
470 const char* type = plugin->GetType();
471 MetadataCredentialsPluginWrapper* wrapper =
472 new MetadataCredentialsPluginWrapper(std::move(plugin));
473 grpc_metadata_credentials_plugin c_plugin = {
474 MetadataCredentialsPluginWrapper::GetMetadata,
475 MetadataCredentialsPluginWrapper::DebugString,
476 MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
477 return WrapCallCredentials(grpc_metadata_credentials_create_from_plugin(
478 c_plugin, min_security_level, nullptr));
479 }
480
481 } // namespace experimental
482
MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin> plugin)483 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
484 std::unique_ptr<MetadataCredentialsPlugin> plugin) {
485 return experimental::MetadataCredentialsFromPlugin(
486 std::move(plugin), GRPC_PRIVACY_AND_INTEGRITY);
487 }
488
489 } // namespace grpc
490