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