Debian Codegraph @

src/core/lib/security/credentials/jwt/jwt_verifier.cc

raw
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/jwt/jwt_verifier.h"
22
23 #include <limits.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include <map>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 #include <openssl/bio.h>
34 #include <openssl/bn.h>
35 #include <openssl/crypto.h>
36 #include <openssl/evp.h>
37 #include <openssl/pem.h>
38 #include <openssl/rsa.h>
39 #include <openssl/x509.h>
40
41 #include "absl/status/status.h"
42 #include "absl/status/statusor.h"
43 #include "absl/strings/string_view.h"
44
45 #include <grpc/grpc.h>
46 #include <grpc/slice.h>
47 #include <grpc/support/alloc.h>
48 #include <grpc/support/log.h>
49 #include <grpc/support/string_util.h>
50 #include <grpc/support/time.h>
51
52 #include "src/core/lib/gpr/string.h"
53 #include "src/core/lib/gprpp/manual_constructor.h"
54 #include "src/core/lib/gprpp/memory.h"
55 #include "src/core/lib/gprpp/orphanable.h"
56 #include "src/core/lib/http/httpcli.h"
57 #include "src/core/lib/http/httpcli_ssl_credentials.h"
58 #include "src/core/lib/http/parser.h"
59 #include "src/core/lib/iomgr/closure.h"
60 #include "src/core/lib/iomgr/error.h"
61 #include "src/core/lib/iomgr/exec_ctx.h"
62 #include "src/core/lib/iomgr/iomgr_fwd.h"
63 #include "src/core/lib/iomgr/polling_entity.h"
64 #include "src/core/lib/security/credentials/credentials.h"
65 #include "src/core/lib/slice/b64.h"
66 #include "src/core/lib/slice/slice.h"
67 #include "src/core/lib/slice/slice_internal.h"
68 #include "src/core/lib/uri/uri_parser.h"
69 #include "src/core/tsi/ssl_types.h"
70
71 using grpc_core::Json;
72
73 /* --- Utils. --- */
74
75 const char* grpc_jwt_verifier_status_to_string(
76 grpc_jwt_verifier_status status) {
77 switch (status) {
78 case GRPC_JWT_VERIFIER_OK:
79 return "OK";
80 case GRPC_JWT_VERIFIER_BAD_SIGNATURE:
81 return "BAD_SIGNATURE";
82 case GRPC_JWT_VERIFIER_BAD_FORMAT:
83 return "BAD_FORMAT";
84 case GRPC_JWT_VERIFIER_BAD_AUDIENCE:
85 return "BAD_AUDIENCE";
86 case GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR:
87 return "KEY_RETRIEVAL_ERROR";
88 case GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE:
89 return "TIME_CONSTRAINT_FAILURE";
90 case GRPC_JWT_VERIFIER_GENERIC_ERROR:
91 return "GENERIC_ERROR";
92 default:
93 return "UNKNOWN";
94 }
95 }
96
97 static const EVP_MD* evp_md_from_alg(const char* alg) {
98 if (strcmp(alg, "RS256") == 0) {
99 return EVP_sha256();
100 } else if (strcmp(alg, "RS384") == 0) {
101 return EVP_sha384();
102 } else if (strcmp(alg, "RS512") == 0) {
103 return EVP_sha512();
104 } else {
105 return nullptr;
106 }
107 }
108
109 static Json parse_json_part_from_jwt(const char* str, size_t len) {
110 grpc_slice slice = grpc_base64_decode_with_len(str, len, 1);
111 if (GRPC_SLICE_IS_EMPTY(slice)) {
112 gpr_log(GPR_ERROR, "Invalid base64.");
113 return Json(); // JSON null
114 }
115 absl::string_view string = grpc_core::StringViewFromSlice(slice);
116 auto json = Json::Parse(string);
117 grpc_core::CSliceUnref(slice);
118 if (!json.ok()) {
119 gpr_log(GPR_ERROR, "JSON parse error: %s",
120 json.status().ToString().c_str());
121 return Json(); // JSON null
122 }
123 return std::move(*json);
124 }
125
126 static const char* validate_string_field(const Json& json, const char* key) {
127 if (json.type() != Json::Type::STRING) {
128 gpr_log(GPR_ERROR, "Invalid %s field", key);
129 return nullptr;
130 }
131 return json.string_value().c_str();
132 }
133
134 static gpr_timespec validate_time_field(const Json& json, const char* key) {
135 gpr_timespec result = gpr_time_0(GPR_CLOCK_REALTIME);
136 if (json.type() != Json::Type::NUMBER) {
137 gpr_log(GPR_ERROR, "Invalid %s field", key);
138 return result;
139 }
140 result.tv_sec = strtol(json.string_value().c_str(), nullptr, 10);
141 return result;
142 }
143
144 /* --- JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 --- */
145
146 struct jose_header {
147 const char* alg;
148 const char* kid;
149 const char* typ;
150 /* TODO(jboeuf): Add others as needed (jku, jwk, x5u, x5c and so on...). */
151 grpc_core::ManualConstructor<Json> json;
152 };
153 static void jose_header_destroy(jose_header* h) {
154 h->json.Destroy();
155 gpr_free(h);
156 }
157
158 static jose_header* jose_header_from_json(Json json) {
159 const char* alg_value;
160 Json::Object::const_iterator it;
161 jose_header* h = grpc_core::Zalloc<jose_header>();
162 if (json.type() != Json::Type::OBJECT) {
163 gpr_log(GPR_ERROR, "JSON value is not an object");
164 goto error;
165 }
166 // Check alg field.
167 it = json.object_value().find("alg");
168 if (it == json.object_value().end()) {
169 gpr_log(GPR_ERROR, "Missing alg field.");
170 goto error;
171 }
172 /* We only support RSA-1.5 signatures for now.
173 Beware of this if we add HMAC support:
174 https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
175 */
176 alg_value = it->second.string_value().c_str();
177 if (it->second.type() != Json::Type::STRING ||
178 strncmp(alg_value, "RS", 2) != 0 ||
179 evp_md_from_alg(alg_value) == nullptr) {
180 gpr_log(GPR_ERROR, "Invalid alg field");
181 goto error;
182 }
183 h->alg = alg_value;
184 // Check typ field.
185 it = json.object_value().find("typ");
186 if (it != json.object_value().end()) {
187 h->typ = validate_string_field(it->second, "typ");
188 if (h->typ == nullptr) goto error;
189 }
190 // Check kid field.
191 it = json.object_value().find("kid");
192 if (it != json.object_value().end()) {
193 h->kid = validate_string_field(it->second, "kid");
194 if (h->kid == nullptr) goto error;
195 }
196 h->json.Init(std::move(json));
197 return h;
198
199 error:
200 jose_header_destroy(h);
201 return nullptr;
202 }
203
204 /* --- JWT claims. see http://tools.ietf.org/html/rfc7519#section-4.1 */
205
206 struct grpc_jwt_claims {
207 /* Well known properties already parsed. */
208 const char* sub;
209 const char* iss;
210 const char* aud;
211 const char* jti;
212 gpr_timespec iat;
213 gpr_timespec exp;
214 gpr_timespec nbf;
215
216 grpc_core::ManualConstructor<Json> json;
217 };
218
219 void grpc_jwt_claims_destroy(grpc_jwt_claims* claims) {
220 claims->json.Destroy();
221 gpr_free(claims);
222 }
223
224 const Json* grpc_jwt_claims_json(const grpc_jwt_claims* claims) {
225 if (claims == nullptr) return nullptr;
226 return claims->json.get();
227 }
228
229 const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims) {
230 if (claims == nullptr) return nullptr;
231 return claims->sub;
232 }
233
234 const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims) {
235 if (claims == nullptr) return nullptr;
236 return claims->iss;
237 }
238
239 const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims) {
240 if (claims == nullptr) return nullptr;
241 return claims->jti;
242 }
243
244 const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims) {
245 if (claims == nullptr) return nullptr;
246 return claims->aud;
247 }
248
249 gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims) {
250 if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
251 return claims->iat;
252 }
253
254 gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims) {
255 if (claims == nullptr) return gpr_inf_future(GPR_CLOCK_REALTIME);
256 return claims->exp;
257 }
258
259 gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims) {
260 if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
261 return claims->nbf;
262 }
263
264 grpc_jwt_claims* grpc_jwt_claims_from_json(Json json) {
265 grpc_jwt_claims* claims = grpc_core::Zalloc<grpc_jwt_claims>();
266 claims->json.Init(std::move(json));
267 claims->iat = gpr_inf_past(GPR_CLOCK_REALTIME);
268 claims->nbf = gpr_inf_past(GPR_CLOCK_REALTIME);
269 claims->exp = gpr_inf_future(GPR_CLOCK_REALTIME);
270
271 /* Per the spec, all fields are optional. */
272 for (const auto& p : claims->json->object_value()) {
273 if (p.first == "sub") {
274 claims->sub = validate_string_field(p.second, "sub");
275 if (claims->sub == nullptr) goto error;
276 } else if (p.first == "iss") {
277 claims->iss = validate_string_field(p.second, "iss");
278 if (claims->iss == nullptr) goto error;
279 } else if (p.first == "aud") {
280 claims->aud = validate_string_field(p.second, "aud");
281 if (claims->aud == nullptr) goto error;
282 } else if (p.first == "jti") {
283 claims->jti = validate_string_field(p.second, "jti");
284 if (claims->jti == nullptr) goto error;
285 } else if (p.first == "iat") {
286 claims->iat = validate_time_field(p.second, "iat");
287 if (gpr_time_cmp(claims->iat, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
288 goto error;
289 }
290 } else if (p.first == "exp") {
291 claims->exp = validate_time_field(p.second, "exp");
292 if (gpr_time_cmp(claims->exp, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
293 goto error;
294 }
295 } else if (p.first == "nbf") {
296 claims->nbf = validate_time_field(p.second, "nbf");
297 if (gpr_time_cmp(claims->nbf, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
298 goto error;
299 }
300 }
301 }
302 return claims;
303
304 error:
305 grpc_jwt_claims_destroy(claims);
306 return nullptr;
307 }
308
309 grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims,
310 const char* audience) {
311 gpr_timespec skewed_now;
312 int audience_ok;
313
314 GPR_ASSERT(claims != nullptr);
315
316 skewed_now =
317 gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
318 if (gpr_time_cmp(skewed_now, claims->nbf) < 0) {
319 gpr_log(GPR_ERROR, "JWT is not valid yet.");
320 return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
321 }
322 skewed_now =
323 gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
324 if (gpr_time_cmp(skewed_now, claims->exp) > 0) {
325 gpr_log(GPR_ERROR, "JWT is expired.");
326 return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
327 }
328
329 /* This should be probably up to the upper layer to decide but let's harcode
330 the 99% use case here for email issuers, where the JWT must be self
331 issued. */
332 if (grpc_jwt_issuer_email_domain(claims->iss) != nullptr &&
333 claims->sub != nullptr && strcmp(claims->iss, claims->sub) != 0) {
334 gpr_log(GPR_ERROR,
335 "Email issuer (%s) cannot assert another subject (%s) than itself.",
336 claims->iss, claims->sub);
337 return GRPC_JWT_VERIFIER_BAD_SUBJECT;
338 }
339
340 if (audience == nullptr) {
341 audience_ok = claims->aud == nullptr;
342 } else {
343 audience_ok = claims->aud != nullptr && strcmp(audience, claims->aud) == 0;
344 }
345 if (!audience_ok) {
346 gpr_log(GPR_ERROR, "Audience mismatch: expected %s and found %s.",
347 audience == nullptr ? "NULL" : audience,
348 claims->aud == nullptr ? "NULL" : claims->aud);
349 return GRPC_JWT_VERIFIER_BAD_AUDIENCE;
350 }
351 return GRPC_JWT_VERIFIER_OK;
352 }
353
354 /* --- verifier_cb_ctx object. --- */
355
356 typedef enum {
357 HTTP_RESPONSE_OPENID = 0,
358 HTTP_RESPONSE_KEYS,
359 HTTP_RESPONSE_COUNT /* must be last */
360 } http_response_index;
361
362 struct verifier_cb_ctx {
363 grpc_jwt_verifier* verifier;
364 grpc_polling_entity pollent;
365 jose_header* header;
366 grpc_jwt_claims* claims;
367 char* audience;
368 grpc_slice signature;
369 grpc_slice signed_data;
370 void* user_data;
371 grpc_jwt_verification_done_cb user_cb;
372 grpc_http_response responses[HTTP_RESPONSE_COUNT];
373 grpc_core::OrphanablePtr<grpc_core::HttpRequest> http_request;
374 };
375 /* Takes ownership of the header, claims and signature. */
376 static verifier_cb_ctx* verifier_cb_ctx_create(
377 grpc_jwt_verifier* verifier, grpc_pollset* pollset, jose_header* header,
378 grpc_jwt_claims* claims, const char* audience, const grpc_slice& signature,
379 const char* signed_jwt, size_t signed_jwt_len, void* user_data,
380 grpc_jwt_verification_done_cb cb) {
381 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
382 grpc_core::ExecCtx exec_ctx;
383 verifier_cb_ctx* ctx = new verifier_cb_ctx();
384 ctx->verifier = verifier;
385 ctx->pollent = grpc_polling_entity_create_from_pollset(pollset);
386 ctx->header = header;
387 ctx->audience = gpr_strdup(audience);
388 ctx->claims = claims;
389 ctx->signature = signature;
390 ctx->signed_data = grpc_slice_from_copied_buffer(signed_jwt, signed_jwt_len);
391 ctx->user_data = user_data;
392 ctx->user_cb = cb;
393 return ctx;
394 }
395
396 void verifier_cb_ctx_destroy(verifier_cb_ctx* ctx) {
397 if (ctx->audience != nullptr) gpr_free(ctx->audience);
398 if (ctx->claims != nullptr) grpc_jwt_claims_destroy(ctx->claims);
399 grpc_core::CSliceUnref(ctx->signature);
400 grpc_core::CSliceUnref(ctx->signed_data);
401 jose_header_destroy(ctx->header);
402 for (size_t i = 0; i < HTTP_RESPONSE_COUNT; i++) {
403 grpc_http_response_destroy(&ctx->responses[i]);
404 }
405 /* TODO: see what to do with claims... */
406 delete ctx;
407 }
408
409 /* --- grpc_jwt_verifier object. --- */
410
411 /* Clock skew defaults to one minute. */
412 gpr_timespec grpc_jwt_verifier_clock_skew = {60, 0, GPR_TIMESPAN};
413
414 /* Max delay defaults to one minute. */
415 grpc_core::Duration grpc_jwt_verifier_max_delay =
416 grpc_core::Duration::Minutes(1);
417
418 struct email_key_mapping {
419 char* email_domain;
420 char* key_url_prefix;
421 };
422 struct grpc_jwt_verifier {
423 email_key_mapping* mappings;
424 size_t num_mappings; /* Should be very few, linear search ok. */
425 size_t allocated_mappings;
426 };
427
428 static Json json_from_http(const grpc_http_response* response) {
429 if (response == nullptr) {
430 gpr_log(GPR_ERROR, "HTTP response is NULL.");
431 return Json(); // JSON null
432 }
433 if (response->status != 200) {
434 gpr_log(GPR_ERROR, "Call to http server failed with error %d.",
435 response->status);
436 return Json(); // JSON null
437 }
438 auto json =
439 Json::Parse(absl::string_view(response->body, response->body_length));
440 if (!json.ok()) {
441 gpr_log(GPR_ERROR, "Invalid JSON found in response.");
442 return Json(); // JSON null
443 }
444 return std::move(*json);
445 }
446
447 static const Json* find_property_by_name(const Json& json, const char* name) {
448 auto it = json.object_value().find(name);
449 if (it == json.object_value().end()) {
450 return nullptr;
451 }
452 return &it->second;
453 }
454
455 static EVP_PKEY* extract_pkey_from_x509(const char* x509_str) {
456 X509* x509 = nullptr;
457 EVP_PKEY* result = nullptr;
458 BIO* bio = BIO_new(BIO_s_mem());
459 size_t len = strlen(x509_str);
460 GPR_ASSERT(len < INT_MAX);
461 BIO_write(bio, x509_str, static_cast<int>(len));
462 x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
463 if (x509 == nullptr) {
464 gpr_log(GPR_ERROR, "Unable to parse x509 cert.");
465 goto end;
466 }
467 result = X509_get_pubkey(x509);
468 if (result == nullptr) {
469 gpr_log(GPR_ERROR, "Cannot find public key in X509 cert.");
470 }
471
472 end:
473 BIO_free(bio);
474 X509_free(x509);
475 return result;
476 }
477
478 static BIGNUM* bignum_from_base64(const char* b64) {
479 BIGNUM* result = nullptr;
480 grpc_slice bin;
481
482 if (b64 == nullptr) return nullptr;
483 bin = grpc_base64_decode(b64, 1);
484 if (GRPC_SLICE_IS_EMPTY(bin)) {
485 gpr_log(GPR_ERROR, "Invalid base64 for big num.");
486 return nullptr;
487 }
488 result = BN_bin2bn(GRPC_SLICE_START_PTR(bin),
489 TSI_SIZE_AS_SIZE(GRPC_SLICE_LENGTH(bin)), nullptr);
490 grpc_core::CSliceUnref(bin);
491 return result;
492 }
493
494 #if OPENSSL_VERSION_NUMBER < 0x10100000L
495
496 // Provide compatibility across OpenSSL 1.02 and 1.1.
497 static int RSA_set0_key(RSA* r, BIGNUM* n, BIGNUM* e, BIGNUM* d) {
498 /* If the fields n and e in r are NULL, the corresponding input
499 * parameters MUST be non-NULL for n and e. d may be
500 * left NULL (in case only the public key is used).
501 */
502 if ((r->n == nullptr && n == nullptr) || (r->e == nullptr && e == nullptr)) {
503 return 0;
504 }
505
506 if (n != nullptr) {
507 BN_free(r->n);
508 r->n = n;
509 }
510 if (e != nullptr) {
511 BN_free(r->e);
512 r->e = e;
513 }
514 if (d != nullptr) {
515 BN_free(r->d);
516 r->d = d;
517 }
518
519 return 1;
520 }
521 #endif // OPENSSL_VERSION_NUMBER < 0x10100000L
522
523 static EVP_PKEY* pkey_from_jwk(const Json& json, const char* kty) {
524 RSA* rsa = nullptr;
525 EVP_PKEY* result = nullptr;
526 BIGNUM* tmp_n = nullptr;
527 BIGNUM* tmp_e = nullptr;
528 Json::Object::const_iterator it;
529
530 GPR_ASSERT(json.type() == Json::Type::OBJECT);
531 GPR_ASSERT(kty != nullptr);
532 if (strcmp(kty, "RSA") != 0) {
533 gpr_log(GPR_ERROR, "Unsupported key type %s.", kty);
534 goto end;
535 }
536 rsa = RSA_new();
537 if (rsa == nullptr) {
538 gpr_log(GPR_ERROR, "Could not create rsa key.");
539 goto end;
540 }
541 it = json.object_value().find("n");
542 if (it == json.object_value().end()) {
543 gpr_log(GPR_ERROR, "Missing RSA public key field.");
544 goto end;
545 }
546 tmp_n = bignum_from_base64(validate_string_field(it->second, "n"));
547 if (tmp_n == nullptr) goto end;
548 it = json.object_value().find("e");
549 if (it == json.object_value().end()) {
550 gpr_log(GPR_ERROR, "Missing RSA public key field.");
551 goto end;
552 }
553 tmp_e = bignum_from_base64(validate_string_field(it->second, "e"));
554 if (tmp_e == nullptr) goto end;
555 if (!RSA_set0_key(rsa, tmp_n, tmp_e, nullptr)) {
556 gpr_log(GPR_ERROR, "Cannot set RSA key from inputs.");
557 goto end;
558 }
559 /* RSA_set0_key takes ownership on success. */
560 tmp_n = nullptr;
561 tmp_e = nullptr;
562 result = EVP_PKEY_new();
563 EVP_PKEY_set1_RSA(result, rsa); /* uprefs rsa. */
564
565 end:
566 RSA_free(rsa);
567 BN_free(tmp_n);
568 BN_free(tmp_e);
569 return result;
570 }
571
572 static EVP_PKEY* find_verification_key(const Json& json, const char* header_alg,
573 const char* header_kid) {
574 /* Try to parse the json as a JWK set:
575 https://tools.ietf.org/html/rfc7517#section-5. */
576 const Json* jwt_keys = find_property_by_name(json, "keys");
577 if (jwt_keys == nullptr) {
578 /* Use the google proprietary format which is:
579 { <kid1>: <x5091>, <kid2>: <x5092>, ... } */
580 const Json* cur = find_property_by_name(json, header_kid);
581 if (cur == nullptr) return nullptr;
582 return extract_pkey_from_x509(cur->string_value().c_str());
583 }
584 if (jwt_keys->type() != Json::Type::ARRAY) {
585 gpr_log(GPR_ERROR,
586 "Unexpected value type of keys property in jwks key set.");
587 return nullptr;
588 }
589 /* Key format is specified in:
590 https://tools.ietf.org/html/rfc7518#section-6. */
591 for (const Json& jkey : jwt_keys->array_value()) {
592 if (jkey.type() != Json::Type::OBJECT) continue;
593 const char* alg = nullptr;
594 auto it = jkey.object_value().find("alg");
595 if (it != jkey.object_value().end()) {
596 alg = validate_string_field(it->second, "alg");
597 }
598 const char* kid = nullptr;
599 it = jkey.object_value().find("kid");
600 if (it != jkey.object_value().end()) {
601 kid = validate_string_field(it->second, "kid");
602 }
603 const char* kty = nullptr;
604 it = jkey.object_value().find("kty");
605 if (it != jkey.object_value().end()) {
606 kty = validate_string_field(it->second, "kty");
607 }
608 if (alg != nullptr && kid != nullptr && kty != nullptr &&
609 strcmp(kid, header_kid) == 0 && strcmp(alg, header_alg) == 0) {
610 return pkey_from_jwk(jkey, kty);
611 }
612 }
613 gpr_log(GPR_ERROR,
614 "Could not find matching key in key set for kid=%s and alg=%s",
615 header_kid, header_alg);
616 return nullptr;
617 }
618
619 static int verify_jwt_signature(EVP_PKEY* key, const char* alg,
620 const grpc_slice& signature,
621 const grpc_slice& signed_data) {
622 EVP_MD_CTX* md_ctx = EVP_MD_CTX_create();
623 const EVP_MD* md = evp_md_from_alg(alg);
624 int result = 0;
625
626 GPR_ASSERT(md != nullptr); /* Checked before. */
627 if (md_ctx == nullptr) {
628 gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX.");
629 goto end;
630 }
631 if (EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key) != 1) {
632 gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed.");
633 goto end;
634 }
635 if (EVP_DigestVerifyUpdate(md_ctx, GRPC_SLICE_START_PTR(signed_data),
636 GRPC_SLICE_LENGTH(signed_data)) != 1) {
637 gpr_log(GPR_ERROR, "EVP_DigestVerifyUpdate failed.");
638 goto end;
639 }
640 if (EVP_DigestVerifyFinal(md_ctx, GRPC_SLICE_START_PTR(signature),
641 GRPC_SLICE_LENGTH(signature)) != 1) {
642 gpr_log(GPR_ERROR, "JWT signature verification failed.");
643 goto end;
644 }
645 result = 1;
646
647 end:
648 EVP_MD_CTX_destroy(md_ctx);
649 return result;
650 }
651
652 static void on_keys_retrieved(void* user_data, grpc_error_handle /*error*/) {
653 verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(user_data);
654 Json json = json_from_http(&ctx->responses[HTTP_RESPONSE_KEYS]);
655 EVP_PKEY* verification_key = nullptr;
656 grpc_jwt_verifier_status status = GRPC_JWT_VERIFIER_GENERIC_ERROR;
657 grpc_jwt_claims* claims = nullptr;
658
659 if (json.type() == Json::Type::JSON_NULL) {
660 status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
661 goto end;
662 }
663 verification_key =
664 find_verification_key(json, ctx->header->alg, ctx->header->kid);
665 if (verification_key == nullptr) {
666 gpr_log(GPR_ERROR, "Could not find verification key with kid %s.",
667 ctx->header->kid);
668 status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
669 goto end;
670 }
671
672 if (!verify_jwt_signature(verification_key, ctx->header->alg, ctx->signature,
673 ctx->signed_data)) {
674 status = GRPC_JWT_VERIFIER_BAD_SIGNATURE;
675 goto end;
676 }
677
678 status = grpc_jwt_claims_check(ctx->claims, ctx->audience);
679 if (status == GRPC_JWT_VERIFIER_OK) {
680 /* Pass ownership. */
681 claims = ctx->claims;
682 ctx->claims = nullptr;
683 }
684
685 end:
686 EVP_PKEY_free(verification_key);
687 ctx->user_cb(ctx->user_data, status, claims);
688 verifier_cb_ctx_destroy(ctx);
689 }
690
691 static void on_openid_config_retrieved(void* user_data,
692 grpc_error_handle /*error*/) {
693 verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(user_data);
694 const grpc_http_response* response = &ctx->responses[HTTP_RESPONSE_OPENID];
695 Json json = json_from_http(response);
696 grpc_http_request req;
697 memset(&req, 0, sizeof(grpc_http_request));
698 const char* jwks_uri;
699 const Json* cur;
700 absl::StatusOr<grpc_core::URI> uri;
701 char* host;
702 char* path;
703
704 /* TODO(jboeuf): Cache the jwks_uri in order to avoid this hop next time. */
705 if (json.type() == Json::Type::JSON_NULL) goto error;
706 cur = find_property_by_name(json, "jwks_uri");
707 if (cur == nullptr) {
708 gpr_log(GPR_ERROR, "Could not find jwks_uri in openid config.");
709 goto error;
710 }
711 jwks_uri = validate_string_field(*cur, "jwks_uri");
712 if (jwks_uri == nullptr) goto error;
713 if (strstr(jwks_uri, "https://") != jwks_uri) {
714 gpr_log(GPR_ERROR, "Invalid non https jwks_uri: %s.", jwks_uri);
715 goto error;
716 }
717 jwks_uri += 8;
718 host = gpr_strdup(jwks_uri);
719 path = const_cast<char*>(strchr(jwks_uri, '/'));
720 if (path == nullptr) {
721 path = const_cast<char*>("");
722 } else {
723 *(host + (path - jwks_uri)) = '\0';
724 }
725
726 /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
727 channel. This would allow us to cancel an authentication query when under
728 extreme memory pressure. */
729 uri = grpc_core::URI::Create("https", host, path, {} /* query params /*/,
730 "" /* fragment */);
731 if (!uri.ok()) {
732 goto error;
733 }
734 ctx->http_request = grpc_core::HttpRequest::Get(
735 std::move(*uri), nullptr /* channel args */, &ctx->pollent, &req,
736 grpc_core::Timestamp::Now() + grpc_jwt_verifier_max_delay,
737 GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx),
738 &ctx->responses[HTTP_RESPONSE_KEYS],
739 grpc_core::CreateHttpRequestSSLCredentials());
740 ctx->http_request->Start();
741 gpr_free(host);
742 return;
743
744 error:
745 ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
746 verifier_cb_ctx_destroy(ctx);
747 }
748
749 static email_key_mapping* verifier_get_mapping(grpc_jwt_verifier* v,
750 const char* email_domain) {
751 size_t i;
752 if (v->mappings == nullptr) return nullptr;
753 for (i = 0; i < v->num_mappings; i++) {
754 if (strcmp(email_domain, v->mappings[i].email_domain) == 0) {
755 return &v->mappings[i];
756 }
757 }
758 return nullptr;
759 }
760
761 static void verifier_put_mapping(grpc_jwt_verifier* v, const char* email_domain,
762 const char* key_url_prefix) {
763 email_key_mapping* mapping = verifier_get_mapping(v, email_domain);
764 GPR_ASSERT(v->num_mappings < v->allocated_mappings);
765 if (mapping != nullptr) {
766 gpr_free(mapping->key_url_prefix);
767 mapping->key_url_prefix = gpr_strdup(key_url_prefix);
768 return;
769 }
770 v->mappings[v->num_mappings].email_domain = gpr_strdup(email_domain);
771 v->mappings[v->num_mappings].key_url_prefix = gpr_strdup(key_url_prefix);
772 v->num_mappings++;
773 GPR_ASSERT(v->num_mappings <= v->allocated_mappings);
774 }
775
776 /* Very non-sophisticated way to detect an email address. Should be good
777 enough for now... */
778 const char* grpc_jwt_issuer_email_domain(const char* issuer) {
779 const char* at_sign = strchr(issuer, '@');
780 if (at_sign == nullptr) return nullptr;
781 const char* email_domain = at_sign + 1;
782 if (*email_domain == '\0') return nullptr;
783 const char* dot = strrchr(email_domain, '.');
784 if (dot == nullptr || dot == email_domain) return email_domain;
785 GPR_ASSERT(dot > email_domain);
786 /* There may be a subdomain, we just want the domain. */
787 dot = static_cast<const char*>(
788 gpr_memrchr(email_domain, '.', static_cast<size_t>(dot - email_domain)));
789 if (dot == nullptr) return email_domain;
790 return dot + 1;
791 }
792
793 /* Takes ownership of ctx. */
794 static void retrieve_key_and_verify(verifier_cb_ctx* ctx) {
795 const char* email_domain;
796 grpc_closure* http_cb;
797 char* path_prefix = nullptr;
798 const char* iss;
799 grpc_http_request req;
800 memset(&req, 0, sizeof(grpc_http_request));
801 http_response_index rsp_idx;
802 char* host;
803 char* path;
804 absl::StatusOr<grpc_core::URI> uri;
805
806 GPR_ASSERT(ctx != nullptr && ctx->header != nullptr &&
807 ctx->claims != nullptr);
808 iss = ctx->claims->iss;
809 if (ctx->header->kid == nullptr) {
810 gpr_log(GPR_ERROR, "Missing kid in jose header.");
811 goto error;
812 }
813 if (iss == nullptr) {
814 gpr_log(GPR_ERROR, "Missing iss in claims.");
815 goto error;
816 }
817
818 /* This code relies on:
819 https://openid.net/specs/openid-connect-discovery-1_0.html
820 Nobody seems to implement the account/email/webfinger part 2. of the spec
821 so we will rely instead on email/url mappings if we detect such an issuer.
822 Part 4, on the other hand is implemented by both google and salesforce. */
823 email_domain = grpc_jwt_issuer_email_domain(iss);
824 if (email_domain != nullptr) {
825 email_key_mapping* mapping;
826 GPR_ASSERT(ctx->verifier != nullptr);
827 mapping = verifier_get_mapping(ctx->verifier, email_domain);
828 if (mapping == nullptr) {
829 gpr_log(GPR_ERROR, "Missing mapping for issuer email.");
830 goto error;
831 }
832 host = gpr_strdup(mapping->key_url_prefix);
833 path_prefix = strchr(host, '/');
834 if (path_prefix == nullptr) {
835 gpr_asprintf(&path, "/%s", iss);
836 } else {
837 *(path_prefix++) = '\0';
838 gpr_asprintf(&path, "/%s/%s", path_prefix, iss);
839 }
840 http_cb =
841 GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx);
842 rsp_idx = HTTP_RESPONSE_KEYS;
843 } else {
844 host = gpr_strdup(strstr(iss, "https://") == iss ? iss + 8 : iss);
845 path_prefix = strchr(host, '/');
846 if (path_prefix == nullptr) {
847 path = gpr_strdup(GRPC_OPENID_CONFIG_URL_SUFFIX);
848 } else {
849 *(path_prefix++) = 0;
850 gpr_asprintf(&path, "/%s%s", path_prefix, GRPC_OPENID_CONFIG_URL_SUFFIX);
851 }
852 http_cb = GRPC_CLOSURE_CREATE(on_openid_config_retrieved, ctx,
853 grpc_schedule_on_exec_ctx);
854 rsp_idx = HTTP_RESPONSE_OPENID;
855 }
856
857 /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
858 channel. This would allow us to cancel an authentication query when under
859 extreme memory pressure. */
860 uri = grpc_core::URI::Create("https", host, path, {} /* query params */,
861 "" /* fragment */);
862 if (!uri.ok()) {
863 goto error;
864 }
865 ctx->http_request = grpc_core::HttpRequest::Get(
866 std::move(*uri), nullptr /* channel args */, &ctx->pollent, &req,
867 grpc_core::Timestamp::Now() + grpc_jwt_verifier_max_delay, http_cb,
868 &ctx->responses[rsp_idx], grpc_core::CreateHttpRequestSSLCredentials());
869 ctx->http_request->Start();
870 gpr_free(host);
871 gpr_free(path);
872 return;
873
874 error:
875 ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
876 verifier_cb_ctx_destroy(ctx);
877 }
878
879 void grpc_jwt_verifier_verify(grpc_jwt_verifier* verifier,
880 grpc_pollset* pollset, const char* jwt,
881 const char* audience,
882 grpc_jwt_verification_done_cb cb,
883 void* user_data) {
884 const char* dot = nullptr;
885 jose_header* header = nullptr;
886 grpc_jwt_claims* claims = nullptr;
887 grpc_slice signature;
888 size_t signed_jwt_len;
889 const char* cur = jwt;
890 Json json;
891
892 GPR_ASSERT(verifier != nullptr && jwt != nullptr && audience != nullptr &&
893 cb != nullptr);
894 dot = strchr(cur, '.');
895 if (dot == nullptr) goto error;
896 json = parse_json_part_from_jwt(cur, static_cast<size_t>(dot - cur));
897 if (json.type() == Json::Type::JSON_NULL) goto error;
898 header = jose_header_from_json(std::move(json));
899 if (header == nullptr) goto error;
900
901 cur = dot + 1;
902 dot = strchr(cur, '.');
903 if (dot == nullptr) goto error;
904 json = parse_json_part_from_jwt(cur, static_cast<size_t>(dot - cur));
905 if (json.type() == Json::Type::JSON_NULL) goto error;
906 claims = grpc_jwt_claims_from_json(std::move(json));
907 if (claims == nullptr) goto error;
908
909 signed_jwt_len = static_cast<size_t>(dot - jwt);
910 cur = dot + 1;
911 signature = grpc_base64_decode(cur, 1);
912 if (GRPC_SLICE_IS_EMPTY(signature)) goto error;
913 retrieve_key_and_verify(
914 verifier_cb_ctx_create(verifier, pollset, header, claims, audience,
915 signature, jwt, signed_jwt_len, user_data, cb));
916 return;
917
918 error:
919 if (header != nullptr) jose_header_destroy(header);
920 if (claims != nullptr) grpc_jwt_claims_destroy(claims);
921 cb(user_data, GRPC_JWT_VERIFIER_BAD_FORMAT, nullptr);
922 }
923
924 grpc_jwt_verifier* grpc_jwt_verifier_create(
925 const grpc_jwt_verifier_email_domain_key_url_mapping* mappings,
926 size_t num_mappings) {
927 grpc_jwt_verifier* v = grpc_core::Zalloc<grpc_jwt_verifier>();
928
929 /* We know at least of one mapping. */
930 v->allocated_mappings = 1 + num_mappings;
931 v->mappings = static_cast<email_key_mapping*>(
932 gpr_malloc(v->allocated_mappings * sizeof(email_key_mapping)));
933 verifier_put_mapping(v, GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN,
934 GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX);
935 /* User-Provided mappings. */
936 if (mappings != nullptr) {
937 size_t i;
938 for (i = 0; i < num_mappings; i++) {
939 verifier_put_mapping(v, mappings[i].email_domain,
940 mappings[i].key_url_prefix);
941 }
942 }
943 return v;
944 }
945
946 void grpc_jwt_verifier_destroy(grpc_jwt_verifier* v) {
947 size_t i;
948 if (v == nullptr) return;
949 if (v->mappings != nullptr) {
950 for (i = 0; i < v->num_mappings; i++) {
951 gpr_free(v->mappings[i].email_domain);
952 gpr_free(v->mappings[i].key_url_prefix);
953 }
954 gpr_free(v->mappings);
955 }
956 gpr_free(v);
957 }