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 <grpc/support/port_platform.h>
20
21 #include "src/core/lib/security/credentials/credentials.h"
22
23 #include <string.h>
24
25 #include <grpc/support/alloc.h>
26 #include <grpc/support/log.h>
27 #include <grpc/support/sync.h>
28
29 #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
30 #include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
31 #include "src/core/lib/channel/channel_args.h"
32 #include "src/core/lib/gpr/env.h"
33 #include "src/core/lib/gpr/string.h"
34 #include "src/core/lib/gprpp/ref_counted_ptr.h"
35 #include "src/core/lib/http/httpcli.h"
36 #include "src/core/lib/http/parser.h"
37 #include "src/core/lib/iomgr/load_file.h"
38 #include "src/core/lib/iomgr/polling_entity.h"
39 #include "src/core/lib/security/credentials/alts/alts_credentials.h"
40 #include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
41 #include "src/core/lib/security/credentials/external/external_account_credentials.h"
42 #include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
43 #include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
44 #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
45 #include "src/core/lib/slice/slice_internal.h"
46 #include "src/core/lib/slice/slice_string_helpers.h"
47 #include "src/core/lib/surface/api_trace.h"
48
49 using grpc_core::Json;
50
51 /* -- Constants. -- */
52
53 #define GRPC_COMPUTE_ENGINE_DETECTION_HOST "metadata.google.internal."
54 #define GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR \
55 "Failed to create Google credentials"
56
57 /* -- Default credentials. -- */
58
59 /* A sticky bit that will be set only if the result of metadata server detection
60 * is positive. We do not set the bit if the result is negative. Because it
61 * means the detection is done via network test that is unreliable and the
62 * unreliable result should not be referred by successive calls. */
63 static int g_metadata_server_available = 0;
64 static grpc_core::Mutex* g_state_mu;
65 /* Protect a metadata_server_detector instance that can be modified by more than
66 * one gRPC threads */
67 static gpr_mu* g_polling_mu;
68 static gpr_once g_once = GPR_ONCE_INIT;
69 static grpc_core::internal::grpc_gce_tenancy_checker g_gce_tenancy_checker =
70 grpc_alts_is_running_on_gcp;
71
init_default_credentials(void)72 static void init_default_credentials(void) {
73 g_state_mu = new grpc_core::Mutex();
74 }
75
76 struct metadata_server_detector {
77 grpc_polling_entity pollent;
78 int is_done;
79 int success;
80 grpc_http_response response;
81 };
82 grpc_core::RefCountedPtr<grpc_channel_security_connector>
create_security_connector(grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,const char * target,const grpc_channel_args * args,grpc_channel_args ** new_args)83 grpc_google_default_channel_credentials::create_security_connector(
84 grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
85 const char* target, const grpc_channel_args* args,
86 grpc_channel_args** new_args) {
87 const bool is_grpclb_load_balancer = grpc_channel_args_find_bool(
88 args, GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER, false);
89 const bool is_backend_from_grpclb_load_balancer = grpc_channel_args_find_bool(
90 args, GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER, false);
91 const char* xds_cluster =
92 grpc_channel_args_find_string(args, GRPC_ARG_XDS_CLUSTER_NAME);
93 const bool is_xds_non_cfe_cluster =
94 xds_cluster != nullptr && strcmp(xds_cluster, "google_cfe") != 0;
95 const bool use_alts = is_grpclb_load_balancer ||
96 is_backend_from_grpclb_load_balancer ||
97 is_xds_non_cfe_cluster;
98 /* Return failure if ALTS is selected but not running on GCE. */
99 if (use_alts && alts_creds_ == nullptr) {
100 gpr_log(GPR_ERROR, "ALTS is selected, but not running on GCE.");
101 return nullptr;
102 }
103 grpc_core::RefCountedPtr<grpc_channel_security_connector> sc =
104 use_alts ? alts_creds_->create_security_connector(call_creds, target,
105 args, new_args)
106 : ssl_creds_->create_security_connector(call_creds, target, args,
107 new_args);
108 /* grpclb-specific channel args are removed from the channel args set
109 * to ensure backends and fallback adresses will have the same set of channel
110 * args. By doing that, it guarantees the connections to backends will not be
111 * torn down and re-connected when switching in and out of fallback mode.
112 */
113 if (use_alts) {
114 static const char* args_to_remove[] = {
115 GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER,
116 GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER,
117 };
118 *new_args = grpc_channel_args_copy_and_add_and_remove(
119 args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), nullptr, 0);
120 }
121 return sc;
122 }
123
update_arguments(grpc_channel_args * args)124 grpc_channel_args* grpc_google_default_channel_credentials::update_arguments(
125 grpc_channel_args* args) {
126 grpc_channel_args* updated = args;
127 if (grpc_channel_args_find(args, GRPC_ARG_DNS_ENABLE_SRV_QUERIES) ==
128 nullptr) {
129 grpc_arg new_srv_arg = grpc_channel_arg_integer_create(
130 const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true);
131 updated = grpc_channel_args_copy_and_add(args, &new_srv_arg, 1);
132 grpc_channel_args_destroy(args);
133 }
134 return updated;
135 }
136
on_metadata_server_detection_http_response(void * user_data,grpc_error * error)137 static void on_metadata_server_detection_http_response(void* user_data,
138 grpc_error* error) {
139 metadata_server_detector* detector =
140 static_cast<metadata_server_detector*>(user_data);
141 if (error == GRPC_ERROR_NONE && detector->response.status == 200 &&
142 detector->response.hdr_count > 0) {
143 /* Internet providers can return a generic response to all requests, so
144 it is necessary to check that metadata header is present also. */
145 size_t i;
146 for (i = 0; i < detector->response.hdr_count; i++) {
147 grpc_http_header* header = &detector->response.hdrs[i];
148 if (strcmp(header->key, "Metadata-Flavor") == 0 &&
149 strcmp(header->value, "Google") == 0) {
150 detector->success = 1;
151 break;
152 }
153 }
154 }
155 gpr_mu_lock(g_polling_mu);
156 detector->is_done = 1;
157 GRPC_LOG_IF_ERROR(
158 "Pollset kick",
159 grpc_pollset_kick(grpc_polling_entity_pollset(&detector->pollent),
160 nullptr));
161 gpr_mu_unlock(g_polling_mu);
162 }
163
destroy_pollset(void * p,grpc_error *)164 static void destroy_pollset(void* p, grpc_error* /*e*/) {
165 grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
166 }
167
is_metadata_server_reachable()168 static int is_metadata_server_reachable() {
169 metadata_server_detector detector;
170 grpc_httpcli_request request;
171 grpc_httpcli_context context;
172 grpc_closure destroy_closure;
173 /* The http call is local. If it takes more than one sec, it is for sure not
174 on compute engine. */
175 grpc_millis max_detection_delay = GPR_MS_PER_SEC;
176 grpc_pollset* pollset =
177 static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
178 grpc_pollset_init(pollset, &g_polling_mu);
179 detector.pollent = grpc_polling_entity_create_from_pollset(pollset);
180 detector.is_done = 0;
181 detector.success = 0;
182 memset(&request, 0, sizeof(grpc_httpcli_request));
183 request.host = const_cast<char*>(GRPC_COMPUTE_ENGINE_DETECTION_HOST);
184 request.http.path = const_cast<char*>("/");
185 grpc_httpcli_context_init(&context);
186 grpc_resource_quota* resource_quota =
187 grpc_resource_quota_create("google_default_credentials");
188 grpc_httpcli_get(
189 &context, &detector.pollent, resource_quota, &request,
190 grpc_core::ExecCtx::Get()->Now() + max_detection_delay,
191 GRPC_CLOSURE_CREATE(on_metadata_server_detection_http_response, &detector,
192 grpc_schedule_on_exec_ctx),
193 &detector.response);
194 grpc_resource_quota_unref_internal(resource_quota);
195 grpc_core::ExecCtx::Get()->Flush();
196 /* Block until we get the response. This is not ideal but this should only be
197 called once for the lifetime of the process by the default credentials. */
198 gpr_mu_lock(g_polling_mu);
199 while (!detector.is_done) {
200 grpc_pollset_worker* worker = nullptr;
201 if (!GRPC_LOG_IF_ERROR(
202 "pollset_work",
203 grpc_pollset_work(grpc_polling_entity_pollset(&detector.pollent),
204 &worker, GRPC_MILLIS_INF_FUTURE))) {
205 detector.is_done = 1;
206 detector.success = 0;
207 }
208 }
209 gpr_mu_unlock(g_polling_mu);
210 grpc_httpcli_context_destroy(&context);
211 GRPC_CLOSURE_INIT(&destroy_closure, destroy_pollset,
212 grpc_polling_entity_pollset(&detector.pollent),
213 grpc_schedule_on_exec_ctx);
214 grpc_pollset_shutdown(grpc_polling_entity_pollset(&detector.pollent),
215 &destroy_closure);
216 g_polling_mu = nullptr;
217 grpc_core::ExecCtx::Get()->Flush();
218 gpr_free(grpc_polling_entity_pollset(&detector.pollent));
219 grpc_http_response_destroy(&detector.response);
220 return detector.success;
221 }
222
223 /* Takes ownership of creds_path if not NULL. */
create_default_creds_from_path(const std::string & creds_path,grpc_core::RefCountedPtr<grpc_call_credentials> * creds)224 static grpc_error* create_default_creds_from_path(
225 const std::string& creds_path,
226 grpc_core::RefCountedPtr<grpc_call_credentials>* creds) {
227 grpc_auth_json_key key;
228 grpc_auth_refresh_token token;
229 grpc_core::RefCountedPtr<grpc_call_credentials> result;
230 grpc_slice creds_data = grpc_empty_slice();
231 grpc_error* error = GRPC_ERROR_NONE;
232 Json json;
233 if (creds_path.empty()) {
234 error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset");
235 goto end;
236 }
237 error = grpc_load_file(creds_path.c_str(), 0, &creds_data);
238 if (error != GRPC_ERROR_NONE) goto end;
239 json = Json::Parse(grpc_core::StringViewFromSlice(creds_data), &error);
240 if (error != GRPC_ERROR_NONE) goto end;
241 if (json.type() != Json::Type::OBJECT) {
242 error = grpc_error_set_str(
243 GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"),
244 GRPC_ERROR_STR_RAW_BYTES, grpc_slice_ref_internal(creds_data));
245 goto end;
246 }
247
248 /* First, try an auth json key. */
249 key = grpc_auth_json_key_create_from_json(json);
250 if (grpc_auth_json_key_is_valid(&key)) {
251 result =
252 grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
253 key, grpc_max_auth_token_lifetime());
254 if (result == nullptr) {
255 error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
256 "grpc_service_account_jwt_access_credentials_create_from_auth_json_"
257 "key failed");
258 }
259 goto end;
260 }
261
262 /* Then try a refresh token if the auth json key was invalid. */
263 token = grpc_auth_refresh_token_create_from_json(json);
264 if (grpc_auth_refresh_token_is_valid(&token)) {
265 result =
266 grpc_refresh_token_credentials_create_from_auth_refresh_token(token);
267 if (result == nullptr) {
268 error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
269 "grpc_refresh_token_credentials_create_from_auth_refresh_token "
270 "failed");
271 }
272 goto end;
273 }
274
275 /* Finally try an external account credentials.*/
276 result = grpc_core::ExternalAccountCredentials::Create(json, {}, &error);
277
278 end:
279 GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1);
280 grpc_slice_unref_internal(creds_data);
281 *creds = result;
282 return error;
283 }
284
update_tenancy()285 static void update_tenancy() {
286 gpr_once_init(&g_once, init_default_credentials);
287 grpc_core::MutexLock lock(g_state_mu);
288
289 /* Try a platform-provided hint for GCE. */
290 if (!g_metadata_server_available) {
291 g_metadata_server_available = g_gce_tenancy_checker();
292 }
293 /* TODO: Add a platform-provided hint for GAE. */
294
295 /* Do a network test for metadata server. */
296 if (!g_metadata_server_available) {
297 g_metadata_server_available = is_metadata_server_reachable();
298 }
299 }
300
metadata_server_available()301 static bool metadata_server_available() {
302 grpc_core::MutexLock lock(g_state_mu);
303 return static_cast<bool>(g_metadata_server_available);
304 }
305
make_default_call_creds(grpc_error ** error)306 static grpc_core::RefCountedPtr<grpc_call_credentials> make_default_call_creds(
307 grpc_error** error) {
308 grpc_core::RefCountedPtr<grpc_call_credentials> call_creds;
309 grpc_error* err;
310
311 /* First, try the environment variable. */
312 char* path_from_env = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR);
313 if (path_from_env != nullptr) {
314 err = create_default_creds_from_path(path_from_env, &call_creds);
315 gpr_free(path_from_env);
316 if (err == GRPC_ERROR_NONE) return call_creds;
317 *error = grpc_error_add_child(*error, err);
318 }
319
320 /* Then the well-known file. */
321 err = create_default_creds_from_path(
322 grpc_get_well_known_google_credentials_file_path(), &call_creds);
323 if (err == GRPC_ERROR_NONE) return call_creds;
324 *error = grpc_error_add_child(*error, err);
325
326 update_tenancy();
327
328 if (metadata_server_available()) {
329 call_creds = grpc_core::RefCountedPtr<grpc_call_credentials>(
330 grpc_google_compute_engine_credentials_create(nullptr));
331 if (call_creds == nullptr) {
332 *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
333 GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR);
334 *error = grpc_error_add_child(
335 *error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
336 "Failed to get credentials from network"));
337 }
338 }
339
340 return call_creds;
341 }
342
grpc_google_default_credentials_create(grpc_call_credentials * call_credentials)343 grpc_channel_credentials* grpc_google_default_credentials_create(
344 grpc_call_credentials* call_credentials) {
345 grpc_channel_credentials* result = nullptr;
346 grpc_core::RefCountedPtr<grpc_call_credentials> call_creds(call_credentials);
347 grpc_error* error = nullptr;
348 grpc_core::ExecCtx exec_ctx;
349
350 GRPC_API_TRACE("grpc_google_default_credentials_create(%p)", 1,
351 (call_credentials));
352
353 if (call_creds == nullptr) {
354 call_creds = make_default_call_creds(&error);
355 }
356
357 if (call_creds != nullptr) {
358 /* Create google default credentials. */
359 grpc_channel_credentials* ssl_creds =
360 grpc_ssl_credentials_create(nullptr, nullptr, nullptr, nullptr);
361 GPR_ASSERT(ssl_creds != nullptr);
362 grpc_alts_credentials_options* options =
363 grpc_alts_credentials_client_options_create();
364 grpc_channel_credentials* alts_creds =
365 grpc_alts_credentials_create(options);
366 grpc_alts_credentials_options_destroy(options);
367 auto creds =
368 grpc_core::MakeRefCounted<grpc_google_default_channel_credentials>(
369 grpc_core::RefCountedPtr<grpc_channel_credentials>(alts_creds),
370 grpc_core::RefCountedPtr<grpc_channel_credentials>(ssl_creds));
371 result = grpc_composite_channel_credentials_create(
372 creds.get(), call_creds.get(), nullptr);
373 GPR_ASSERT(result != nullptr);
374 } else {
375 gpr_log(GPR_ERROR, "Could not create google default credentials: %s",
376 grpc_error_string(error));
377 }
378 GRPC_ERROR_UNREF(error);
379 return result;
380 }
381
382 namespace grpc_core {
383 namespace internal {
384
set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker)385 void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker) {
386 g_gce_tenancy_checker = checker;
387 }
388
grpc_flush_cached_google_default_credentials(void)389 void grpc_flush_cached_google_default_credentials(void) {
390 grpc_core::ExecCtx exec_ctx;
391 gpr_once_init(&g_once, init_default_credentials);
392 grpc_core::MutexLock lock(g_state_mu);
393 g_metadata_server_available = 0;
394 }
395
396 } // namespace internal
397 } // namespace grpc_core
398
399 /* -- Well known credentials path. -- */
400
401 static grpc_well_known_credentials_path_getter creds_path_getter = nullptr;
402
grpc_get_well_known_google_credentials_file_path(void)403 std::string grpc_get_well_known_google_credentials_file_path(void) {
404 if (creds_path_getter != nullptr) return creds_path_getter();
405 return grpc_get_well_known_google_credentials_file_path_impl();
406 }
407
grpc_override_well_known_credentials_path_getter(grpc_well_known_credentials_path_getter getter)408 void grpc_override_well_known_credentials_path_getter(
409 grpc_well_known_credentials_path_getter getter) {
410 creds_path_getter = getter;
411 }
412