Debian Codegraph @

src/core/lib/security/credentials/jwt/json_token.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/json_token.h"
22
23 #include <stdint.h>
24 #include <string.h>
25
26 #include <string>
27 #include <utility>
28
29 #include <openssl/bio.h>
30 #include <openssl/evp.h>
31 #include <openssl/pem.h>
32 #include <openssl/rsa.h>
33
34 #include "absl/status/status.h"
35 #include "absl/status/statusor.h"
36
37 #include <grpc/grpc_security.h>
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/log.h>
40 #include <grpc/support/time.h>
41
42 #include "src/core/lib/iomgr/error.h"
43 #include "src/core/lib/security/util/json_util.h"
44 #include "src/core/lib/slice/b64.h"
45
46 using grpc_core::Json;
47
48 /* --- Constants. --- */
49
50 /* 1 hour max. */
51 gpr_timespec grpc_max_auth_token_lifetime() {
52 gpr_timespec out;
53 out.tv_sec = 3600;
54 out.tv_nsec = 0;
55 out.clock_type = GPR_TIMESPAN;
56 return out;
57 }
58
59 #define GRPC_JWT_RSA_SHA256_ALGORITHM "RS256"
60 #define GRPC_JWT_TYPE "JWT"
61
62 /* --- Override for testing. --- */
63
64 static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override =
65 nullptr;
66
67 /* --- grpc_auth_json_key. --- */
68
69 int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key) {
70 return (json_key != nullptr) &&
71 strcmp(json_key->type, GRPC_AUTH_JSON_TYPE_INVALID) != 0;
72 }
73
74 grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) {
75 grpc_auth_json_key result;
76 BIO* bio = nullptr;
77 const char* prop_value;
78 int success = 0;
79 grpc_error_handle error;
80
81 memset(&result, 0, sizeof(grpc_auth_json_key));
82 result.type = GRPC_AUTH_JSON_TYPE_INVALID;
83 if (json.type() == Json::Type::JSON_NULL) {
84 gpr_log(GPR_ERROR, "Invalid json.");
85 goto end;
86 }
87
88 prop_value = grpc_json_get_string_property(json, "type", &error);
89 GRPC_LOG_IF_ERROR("JSON key parsing", error);
90 if (prop_value == nullptr ||
91 strcmp(prop_value, GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT) != 0) {
92 goto end;
93 }
94 result.type = GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT;
95
96 if (!grpc_copy_json_string_property(json, "private_key_id",
97 &result.private_key_id) ||
98 !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
99 !grpc_copy_json_string_property(json, "client_email",
100 &result.client_email)) {
101 goto end;
102 }
103
104 prop_value = grpc_json_get_string_property(json, "private_key", &error);
105 GRPC_LOG_IF_ERROR("JSON key parsing", error);
106 if (prop_value == nullptr) {
107 goto end;
108 }
109 bio = BIO_new(BIO_s_mem());
110 success = BIO_puts(bio, prop_value);
111 if ((success < 0) || (static_cast<size_t>(success) != strlen(prop_value))) {
112 gpr_log(GPR_ERROR, "Could not write into openssl BIO.");
113 goto end;
114 }
115 result.private_key =
116 PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, const_cast<char*>(""));
117 if (result.private_key == nullptr) {
118 gpr_log(GPR_ERROR, "Could not deserialize private key.");
119 goto end;
120 }
121 success = 1;
122
123 end:
124 if (bio != nullptr) BIO_free(bio);
125 if (!success) grpc_auth_json_key_destruct(&result);
126 return result;
127 }
128
129 grpc_auth_json_key grpc_auth_json_key_create_from_string(
130 const char* json_string) {
131 Json json;
132 auto json_or = Json::Parse(json_string);
133 if (!json_or.ok()) {
134 gpr_log(GPR_ERROR, "JSON key parsing error: %s",
135 json_or.status().ToString().c_str());
136 } else {
137 json = std::move(*json_or);
138 }
139 return grpc_auth_json_key_create_from_json(json);
140 }
141
142 void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) {
143 if (json_key == nullptr) return;
144 json_key->type = GRPC_AUTH_JSON_TYPE_INVALID;
145 if (json_key->client_id != nullptr) {
146 gpr_free(json_key->client_id);
147 json_key->client_id = nullptr;
148 }
149 if (json_key->private_key_id != nullptr) {
150 gpr_free(json_key->private_key_id);
151 json_key->private_key_id = nullptr;
152 }
153 if (json_key->client_email != nullptr) {
154 gpr_free(json_key->client_email);
155 json_key->client_email = nullptr;
156 }
157 if (json_key->private_key != nullptr) {
158 RSA_free(json_key->private_key);
159 json_key->private_key = nullptr;
160 }
161 }
162
163 /* --- jwt encoding and signature. --- */
164
165 static char* encoded_jwt_header(const char* key_id, const char* algorithm) {
166 Json json = Json::Object{
167 {"alg", algorithm},
168 {"typ", GRPC_JWT_TYPE},
169 {"kid", key_id},
170 };
171 std::string json_str = json.Dump();
172 return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
173 }
174
175 static char* encoded_jwt_claim(const grpc_auth_json_key* json_key,
176 const char* audience,
177 gpr_timespec token_lifetime, const char* scope) {
178 gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
179 gpr_timespec expiration = gpr_time_add(now, token_lifetime);
180 if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) > 0) {
181 gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value.");
182 expiration = gpr_time_add(now, grpc_max_auth_token_lifetime());
183 }
184
185 Json::Object object = {
186 {"iss", json_key->client_email},
187 {"aud", audience},
188 {"iat", now.tv_sec},
189 {"exp", expiration.tv_sec},
190 };
191 if (scope != nullptr) {
192 object["scope"] = scope;
193 } else {
194 /* Unscoped JWTs need a sub field. */
195 object["sub"] = json_key->client_email;
196 }
197
198 Json json(object);
199 std::string json_str = json.Dump();
200 return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
201 }
202
203 static char* dot_concat_and_free_strings(char* str1, char* str2) {
204 size_t str1_len = strlen(str1);
205 size_t str2_len = strlen(str2);
206 size_t result_len = str1_len + 1 /* dot */ + str2_len;
207 char* result =
208 static_cast<char*>(gpr_malloc(result_len + 1 /* NULL terminated */));
209 char* current = result;
210 memcpy(current, str1, str1_len);
211 current += str1_len;
212 *(current++) = '.';
213 memcpy(current, str2, str2_len);
214 current += str2_len;
215 GPR_ASSERT(current >= result);
216 GPR_ASSERT((uintptr_t)(current - result) == result_len);
217 *current = '\0';
218 gpr_free(str1);
219 gpr_free(str2);
220 return result;
221 }
222
223 const EVP_MD* openssl_digest_from_algorithm(const char* algorithm) {
224 if (strcmp(algorithm, GRPC_JWT_RSA_SHA256_ALGORITHM) == 0) {
225 return EVP_sha256();
226 } else {
227 gpr_log(GPR_ERROR, "Unknown algorithm %s.", algorithm);
228 return nullptr;
229 }
230 }
231
232 char* compute_and_encode_signature(const grpc_auth_json_key* json_key,
233 const char* signature_algorithm,
234 const char* to_sign) {
235 const EVP_MD* md = openssl_digest_from_algorithm(signature_algorithm);
236 EVP_MD_CTX* md_ctx = nullptr;
237 EVP_PKEY* key = EVP_PKEY_new();
238 size_t sig_len = 0;
239 unsigned char* sig = nullptr;
240 char* result = nullptr;
241 if (md == nullptr) return nullptr;
242 md_ctx = EVP_MD_CTX_create();
243 if (md_ctx == nullptr) {
244 gpr_log(GPR_ERROR, "Could not create MD_CTX");
245 goto end;
246 }
247 EVP_PKEY_set1_RSA(key, json_key->private_key);
248 if (EVP_DigestSignInit(md_ctx, nullptr, md, nullptr, key) != 1) {
249 gpr_log(GPR_ERROR, "DigestInit failed.");
250 goto end;
251 }
252 if (EVP_DigestSignUpdate(md_ctx, to_sign, strlen(to_sign)) != 1) {
253 gpr_log(GPR_ERROR, "DigestUpdate failed.");
254 goto end;
255 }
256 if (EVP_DigestSignFinal(md_ctx, nullptr, &sig_len) != 1) {
257 gpr_log(GPR_ERROR, "DigestFinal (get signature length) failed.");
258 goto end;
259 }
260 sig = static_cast<unsigned char*>(gpr_malloc(sig_len));
261 if (EVP_DigestSignFinal(md_ctx, sig, &sig_len) != 1) {
262 gpr_log(GPR_ERROR, "DigestFinal (signature compute) failed.");
263 goto end;
264 }
265 result = grpc_base64_encode(sig, sig_len, 1, 0);
266
267 end:
268 if (key != nullptr) EVP_PKEY_free(key);
269 if (md_ctx != nullptr) EVP_MD_CTX_destroy(md_ctx);
270 if (sig != nullptr) gpr_free(sig);
271 return result;
272 }
273
274 char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key,
275 const char* audience,
276 gpr_timespec token_lifetime, const char* scope) {
277 if (g_jwt_encode_and_sign_override != nullptr) {
278 return g_jwt_encode_and_sign_override(json_key, audience, token_lifetime,
279 scope);
280 } else {
281 const char* sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM;
282 char* to_sign = dot_concat_and_free_strings(
283 encoded_jwt_header(json_key->private_key_id, sig_algo),
284 encoded_jwt_claim(json_key, audience, token_lifetime, scope));
285 char* sig = compute_and_encode_signature(json_key, sig_algo, to_sign);
286 if (sig == nullptr) {
287 gpr_free(to_sign);
288 return nullptr;
289 }
290 return dot_concat_and_free_strings(to_sign, sig);
291 }
292 }
293
294 void grpc_jwt_encode_and_sign_set_override(
295 grpc_jwt_encode_and_sign_override func) {
296 g_jwt_encode_and_sign_override = func;
297 }