RECLAIM/REST: simplify auth code; include attrs
[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
30 #include "gnunet_util_lib.h"
31
32 #include "gnunet_reclaim_attribute_lib.h"
33 #include "gnunet_reclaim_service.h"
34 #include "gnunet_signatures.h"
35 #include "oidc_helper.h"
36 static char *
37 create_jwt_header (void)
38 {
39   json_t *root;
40   char *json_str;
41
42   root = json_object ();
43   json_object_set_new (root, JWT_ALG, json_string (JWT_ALG_VALUE));
44   json_object_set_new (root, JWT_TYP, json_string (JWT_TYP_VALUE));
45
46   json_str = json_dumps (root, JSON_INDENT (0) | JSON_COMPACT);
47   json_decref (root);
48   return json_str;
49 }
50
51 static void
52 replace_char (char *str, char find, char replace)
53 {
54   char *current_pos = strchr (str, find);
55   while (current_pos)
56   {
57     *current_pos = replace;
58     current_pos = strchr (current_pos, find);
59   }
60 }
61
62 // RFC4648
63 static void
64 fix_base64 (char *str)
65 {
66   // Replace + with -
67   replace_char (str, '+', '-');
68
69   // Replace / with _
70   replace_char (str, '/', '_');
71 }
72
73 /**
74  * Create a JWT from attributes
75  *
76  * @param aud_key the public of the audience
77  * @param sub_key the public key of the subject
78  * @param attrs the attribute list
79  * @param expiration_time the validity of the token
80  * @param secret_key the key used to sign the JWT
81  * @return a new base64-encoded JWT string.
82  */
83 char *
84 OIDC_id_token_new (const struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key,
85                    const struct GNUNET_CRYPTO_EcdsaPublicKey *sub_key,
86                    const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs,
87                    const struct GNUNET_TIME_Relative *expiration_time,
88                    const char *nonce,
89                    const char *secret_key)
90 {
91   struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le;
92   struct GNUNET_HashCode signature;
93   struct GNUNET_TIME_Absolute exp_time;
94   struct GNUNET_TIME_Absolute time_now;
95   char *audience;
96   char *subject;
97   char *header;
98   char *body_str;
99   char *result;
100   char *header_base64;
101   char *body_base64;
102   char *signature_target;
103   char *signature_base64;
104   char *attr_val_str;
105   json_t *body;
106
107   // iat REQUIRED time now
108   time_now = GNUNET_TIME_absolute_get ();
109   // exp REQUIRED time expired from config
110   exp_time = GNUNET_TIME_absolute_add (time_now, *expiration_time);
111   // auth_time only if max_age
112   // nonce only if nonce
113   // OPTIONAL acr,amr,azp
114   subject = GNUNET_STRINGS_data_to_string_alloc (
115     sub_key,
116     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
117   audience = GNUNET_STRINGS_data_to_string_alloc (
118     aud_key,
119     sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
120   header = create_jwt_header ();
121   body = json_object ();
122
123   // iss REQUIRED case sensitive server uri with https
124   // The issuer is the local reclaim instance (e.g.
125   // https://reclaim.id/api/openid)
126   json_object_set_new (body, "iss", json_string (SERVER_ADDRESS));
127   // sub REQUIRED public key identity, not exceed 255 ASCII  length
128   json_object_set_new (body, "sub", json_string (subject));
129   // aud REQUIRED public key client_id must be there
130   json_object_set_new (body, "aud", json_string (audience));
131   // iat
132   json_object_set_new (body,
133                        "iat",
134                        json_integer (time_now.abs_value_us / (1000 * 1000)));
135   // exp
136   json_object_set_new (body,
137                        "exp",
138                        json_integer (exp_time.abs_value_us / (1000 * 1000)));
139   // nbf
140   json_object_set_new (body,
141                        "nbf",
142                        json_integer (time_now.abs_value_us / (1000 * 1000)));
143   // nonce
144   if (NULL != nonce)
145     json_object_set_new (body, "nonce", json_string (nonce));
146
147   for (le = attrs->list_head; NULL != le; le = le->next)
148   {
149     attr_val_str =
150       GNUNET_RECLAIM_ATTRIBUTE_value_to_string (le->claim->type,
151                                                 le->claim->data,
152                                                 le->claim->data_size);
153     json_object_set_new (body, le->claim->name, json_string (attr_val_str));
154     GNUNET_free (attr_val_str);
155   }
156   body_str = json_dumps (body, JSON_INDENT (0) | JSON_COMPACT);
157   json_decref (body);
158
159   GNUNET_STRINGS_base64_encode (header, strlen (header), &header_base64);
160   fix_base64 (header_base64);
161
162   GNUNET_STRINGS_base64_encode (body_str, strlen (body_str), &body_base64);
163   fix_base64 (body_base64);
164
165   GNUNET_free (subject);
166   GNUNET_free (audience);
167
168   /**
169    * Creating the JWT signature. This might not be
170    * standards compliant, check.
171    */
172   GNUNET_asprintf (&signature_target, "%s.%s", header_base64, body_base64);
173   GNUNET_CRYPTO_hmac_raw (secret_key,
174                           strlen (secret_key),
175                           signature_target,
176                           strlen (signature_target),
177                           &signature);
178   GNUNET_STRINGS_base64_encode ((const char *) &signature,
179                                 sizeof (struct GNUNET_HashCode),
180                                 &signature_base64);
181   fix_base64 (signature_base64);
182
183   GNUNET_asprintf (&result,
184                    "%s.%s.%s",
185                    header_base64,
186                    body_base64,
187                    signature_base64);
188
189   GNUNET_free (signature_target);
190   GNUNET_free (header);
191   GNUNET_free (body_str);
192   GNUNET_free (signature_base64);
193   GNUNET_free (body_base64);
194   GNUNET_free (header_base64);
195   return result;
196 }
197
198
199 /**
200  * Returns base64 encoded string urlencoded
201  *
202  * @param string the string to encode
203  * @return base64 encoded string
204  */
205 static char *
206 base64_encode (const char *data,
207                size_t data_size)
208 {
209   char *enc;
210   char *enc_urlencode;
211   char *tmp;
212   int i;
213   int num_pads = 0;
214
215   GNUNET_STRINGS_base64_encode (data, data_size, &enc);
216   tmp = strchr (enc, '=');
217   num_pads = strlen (enc) - (tmp - enc);
218   GNUNET_assert ((3 > num_pads) && (0 <= num_pads));
219   if (0 == num_pads)
220     return enc;
221   enc_urlencode = GNUNET_malloc (strlen (enc) + num_pads * 2);
222   strcpy (enc_urlencode, enc);
223   GNUNET_free (enc);
224   tmp = strchr (enc_urlencode, '=');
225   for (i = 0; i < num_pads; i++) {
226     strcpy (tmp, "%3D"); // replace '=' with '%3D'
227     tmp += 3;
228   }
229   return enc_urlencode;
230 }
231
232
233
234
235 /**
236  * Builds an OIDC authorization code including
237  * a reclaim ticket and nonce
238  *
239  * @param issuer the issuer of the ticket, used to sign the ticket and nonce
240  * @param ticket the ticket to include in the code
241  * @param attrs list of attributes whicha re shared
242  * @param nonce the nonce to include in the code
243  * @return a new authorization code (caller must free)
244  */
245 char *
246 OIDC_build_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer,
247                        const struct GNUNET_RECLAIM_Ticket *ticket,
248                        struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs,
249                        const char *nonce_str)
250 {
251   char *code_payload;
252   char *attrs_ser;
253   char *code_str;
254   char *buf_ptr;
255   size_t signature_payload_len;
256   size_t attr_list_len;
257   size_t code_payload_len;
258   unsigned int nonce;
259   unsigned int nonce_tmp;
260   struct GNUNET_CRYPTO_EcdsaSignature signature;
261   struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
262
263   attrs_ser = NULL;
264   signature_payload_len =
265     sizeof (struct GNUNET_RECLAIM_Ticket) + sizeof (unsigned int);
266   if (NULL != attrs)
267   {
268     attr_list_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size (attrs);
269     signature_payload_len += attr_list_len;
270     attrs_ser = GNUNET_malloc (attr_list_len);
271     GNUNET_RECLAIM_ATTRIBUTE_list_serialize (attrs, attrs_ser);
272   }
273   code_payload_len = sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
274                      signature_payload_len + sizeof (signature);
275   code_payload = GNUNET_malloc (code_payload_len);
276   purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
277   purpose->size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
278                          signature_payload_len);
279   purpose->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN);
280   // First, copy ticket
281   buf_ptr = (char *) &purpose[1];
282   memcpy (buf_ptr, ticket, sizeof (struct GNUNET_RECLAIM_Ticket));
283   buf_ptr += sizeof (struct GNUNET_RECLAIM_Ticket);
284   // Then copy nonce
285   nonce = 0;
286   if (NULL != nonce_str)
287   {
288     if ((1 != SSCANF (nonce_str, "%u", &nonce)) || (nonce > UINT16_MAX))
289     {
290       GNUNET_free (code_payload);
291       GNUNET_free_non_null (attrs_ser);
292       return NULL;
293     }
294   }
295   nonce_tmp = htons (nonce);
296   memcpy (buf_ptr, &nonce_tmp, sizeof (unsigned int));
297   buf_ptr += sizeof (unsigned int);
298   // Finally, attributes
299   if (NULL != attrs_ser)
300   {
301     memcpy (buf_ptr, attrs_ser, attr_list_len);
302     buf_ptr += attr_list_len;
303   }
304   if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign (issuer, purpose, &signature))
305   {
306     GNUNET_free (code_payload);
307     GNUNET_free_non_null (attrs_ser);
308     return NULL;
309   }
310   memcpy (buf_ptr, &signature, sizeof (signature));
311   code_str = base64_encode ((const char *) &code_payload,
312                             code_payload_len);
313   GNUNET_free (code_payload);
314   GNUNET_free_non_null (attrs_ser);
315   return code_str;
316 }
317
318
319 /**
320  * Parse reclaim ticket and nonce from
321  * authorization code.
322  * This also verifies the signature in the code.
323  *
324  * @param audience the expected audience of the code
325  * @param code the string representation of the code
326  * @param ticket where to store the ticket
327  * @param attrs the attributes in the code
328  * @param nonce where to store the nonce
329  * @return GNUNET_OK if successful, else GNUNET_SYSERR
330  */
331 int
332 OIDC_parse_authz_code (const struct GNUNET_CRYPTO_EcdsaPublicKey *audience,
333                        const char *code,
334                        struct GNUNET_RECLAIM_Ticket *ticket,
335                        struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList **attrs,
336                        char **nonce_str)
337 {
338   char *code_payload;
339   char *attrs_ser;
340   char *ptr;
341   struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
342   struct GNUNET_CRYPTO_EcdsaSignature *signature;
343   size_t code_payload_len;
344   size_t attrs_ser_len;
345   size_t signature_offset;
346   unsigned int nonce;
347
348   code_payload = NULL;
349   code_payload_len =
350     GNUNET_STRINGS_base64_decode (code, strlen (code), (void **) &code_payload);
351   purpose = (struct GNUNET_CRYPTO_EccSignaturePurpose *) code_payload;
352   attrs_ser_len = code_payload_len;
353   attrs_ser_len -= sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose);
354   *ticket = *((struct GNUNET_RECLAIM_Ticket*) &purpose[1]);
355   attrs_ser_len -= sizeof (struct GNUNET_RECLAIM_Ticket);
356   nonce = ntohs (((unsigned int *) &ticket[1]));
357   attrs_ser_len -= sizeof (unsigned int);
358   ptr = code_payload;
359   signature_offset =
360     code_payload_len - sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
361   signature = (struct GNUNET_CRYPTO_EcdsaSignature *)&ptr[signature_offset];
362   attrs_ser_len -= sizeof (struct GNUNET_CRYPTO_EcdsaSignature);
363   attrs_ser = ((char *) &ticket[1]) + sizeof (unsigned int);
364   *attrs = GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (attrs_ser, attrs_ser_len);
365   if (0 != GNUNET_memcmp (audience, &ticket->audience))
366   {
367     GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
368     GNUNET_free (code_payload);
369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
370                 "Audience in ticket does not match client!\n");
371     return GNUNET_SYSERR;
372   }
373   if (GNUNET_OK !=
374       GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_RECLAIM_CODE_SIGN,
375                                   purpose,
376                                   signature,
377                                   &ticket->identity))
378   {
379     GNUNET_RECLAIM_ATTRIBUTE_list_destroy (*attrs);
380     GNUNET_free (code_payload);
381     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Signature of AuthZ code invalid!\n");
382     return GNUNET_SYSERR;
383   }
384   *nonce_str = NULL;
385   if (nonce != 0)
386     GNUNET_asprintf (nonce_str, "%u", nonce);
387   return GNUNET_OK;
388 }
389
390
391 /**
392  * Build a token response for a token request
393  * TODO: Maybe we should add the scope here?
394  *
395  * @param access_token the access token to include
396  * @param id_token the id_token to include
397  * @param expiration_time the expiration time of the token(s)
398  * @param token_response where to store the response
399  */
400 void
401 OIDC_build_token_response (const char *access_token,
402                            const char *id_token,
403                            const struct GNUNET_TIME_Relative *expiration_time,
404                            char **token_response)
405 {
406   json_t *root_json;
407
408   root_json = json_object ();
409
410   GNUNET_assert (NULL != access_token);
411   GNUNET_assert (NULL != id_token);
412   GNUNET_assert (NULL != expiration_time);
413   json_object_set_new (root_json, "access_token", json_string (access_token));
414   json_object_set_new (root_json, "token_type", json_string ("Bearer"));
415   json_object_set_new (
416     root_json,
417     "expires_in",
418     json_integer (expiration_time->rel_value_us / (1000 * 1000)));
419   json_object_set_new (root_json, "id_token", json_string (id_token));
420   *token_response = json_dumps (root_json, JSON_INDENT (0) | JSON_COMPACT);
421   json_decref (root_json);
422 }
423
424 /**
425  * Generate a new access token
426  */
427 char *
428 OIDC_access_token_new ()
429 {
430   char *access_token_number;
431   char *access_token;
432   uint64_t random_number;
433
434   random_number =
435     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
436   GNUNET_asprintf (&access_token_number, "%" PRIu64, random_number);
437   GNUNET_STRINGS_base64_encode (access_token_number,
438                                 strlen (access_token_number),
439                                 &access_token);
440   return access_token;
441 }