fix loop
[oweals/gnunet.git] / src / reclaim / oidc_helper.c
1 /*
2    This file is part of GNUnet
3    Copyright (C) 2010-2015 GNUnet e.V.
4
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.
9
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.
14
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/>.
17
18    SPDX-License-Identifier: AGPL3.0-or-later
19    */
20
21 /**
22  * @file reclaim/oidc_helper.c
23  * @brief helper library for OIDC related functions
24  * @author Martin Schanzenbach
25  */
26 #include "platform.h"
27 #include <inttypes.h>
28 #include <jansson.h>
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"
35 #include <gcrypt.h>
36
37 GNUNET_NETWORK_STRUCT_BEGIN
38
39 /**
40  * The signature used to generate the authorization code
41  */
42 struct OIDC_Parameters
43 {
44   /**
45    * The reclaim ticket
46    */
47   const struct GNUNET_RECLAIM_Ticket *ticket;
48
49   /**
50    * The nonce
51    */
52   uint32_t nonce GNUNET_PACKED;
53
54   /**
55    * The length of the PKCE code_challenge
56    */
57   uint32_t code_challenge_len GNUNET_PACKED;
58
59   /**
60    * The length of the attributes list
61    */
62   uint32_t attr_list_len GNUNET_PACKED;
63 };
64
65 GNUNET_NETWORK_STRUCT_END
66
67 static char *
68 create_jwt_header (void)
69 {
70   json_t *root;
71   char *json_str;
72
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));
76
77   json_str = json_dumps (root, JSON_INDENT (0) | JSON_COMPACT);
78   json_decref (root);
79   return json_str;
80 }
81
82 static void
83 replace_char (char *str, char find, char replace)
84 {
85   char *current_pos = strchr (str, find);
86   while (current_pos)
87   {
88     *current_pos = replace;
89     current_pos = strchr (current_pos, find);
90   }
91 }
92
93 // RFC4648
94 static void
95 fix_base64 (char *str)
96 {
97   // Replace + with -
98   replace_char (str, '+', '-');
99
100   // Replace / with _
101   replace_char (str, '/', '_');
102 }
103
104 /**
105  * Create a JWT from attributes
106  *
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.
113  */
114 char *
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,
119                    const char *nonce,
120                    const char *secret_key)
121 {
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;
126   char *audience;
127   char *subject;
128   char *header;
129   char *body_str;
130   char *result;
131   char *header_base64;
132   char *body_base64;
133   char *signature_target;
134   char *signature_base64;
135   char *attr_val_str;
136   json_t *body;
137
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
145   subject =
146     GNUNET_STRINGS_data_to_string_alloc (sub_key,
147                                          sizeof (struct
148                                                  GNUNET_CRYPTO_EcdsaPublicKey));
149   audience =
150     GNUNET_STRINGS_data_to_string_alloc (aud_key,
151                                          sizeof (struct
152                                                  GNUNET_CRYPTO_EcdsaPublicKey));
153   header = create_jwt_header ();
154   body = json_object ();
155
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));
164   // iat
165   json_object_set_new (body,
166                        "iat",
167                        json_integer (time_now.abs_value_us / (1000 * 1000)));
168   // exp
169   json_object_set_new (body,
170                        "exp",
171                        json_integer (exp_time.abs_value_us / (1000 * 1000)));
172   // nbf
173   json_object_set_new (body,
174                        "nbf",
175                        json_integer (time_now.abs_value_us / (1000 * 1000)));
176   // nonce
177   if (NULL != nonce)
178     json_object_set_new (body, "nonce", json_string (nonce));
179
180   for (le = attrs->list_head; NULL != le; le = le->next)
181   {
182     attr_val_str =
183       GNUNET_RECLAIM_ATTRIBUTE_value_to_string (le->claim->type,
184                                                 le->claim->data,
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);
188   }
189   body_str = json_dumps (body, JSON_INDENT (0) | JSON_COMPACT);
190   json_decref (body);
191
192   GNUNET_STRINGS_base64_encode (header, strlen (header), &header_base64);
193   fix_base64 (header_base64);
194
195   GNUNET_STRINGS_base64_encode (body_str, strlen (body_str), &body_base64);
196   fix_base64 (body_base64);
197
198   GNUNET_free (subject);
199   GNUNET_free (audience);
200
201   /**
202    * Creating the JWT signature. This might not be
203    * standards compliant, check.
204    */
205   GNUNET_asprintf (&signature_target, "%s.%s", header_base64, body_base64);
206   GNUNET_CRYPTO_hmac_raw (secret_key,
207                           strlen (secret_key),
208                           signature_target,
209                           strlen (signature_target),
210                           &signature);
211   GNUNET_STRINGS_base64_encode ((const char *) &signature,
212                                 sizeof (struct GNUNET_HashCode),
213                                 &signature_base64);
214   fix_base64 (signature_base64);
215
216   GNUNET_asprintf (&result,
217                    "%s.%s.%s",
218                    header_base64,
219                    body_base64,
220                    signature_base64);
221
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);
228   return result;
229 }
230
231 /* Converts a hex character to its integer value */
232 static char
233 from_hex (char ch)
234 {
235   return isdigit (ch) ? ch - '0' : tolower (ch) - 'a' + 10;
236 }
237
238 /* Converts an integer value to its hex character*/
239 static char
240 to_hex (char code)
241 {
242   static char hex[] = "0123456789abcdef";
243   return hex[code & 15];
244 }
245
246 /* Returns a url-encoded version of str */
247 /* IMPORTANT: be sure to free() the returned string after use */
248 static char *
249 url_encode (const char *str)
250 {
251   char *pstr = (char *) str;
252   char *buf = GNUNET_malloc (strlen (str) * 3 + 1);
253   char *pbuf = buf;
254   while (*pstr)
255   {
256     if (isalnum (*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' ||
257         *pstr == '~')
258       *pbuf++ = *pstr;
259     else if (*pstr == ' ')
260       *pbuf++ = '+';
261     else
262     {
263       *pbuf++ = '%';
264       *pbuf++ = to_hex (*pstr >> 4);
265       *pbuf++ = to_hex (*pstr & 15);
266     }
267     pstr++;
268   }
269   *pbuf = '\0';
270   return buf;
271 }
272
273
274 /* Returns a url-decoded version of str */
275 /* IMPORTANT: be sure to free() the returned string after use */
276 static char *
277 url_decode (const char *str)
278 {
279   char *pstr = (char *) str;
280   char *buf = GNUNET_malloc (strlen (str) + 1);
281   char *pbuf = buf;
282   while (*pstr)
283   {
284     if (*pstr == '%')
285     {
286       if (pstr[1] && pstr[2])
287       {
288         *pbuf++ = from_hex (pstr[1]) << 4 | from_hex (pstr[2]);
289         pstr += 2;
290       }
291     }
292     else if (*pstr == '+')
293     {
294       *pbuf++ = ' ';
295     }
296     else
297     {
298       *pbuf++ = *pstr;
299     }
300     pstr++;
301   }
302   *pbuf = '\0';
303   return buf;
304 }
305
306 /**
307  * Returns base64 encoded string urlencoded
308  *
309  * @param string the string to encode
310  * @return base64 encoded string
311  */
312 static char *
313 base64_and_urlencode (const char *data, size_t data_size)
314 {
315   char *enc;
316   char *urlenc;
317
318   GNUNET_STRINGS_base64_encode (data, data_size, &enc);
319   urlenc = url_encode (enc);
320   GNUNET_free (enc);
321   return urlenc;
322 }
323
324
325
326
327 /**
328  * Returns base64 encoded string urlencoded
329  *
330  * @param string the string to encode
331  * @return base64 encoded string
332  */
333 static char *
334 base64url_encode (const char *data, size_t data_size)
335 {
336   char *enc;
337   size_t pos;
338
339   GNUNET_STRINGS_base64_encode (data, data_size, &enc);
340   //Replace with correct characters for base64url
341   pos = 0;
342   while ('\0' != enc[pos])
343   {
344     if ('+' == enc[pos])
345       enc[pos] = '-';
346     if ('/' == enc[pos])
347       enc[pos] = '_';
348     if ('=' == enc[pos])
349     {
350       enc[pos] = '\0';
351       break;
352     }
353     pos++;
354   }
355   return enc;
356 }
357
358
359 static void
360 derive_aes_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
361                 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
362                 struct GNUNET_HashCode *key_material)
363 {
364   static const char ctx_key[] = "reclaim-aes-ctx-key";
365   static const char ctx_iv[] = "reclaim-aes-ctx-iv";
366   GNUNET_CRYPTO_kdf (key,
367                      sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
368                      ctx_key,
369                      strlen (ctx_key),
370                      key_material,
371                      sizeof (struct GNUNET_HashCode),
372                      NULL);
373   GNUNET_CRYPTO_kdf (iv,
374                      sizeof (
375                        struct GNUNET_CRYPTO_SymmetricInitializationVector),
376                      ctx_iv,
377                      strlen (ctx_iv),
378                      key_material,
379                      sizeof (struct GNUNET_HashCode),
380                      NULL);
381 }
382
383
384 static void
385 calculate_key_priv (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
386                     struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
387                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
388                     const struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub)
389 {
390   struct GNUNET_HashCode key_material;
391   GNUNET_CRYPTO_ecdsa_ecdh (ecdsa_priv, ecdh_pub, &key_material);
392   derive_aes_key (key, iv, &key_material);
393 }
394
395
396 static void
397 calculate_key_pub (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
398                    struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
399                    const struct GNUNET_CRYPTO_EcdsaPublicKey *ecdsa_pub,
400                    const struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv)
401 {
402   struct GNUNET_HashCode key_material;
403   GNUNET_CRYPTO_ecdh_ecdsa (ecdh_priv, ecdsa_pub, &key_material);
404   derive_aes_key (key, iv, &key_material);
405 }
406
407
408 static void
409 decrypt_payload (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
410                  const struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub,
411                  const char *ct,
412                  size_t ct_len,
413                  char *buf)
414 {
415   struct GNUNET_CRYPTO_SymmetricSessionKey key;
416   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
417
418   calculate_key_priv (&key, &iv, ecdsa_priv, ecdh_pub);
419   GNUNET_break (GNUNET_CRYPTO_symmetric_decrypt (ct, ct_len, &key, &iv, buf));
420 }
421
422
423 static void
424 encrypt_payload (const struct GNUNET_CRYPTO_EcdsaPublicKey *ecdsa_pub,
425                  const struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv,
426                  const char *payload,
427                  size_t payload_len,
428                  char *buf)
429 {
430   struct GNUNET_CRYPTO_SymmetricSessionKey key;
431   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
432
433   calculate_key_pub (&key, &iv, ecdsa_pub, ecdh_priv);
434   GNUNET_break (
435     GNUNET_CRYPTO_symmetric_encrypt (payload, payload_len, &key, &iv, buf));
436 }
437
438 /**
439  * Builds an OIDC authorization code including
440  * a reclaim ticket and nonce
441  *
442  * @param issuer the issuer of the ticket, used to sign the ticket and nonce
443  * @param ticket the ticket to include in the code
444  * @param attrs list of attributes which are shared
445  * @param nonce the nonce to include in the code
446  * @param code_challenge PKCE code challenge
447  * @return a new authorization code (caller must free)
448  */
449 char *
450 OIDC_build_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer,
451                        const struct GNUNET_RECLAIM_Ticket *ticket,
452                        struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs,
453                        const char *nonce_str,
454                        const char *code_challenge)
455 {
456   struct OIDC_Parameters params;
457   char *code_payload;
458   char *payload;
459   char *tmp;
460   char *code_str;
461   char *buf_ptr = NULL;
462   size_t payload_len;
463   size_t code_payload_len;
464   size_t attr_list_len = 0;
465   uint32_t nonce;
466   uint32_t nonce_tmp;
467   struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
468   struct GNUNET_CRYPTO_EcdhePrivateKey *ecdh_priv;
469   struct GNUNET_CRYPTO_EcdhePublicKey ecdh_pub;
470
471   /** PLAINTEXT **/
472   // Assign ticket
473   memset (&params, 0, sizeof (params));
474   params.ticket = ticket;
475   // Assign nonce
476   nonce = 0;
477   payload_len = sizeof (struct OIDC_Parameters);
478   if (NULL != nonce_str && strcmp ("", nonce_str) != 0)
479   {
480     if ((1 != SSCANF (nonce_str, "%u", &nonce)) || (nonce > UINT32_MAX))
481     {
482       GNUNET_break (0);
483       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid nonce %s\n", nonce_str);
484       return NULL;
485     }
486     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
487                 "Got nonce: %u from %s\n",
488                 nonce,
489                 nonce_str);
490   }
491   nonce_tmp = htonl (nonce);
492   params.nonce = nonce_tmp;
493   // Assign code challenge
494   if (NULL == code_challenge || strcmp ("", code_challenge) == 0)
495   {
496     GNUNET_break (0);
497     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "PKCE: Code challenge missing");
498     return NULL;
499   }
500   payload_len += strlen (code_challenge);
501   params.code_challenge_len = htonl (strlen (code_challenge));
502   // Assign attributes
503   if (NULL != attrs)
504   {
505     // Get length
506     attr_list_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size (attrs);
507     params.attr_list_len = htonl (attr_list_len);
508     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
509                 "Length of serialized attributes: %lu\n",
510                 attr_list_len);
511     // Get serialized attributes
512     payload_len += attr_list_len;
513   }
514   // Get plaintext length
515   payload = GNUNET_malloc (payload_len);
516   memcpy (payload, &params, sizeof (params));
517   tmp = payload + sizeof (params);
518   memcpy (tmp, code_challenge, strlen (code_challenge));
519   tmp += strlen (code_challenge);
520   if (0 < attr_list_len)
521     GNUNET_RECLAIM_ATTRIBUTE_list_serialize (attrs, tmp);
522   /** END **/
523
524   /** ENCRYPT **/
525   // Get length
526   code_payload_len = sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
527                      sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
528                      payload_len + sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
530               "Length of data to encode: %lu\n",
531               code_payload_len);
532
533   // Generate ECDH key
534   ecdh_priv = GNUNET_CRYPTO_ecdhe_key_create ();
535   GNUNET_CRYPTO_ecdhe_key_get_public (ecdh_priv, &ecdh_pub);
536   // Initialize code payload
537   code_payload = GNUNET_malloc (code_payload_len);
538   GNUNET_assert (NULL != code_payload);
539   purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
540   purpose->size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
541                          sizeof (ecdh_pub) + payload_len);
542   purpose->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN);
543   // Store pubkey
544   buf_ptr = (char *) &purpose[1];
545   memcpy (buf_ptr, &ecdh_pub, sizeof (ecdh_pub));
546   buf_ptr += sizeof (ecdh_pub);
547   // Encrypt plaintext and store
548   encrypt_payload (&ticket->audience, ecdh_priv, payload, payload_len, buf_ptr);
549   GNUNET_free (ecdh_priv);
550   GNUNET_free (payload);
551   buf_ptr += payload_len;
552   // Sign and store signature
553   if (GNUNET_SYSERR ==
554       GNUNET_CRYPTO_ecdsa_sign (issuer,
555                                 purpose,
556                                 (struct GNUNET_CRYPTO_EcdsaSignature *)
557                                   buf_ptr))
558   {
559     GNUNET_break (0);
560     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unable to sign code\n");
561     GNUNET_free (code_payload);
562     return NULL;
563   }
564   code_str = base64_and_urlencode (code_payload, code_payload_len);
565   GNUNET_free (code_payload);
566   return code_str;
567 }
568
569
570 /**
571  * Parse reclaim ticket and nonce from
572  * authorization code.
573  * This also verifies the signature in the code.
574  *
575  * @param audience the expected audience of the code
576  * @param code the string representation of the code
577  * @param code_verfier PKCE code verifier
578  * @param ticket where to store the ticket
579  * @param attrs the attributes in the code
580  * @param nonce where to store the nonce
581  * @return GNUNET_OK if successful, else GNUNET_SYSERR
582  */
583 int
584 OIDC_parse_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv,
585                        const char *code,
586                        const char *code_verifier,
587                        struct GNUNET_RECLAIM_Ticket *ticket,
588                        struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList **attrs,
589                        char **nonce_str)
590 {
591   char *code_payload;
592   char *ptr;
593   char *plaintext;
594   char *attrs_ser;
595   char *expected_code_challenge;
596   char *code_challenge;
597   char *code_verifier_hash;
598   struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
599   struct GNUNET_CRYPTO_EcdsaSignature *signature;
600   struct GNUNET_CRYPTO_EcdsaPublicKey ecdsa_pub;
601   struct GNUNET_CRYPTO_EcdhePublicKey *ecdh_pub;
602   uint32_t code_challenge_len;
603   uint32_t attrs_ser_len;
604   size_t plaintext_len;
605   size_t code_payload_len;
606   uint32_t nonce = 0;
607   struct OIDC_Parameters *params;
608
609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to decode `%s'\n", code);
610   code_payload = NULL;
611   code_payload_len =
612     GNUNET_STRINGS_base64_decode (code, strlen (code), (void **) &code_payload);
613   if (code_payload_len < sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
614                            sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
615                            sizeof (struct OIDC_Parameters) +
616                            sizeof (struct GNUNET_CRYPTO_EcdsaSignature))
617   {
618     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Authorization code malformed\n");
619     GNUNET_free_non_null (code_payload);
620     return GNUNET_SYSERR;
621   }
622
623   purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
624   plaintext_len = code_payload_len;
625   plaintext_len -= sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose);
626   ptr = (char *) &purpose[1];
627   // Public ECDH key
628   ecdh_pub = (struct GNUNET_CRYPTO_EcdhePublicKey *) ptr;
629   ptr += sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
630   plaintext_len -= sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
631
632   // Decrypt ciphertext
633   plaintext_len -= sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
634   plaintext = GNUNET_malloc (plaintext_len);
635   decrypt_payload (ecdsa_priv, ecdh_pub, ptr, plaintext_len, plaintext);
636   //ptr = plaintext;
637   params = (struct OIDC_Parameters *) plaintext;
638
639   // cmp code_challenge code_verifier
640   code_verifier_hash = GNUNET_malloc (256 / 8);
641   // hash code verifier
642   gcry_md_hash_buffer (GCRY_MD_SHA256,
643                        code_verifier_hash,
644                        code_verifier,
645                        strlen (code_verifier));
646   // encode code verifier
647   expected_code_challenge = base64url_encode (code_verifier_hash, 256 / 8);
648   code_challenge = (char *) &params[1];
649   code_challenge_len = ntohl (params->code_challenge_len);
650   GNUNET_free (code_verifier_hash);
651   if ((strlen (expected_code_challenge) != code_challenge_len) ||
652       (0 !=
653        strncmp (expected_code_challenge, code_challenge, code_challenge_len)))
654   {
655     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
656                 "Invalid code verifier! Expected: %s, Got: %.*s\n",
657                 expected_code_challenge,
658                 code_challenge_len,
659                 code_challenge);
660     GNUNET_free_non_null (code_payload);
661     GNUNET_free (expected_code_challenge);
662     return GNUNET_SYSERR;
663   }
664   GNUNET_free (expected_code_challenge);
665   // Ticket
666   memcpy (ticket, &params->ticket, sizeof (params->ticket));
667   // Nonce
668   nonce = ntohl (params->nonce); //ntohl (*((uint32_t *) ptr));
669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got nonce: %u\n", nonce);
670   // Attributes
671   attrs_ser = ((char *) &params[1]) + code_challenge_len;
672   attrs_ser_len = ntohl (params->attr_list_len);
673   *attrs = GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (attrs_ser, attrs_ser_len);
674   // Signature
675   signature = (struct GNUNET_CRYPTO_EcdsaSignature *) attrs_ser + attrs_ser_len;
676   GNUNET_CRYPTO_ecdsa_key_get_public (ecdsa_priv, &ecdsa_pub);
677   if (0 != GNUNET_memcmp (&ecdsa_pub, &ticket->audience))
678   {
679     GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
680     GNUNET_free (code_payload);
681     GNUNET_free (plaintext);
682     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
683                 "Audience in ticket does not match client!\n");
684     return GNUNET_SYSERR;
685   }
686   if (GNUNET_OK !=
687       GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN,
688                                   purpose,
689                                   signature,
690                                   &ticket->identity))
691   {
692     GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
693     GNUNET_free (code_payload);
694     GNUNET_free (plaintext);
695     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Signature of AuthZ code invalid!\n");
696     return GNUNET_SYSERR;
697   }
698   *nonce_str = NULL;
699   if (nonce != 0)
700     GNUNET_asprintf (nonce_str, "%u", nonce);
701   GNUNET_free (code_payload);
702   GNUNET_free (plaintext);
703   return GNUNET_OK;
704 }
705
706
707 /**
708  * Build a token response for a token request
709  * TODO: Maybe we should add the scope here?
710  *
711  * @param access_token the access token to include
712  * @param id_token the id_token to include
713  * @param expiration_time the expiration time of the token(s)
714  * @param token_response where to store the response
715  */
716 void
717 OIDC_build_token_response (const char *access_token,
718                            const char *id_token,
719                            const struct GNUNET_TIME_Relative *expiration_time,
720                            char **token_response)
721 {
722   json_t *root_json;
723
724   root_json = json_object ();
725
726   GNUNET_assert (NULL != access_token);
727   GNUNET_assert (NULL != id_token);
728   GNUNET_assert (NULL != expiration_time);
729   json_object_set_new (root_json, "access_token", json_string (access_token));
730   json_object_set_new (root_json, "token_type", json_string ("Bearer"));
731   json_object_set_new (root_json,
732                        "expires_in",
733                        json_integer (expiration_time->rel_value_us /
734                                      (1000 * 1000)));
735   json_object_set_new (root_json, "id_token", json_string (id_token));
736   *token_response = json_dumps (root_json, JSON_INDENT (0) | JSON_COMPACT);
737   json_decref (root_json);
738 }
739
740 /**
741  * Generate a new access token
742  */
743 char *
744 OIDC_access_token_new ()
745 {
746   char *access_token;
747   uint64_t random_number;
748
749   random_number =
750     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
751   GNUNET_STRINGS_base64_encode (&random_number,
752                                 sizeof (uint64_t),
753                                 &access_token);
754   return access_token;
755 }
756