2 This file is part of GNUnet
3 Copyright (C) 2010-2015 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file reclaim/oidc_helper.c
23 * @brief helper library for OIDC related functions
24 * @author Martin Schanzenbach
29 #include "gnunet_util_lib.h"
30 #include "gnunet_reclaim_attribute_lib.h"
31 #include "gnunet_reclaim_service.h"
32 #include "gnunet_signatures.h"
33 #include "oidc_helper.h"
34 //#include "benchmark.h"
37 GNUNET_NETWORK_STRUCT_BEGIN
40 * The signature used to generate the authorization code
42 struct OIDC_Parameters
47 const struct GNUNET_RECLAIM_Ticket *ticket;
52 uint32_t nonce GNUNET_PACKED;
55 * The length of the PKCE code_challenge
57 uint16_t code_challenge_len GNUNET_PACKED;
60 * The length of the attributes list
62 uint16_t attr_list_len GNUNET_PACKED;
65 GNUNET_NETWORK_STRUCT_END
68 create_jwt_header (void)
73 root = json_object ();
74 json_object_set_new (root, JWT_ALG, json_string (JWT_ALG_VALUE));
75 json_object_set_new (root, JWT_TYP, json_string (JWT_TYP_VALUE));
77 json_str = json_dumps (root, JSON_INDENT (0) | JSON_COMPACT);
83 replace_char (char *str, char find, char replace)
85 char *current_pos = strchr (str, find);
88 *current_pos = replace;
89 current_pos = strchr (current_pos, find);
95 fix_base64 (char *str)
98 replace_char (str, '+', '-');
101 replace_char (str, '/', '_');
105 * Create a JWT from attributes
107 * @param aud_key the public of the audience
108 * @param sub_key the public key of the subject
109 * @param attrs the attribute list
110 * @param expiration_time the validity of the token
111 * @param secret_key the key used to sign the JWT
112 * @return a new base64-encoded JWT string.
115 OIDC_id_token_new (const struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key,
116 const struct GNUNET_CRYPTO_EcdsaPublicKey *sub_key,
117 const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs,
118 const struct GNUNET_TIME_Relative *expiration_time,
120 const char *secret_key)
122 struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le;
123 struct GNUNET_HashCode signature;
124 struct GNUNET_TIME_Absolute exp_time;
125 struct GNUNET_TIME_Absolute time_now;
133 char *signature_target;
134 char *signature_base64;
138 // iat REQUIRED time now
139 time_now = GNUNET_TIME_absolute_get ();
140 // exp REQUIRED time expired from config
141 exp_time = GNUNET_TIME_absolute_add (time_now, *expiration_time);
142 // auth_time only if max_age
143 // nonce only if nonce
144 // OPTIONAL acr,amr,azp
146 GNUNET_STRINGS_data_to_string_alloc (sub_key,
148 GNUNET_CRYPTO_EcdsaPublicKey));
150 GNUNET_STRINGS_data_to_string_alloc (aud_key,
152 GNUNET_CRYPTO_EcdsaPublicKey));
153 header = create_jwt_header ();
154 body = json_object ();
156 // iss REQUIRED case sensitive server uri with https
157 // The issuer is the local reclaim instance (e.g.
158 // https://reclaim.id/api/openid)
159 json_object_set_new (body, "iss", json_string (SERVER_ADDRESS));
160 // sub REQUIRED public key identity, not exceed 255 ASCII length
161 json_object_set_new (body, "sub", json_string (subject));
162 // aud REQUIRED public key client_id must be there
163 json_object_set_new (body, "aud", json_string (audience));
165 json_object_set_new (body,
167 json_integer (time_now.abs_value_us / (1000 * 1000)));
169 json_object_set_new (body,
171 json_integer (exp_time.abs_value_us / (1000 * 1000)));
173 json_object_set_new (body,
175 json_integer (time_now.abs_value_us / (1000 * 1000)));
178 json_object_set_new (body, "nonce", json_string (nonce));
180 for (le = attrs->list_head; NULL != le; le = le->next)
183 GNUNET_RECLAIM_ATTRIBUTE_value_to_string (le->claim->type,
185 le->claim->data_size);
186 json_object_set_new (body, le->claim->name, json_string (attr_val_str));
187 GNUNET_free (attr_val_str);
189 body_str = json_dumps (body, JSON_INDENT (0) | JSON_COMPACT);
192 GNUNET_STRINGS_base64_encode (header, strlen (header), &header_base64);
193 fix_base64 (header_base64);
195 GNUNET_STRINGS_base64_encode (body_str, strlen (body_str), &body_base64);
196 fix_base64 (body_base64);
198 GNUNET_free (subject);
199 GNUNET_free (audience);
202 * Creating the JWT signature. This might not be
203 * standards compliant, check.
205 GNUNET_asprintf (&signature_target, "%s.%s", header_base64, body_base64);
206 GNUNET_CRYPTO_hmac_raw (secret_key,
209 strlen (signature_target),
211 GNUNET_STRINGS_base64_encode ((const char *) &signature,
212 sizeof (struct GNUNET_HashCode),
214 fix_base64 (signature_base64);
216 GNUNET_asprintf (&result,
222 GNUNET_free (signature_target);
223 GNUNET_free (header);
224 GNUNET_free (body_str);
225 GNUNET_free (signature_base64);
226 GNUNET_free (body_base64);
227 GNUNET_free (header_base64);
231 /* Converts a hex character to its integer value */
235 return isdigit (ch) ? ch - '0' : tolower (ch) - 'a' + 10;
238 /* Converts an integer value to its hex character*/
242 static char hex[] = "0123456789abcdef";
243 return hex[code & 15];
246 /* Returns a url-encoded version of str */
247 /* IMPORTANT: be sure to free() the returned string after use */
249 url_encode (const char *str)
251 char *pstr = (char *) str;
252 char *buf = GNUNET_malloc (strlen (str) * 3 + 1);
256 if (isalnum (*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' ||
259 else if (*pstr == ' ')
264 *pbuf++ = to_hex (*pstr >> 4);
265 *pbuf++ = to_hex (*pstr & 15);
274 /* Returns a url-decoded version of str */
275 /* IMPORTANT: be sure to free() the returned string after use */
277 url_decode (const char *str)
279 char *pstr = (char *) str;
280 char *buf = GNUNET_malloc (strlen (str) + 1);
286 if (pstr[1] && pstr[2])
288 *pbuf++ = from_hex (pstr[1]) << 4 | from_hex (pstr[2]);
292 else if (*pstr == '+')
308 * Returns base64 encoded string urlencoded
310 * @param string the string to encode
311 * @return base64 encoded string
314 base64_encode (const char *data, size_t data_size)
319 GNUNET_STRINGS_base64_encode (data, data_size, &enc);
320 enc_urlencode = url_encode (enc);
322 return enc_urlencode;
327 derive_aes_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
328 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
329 struct GNUNET_HashCode *key_material)
331 static const char ctx_key[] = "reclaim-aes-ctx-key";
332 static const char ctx_iv[] = "reclaim-aes-ctx-iv";
333 GNUNET_CRYPTO_kdf (key,
334 sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
338 sizeof (struct GNUNET_HashCode),
340 GNUNET_CRYPTO_kdf (iv,
342 struct GNUNET_CRYPTO_SymmetricInitializationVector),
346 sizeof (struct GNUNET_HashCode),
352 calculate_key_priv (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
353 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
354 const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
355 const struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub)
357 struct GNUNET_HashCode key_material;
358 GNUNET_CRYPTO_ecdsa_ecdh (ecdsa_priv, ecdh_pub, &key_material);
359 derive_aes_key (key, iv, &key_material);
364 calculate_key_pub (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
365 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
366 const struct GNUNET_CRYPTO_EcdsaPublicKey *ecdsa_pub,
367 const struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv)
369 struct GNUNET_HashCode key_material;
370 GNUNET_CRYPTO_ecdh_ecdsa (ecdh_priv, ecdsa_pub, &key_material);
371 derive_aes_key (key, iv, &key_material);
376 decrypt_payload (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
377 const struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub,
382 struct GNUNET_CRYPTO_SymmetricSessionKey key;
383 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
385 calculate_key_priv (&key, &iv, ecdsa_priv, ecdh_pub);
386 GNUNET_break (GNUNET_CRYPTO_symmetric_decrypt (ct, ct_len, &key, &iv, buf));
391 encrypt_payload (const struct GNUNET_CRYPTO_EcdsaPublicKey *ecdsa_pub,
392 const struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv,
397 struct GNUNET_CRYPTO_SymmetricSessionKey key;
398 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
400 calculate_key_pub (&key, &iv, ecdsa_pub, ecdh_priv);
402 GNUNET_CRYPTO_symmetric_encrypt (payload, payload_len, &key, &iv, buf));
406 * Builds an OIDC authorization code including
407 * a reclaim ticket and nonce
409 * @param issuer the issuer of the ticket, used to sign the ticket and nonce
410 * @param ticket the ticket to include in the code
411 * @param attrs list of attributes which are shared
412 * @param nonce the nonce to include in the code
413 * @param code_challenge PKCE code challenge
414 * @return a new authorization code (caller must free)
417 OIDC_build_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer,
418 const struct GNUNET_RECLAIM_Ticket *ticket,
419 struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs,
420 const char *nonce_str,
421 const char *code_challenge)
423 struct OIDC_Parameters params;
428 char *buf_ptr = NULL;
430 size_t code_payload_len;
431 size_t attr_list_len = 0;
434 struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
435 struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv;
436 struct GNUNET_CRYPTO_EcdhePublicKey ecdh_pub;
440 memset (¶ms, 0, sizeof (params));
441 params.ticket = ticket;
444 payload_len = sizeof (struct OIDC_Parameters);
445 if (NULL != nonce_str && strcmp ("", nonce_str) != 0)
447 if ((1 != SSCANF (nonce_str, "%u", &nonce)) || (nonce > UINT32_MAX))
450 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid nonce %s\n", nonce_str);
453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
454 "Got nonce: %u from %s\n",
458 nonce_tmp = htonl (nonce);
459 params.nonce = nonce_tmp;
460 // Assign code challenge
461 if (NULL == code_challenge || strcmp ("", code_challenge) == 0)
464 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "PKCE: Code challenge missing");
467 payload_len += strlen (code_challenge);
468 params.code_challenge_len = htonl (strlen (code_challenge));
473 attr_list_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size (attrs);
474 params.attr_list_len = htonl (attr_list_len);
475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
476 "Length of serialized attributes: %lu\n",
478 // Get serialized attributes
479 payload_len += attr_list_len;
481 // Get plaintext length
482 payload = GNUNET_malloc (payload_len);
483 memcpy (payload, ¶ms, sizeof (params));
484 tmp = payload + sizeof (params);
485 memcpy (tmp, code_challenge, strlen (code_challenge));
486 tmp += strlen (code_challenge);
487 if (0 < attr_list_len)
488 GNUNET_RECLAIM_ATTRIBUTE_list_serialize (attrs, tmp);
493 code_payload_len = sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
494 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
495 payload_len + sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497 "Length of data to encode: %lu\n",
501 ecdh_priv = GNUNET_CRYPTO_ecdhe_key_create ();
502 GNUNET_CRYPTO_ecdhe_key_get_public (ecdh_priv, &ecdh_pub);
503 // Initialize code payload
504 code_payload = GNUNET_malloc (code_payload_len);
505 GNUNET_assert (NULL != code_payload);
506 purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
507 purpose->size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
508 sizeof (ecdh_pub) + payload_len);
509 purpose->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN);
511 buf_ptr = (char *) &purpose[1];
512 memcpy (buf_ptr, &ecdh_pub, sizeof (ecdh_pub));
513 buf_ptr += sizeof (ecdh_pub);
514 // Encrypt plaintext and store
515 encrypt_payload (&ticket->audience,
520 GNUNET_free (ecdh_priv);
521 GNUNET_free (payload);
522 buf_ptr += payload_len;
523 // Sign and store signature
525 GNUNET_CRYPTO_ecdsa_sign (issuer,
527 (struct GNUNET_CRYPTO_EcdsaSignature *)
531 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unable to sign code\n");
532 GNUNET_free (code_payload);
535 code_str = base64_encode (code_payload, code_payload_len);
536 GNUNET_free (code_payload);
542 * Parse reclaim ticket and nonce from
543 * authorization code.
544 * This also verifies the signature in the code.
546 * @param audience the expected audience of the code
547 * @param code the string representation of the code
548 * @param code_verfier PKCE code verifier
549 * @param ticket where to store the ticket
550 * @param attrs the attributes in the code
551 * @param nonce where to store the nonce
552 * @return GNUNET_OK if successful, else GNUNET_SYSERR
555 OIDC_parse_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
557 const char *code_verifier,
558 struct GNUNET_RECLAIM_Ticket *ticket,
559 struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList **attrs,
566 char *expected_code_challenge;
567 char *code_challenge;
568 char *code_verifier_hash;
569 struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
570 struct GNUNET_CRYPTO_EcdsaSignature *signature;
571 struct GNUNET_CRYPTO_EcdsaPublicKey ecdsa_pub;
572 struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub;
573 size_t code_challenge_len;
574 size_t attrs_ser_len;
575 size_t plaintext_len;
576 size_t code_payload_len;
578 struct OIDC_Parameters *params;
580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to decode `%s'\n", code);
583 GNUNET_STRINGS_base64_decode (code, strlen (code), (void **) &code_payload);
584 if (code_payload_len < sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
585 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
586 sizeof (struct OIDC_Parameters) +
587 sizeof (struct GNUNET_CRYPTO_EcdsaSignature))
589 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Authorization code malformed\n");
590 GNUNET_free_non_null (code_payload);
591 return GNUNET_SYSERR;
594 purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
595 plaintext_len = code_payload_len;
596 plaintext_len -= sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose);
597 ptr = (char *) &purpose[1];
599 ecdh_pub = (struct GNUNET_CRYPTO_EcdhePublicKey *) ptr;
600 ptr += sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
601 plaintext_len -= sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
603 // Decrypt ciphertext
604 plaintext_len -= sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
605 plaintext = GNUNET_malloc (plaintext_len);
606 decrypt_payload (ecdsa_priv, ecdh_pub, ptr, plaintext_len, plaintext);
608 params = (struct OIDC_Parameters *) plaintext;
610 // cmp code_challenge code_verifier
611 code_verifier_hash = GNUNET_malloc (strlen (code_verifier));
612 // hash code verifier
613 gcry_md_hash_buffer (GCRY_MD_SHA256,
616 strlen (code_verifier));
617 // encode code verifier
618 expected_code_challenge =
619 base64_encode (code_verifier_hash, strlen (code_verifier_hash));
620 code_challenge = (char*)¶ms[1];
621 code_challenge_len = ntohl (params->code_challenge_len);
622 GNUNET_free (code_verifier_hash);
623 if ((strlen (expected_code_challenge) != code_challenge_len) ||
625 strncmp (expected_code_challenge, code_challenge, code_challenge_len)))
627 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid code verifier\n");
628 GNUNET_free_non_null (code_payload);
629 GNUNET_free (expected_code_challenge);
630 return GNUNET_SYSERR;
632 GNUNET_free (expected_code_challenge);
634 memcpy (ticket, params->ticket, sizeof (*ticket));
636 nonce = ntohl (params->nonce); //ntohl (*((uint32_t *) ptr));
637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got nonce: %u\n", nonce);
639 attrs_ser = ((char *) ¶ms[1]) + code_challenge_len;
640 attrs_ser_len = ntohl (params->attr_list_len);
642 GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (attrs_ser,
645 signature = (struct GNUNET_CRYPTO_EcdsaSignature *) attrs_ser + attrs_ser_len;
646 GNUNET_CRYPTO_ecdsa_key_get_public (ecdsa_priv, &ecdsa_pub);
647 if (0 != GNUNET_memcmp (&ecdsa_pub, &ticket->audience))
649 GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
650 GNUNET_free (code_payload);
651 GNUNET_free (plaintext);
652 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
653 "Audience in ticket does not match client!\n");
654 return GNUNET_SYSERR;
657 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN,
662 GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
663 GNUNET_free (code_payload);
664 GNUNET_free (plaintext);
665 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Signature of AuthZ code invalid!\n");
666 return GNUNET_SYSERR;
670 GNUNET_asprintf (nonce_str, "%u", nonce);
671 GNUNET_free (code_payload);
672 GNUNET_free (plaintext);
678 * Build a token response for a token request
679 * TODO: Maybe we should add the scope here?
681 * @param access_token the access token to include
682 * @param id_token the id_token to include
683 * @param expiration_time the expiration time of the token(s)
684 * @param token_response where to store the response
687 OIDC_build_token_response (const char *access_token,
688 const char *id_token,
689 const struct GNUNET_TIME_Relative *expiration_time,
690 char **token_response)
694 root_json = json_object ();
696 GNUNET_assert (NULL != access_token);
697 GNUNET_assert (NULL != id_token);
698 GNUNET_assert (NULL != expiration_time);
699 json_object_set_new (root_json, "access_token", json_string (access_token));
700 json_object_set_new (root_json, "token_type", json_string ("Bearer"));
701 json_object_set_new (root_json,
703 json_integer (expiration_time->rel_value_us /
705 json_object_set_new (root_json, "id_token", json_string (id_token));
706 *token_response = json_dumps (root_json, JSON_INDENT (0) | JSON_COMPACT);
707 json_decref (root_json);
711 * Generate a new access token
714 OIDC_access_token_new ()
717 uint64_t random_number;
720 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
721 GNUNET_STRINGS_base64_encode (&random_number,