19b0ce5a58c9118d51d46121b2a99db76e5471e4
[vpp.git] / src / plugins / wireguard / wireguard_noise.c
1 /*
2  * Copyright (c) 2020 Doc.ai and/or its affiliates.
3  * Copyright (c) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>.
4  * Copyright (c) 2019-2020 Matt Dunwoodie <ncon@noconroy.net>.
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 #include <openssl/hmac.h>
19 #include <wireguard/wireguard.h>
20 #include <wireguard/wireguard_chachapoly.h>
21
22 /* This implements Noise_IKpsk2:
23  *
24  * <- s
25  * ******
26  * -> e, es, s, ss, {t}
27  * <- e, ee, se, psk, {}
28  */
29
30 noise_local_t *noise_local_pool;
31
32 /* Private functions */
33 static noise_keypair_t *noise_remote_keypair_allocate (noise_remote_t *);
34 static void noise_remote_keypair_free (vlib_main_t * vm, noise_remote_t *,
35                                        noise_keypair_t **);
36 static uint32_t noise_remote_handshake_index_get (vlib_main_t *vm,
37                                                   noise_remote_t *);
38 static void noise_remote_handshake_index_drop (vlib_main_t *vm,
39                                                noise_remote_t *);
40
41 static uint64_t noise_counter_send (noise_counter_t *);
42 bool noise_counter_recv (noise_counter_t *, uint64_t);
43
44 static void noise_kdf (uint8_t *, uint8_t *, uint8_t *, const uint8_t *,
45                        size_t, size_t, size_t, size_t,
46                        const uint8_t[NOISE_HASH_LEN]);
47 static bool noise_mix_dh (uint8_t[NOISE_HASH_LEN],
48                           uint8_t[NOISE_SYMMETRIC_KEY_LEN],
49                           const uint8_t[NOISE_PUBLIC_KEY_LEN],
50                           const uint8_t[NOISE_PUBLIC_KEY_LEN]);
51 static bool noise_mix_ss (uint8_t ck[NOISE_HASH_LEN],
52                           uint8_t key[NOISE_SYMMETRIC_KEY_LEN],
53                           const uint8_t ss[NOISE_PUBLIC_KEY_LEN]);
54 static void noise_mix_hash (uint8_t[NOISE_HASH_LEN], const uint8_t *, size_t);
55 static void noise_mix_psk (uint8_t[NOISE_HASH_LEN],
56                            uint8_t[NOISE_HASH_LEN],
57                            uint8_t[NOISE_SYMMETRIC_KEY_LEN],
58                            const uint8_t[NOISE_SYMMETRIC_KEY_LEN]);
59 static void noise_param_init (uint8_t[NOISE_HASH_LEN],
60                               uint8_t[NOISE_HASH_LEN],
61                               const uint8_t[NOISE_PUBLIC_KEY_LEN]);
62
63 static void noise_msg_encrypt (vlib_main_t * vm, uint8_t *, uint8_t *, size_t,
64                                uint32_t key_idx, uint8_t[NOISE_HASH_LEN]);
65 static bool noise_msg_decrypt (vlib_main_t * vm, uint8_t *, uint8_t *, size_t,
66                                uint32_t key_idx, uint8_t[NOISE_HASH_LEN]);
67 static void noise_msg_ephemeral (uint8_t[NOISE_HASH_LEN],
68                                  uint8_t[NOISE_HASH_LEN],
69                                  const uint8_t src[NOISE_PUBLIC_KEY_LEN]);
70
71 static void noise_tai64n_now (uint8_t[NOISE_TIMESTAMP_LEN]);
72
73 /* Set/Get noise parameters */
74 void
75 noise_local_init (noise_local_t * l, struct noise_upcall *upcall)
76 {
77   clib_memset (l, 0, sizeof (*l));
78   l->l_upcall = *upcall;
79 }
80
81 bool
82 noise_local_set_private (noise_local_t * l,
83                          const uint8_t private[NOISE_PUBLIC_KEY_LEN])
84 {
85   clib_memcpy (l->l_private, private, NOISE_PUBLIC_KEY_LEN);
86
87   return curve25519_gen_public (l->l_public, private);
88 }
89
90 void
91 noise_remote_init (vlib_main_t *vm, noise_remote_t *r, uint32_t peer_pool_idx,
92                    const uint8_t public[NOISE_PUBLIC_KEY_LEN],
93                    u32 noise_local_idx)
94 {
95   clib_memset (r, 0, sizeof (*r));
96   clib_memcpy (r->r_public, public, NOISE_PUBLIC_KEY_LEN);
97   clib_rwlock_init (&r->r_keypair_lock);
98   r->r_peer_idx = peer_pool_idx;
99   r->r_local_idx = noise_local_idx;
100   r->r_handshake.hs_state = HS_ZEROED;
101
102   noise_remote_precompute (vm, r);
103 }
104
105 void
106 noise_remote_precompute (vlib_main_t *vm, noise_remote_t *r)
107 {
108   noise_local_t *l = noise_local_get (r->r_local_idx);
109
110   if (!curve25519_gen_shared (r->r_ss, l->l_private, r->r_public))
111     clib_memset (r->r_ss, 0, NOISE_PUBLIC_KEY_LEN);
112
113   noise_remote_handshake_index_drop (vm, r);
114   wg_secure_zero_memory (&r->r_handshake, sizeof (r->r_handshake));
115 }
116
117 /* Handshake functions */
118 bool
119 noise_create_initiation (vlib_main_t * vm, noise_remote_t * r,
120                          uint32_t * s_idx, uint8_t ue[NOISE_PUBLIC_KEY_LEN],
121                          uint8_t es[NOISE_PUBLIC_KEY_LEN + NOISE_AUTHTAG_LEN],
122                          uint8_t ets[NOISE_TIMESTAMP_LEN + NOISE_AUTHTAG_LEN])
123 {
124   noise_handshake_t *hs = &r->r_handshake;
125   noise_local_t *l = noise_local_get (r->r_local_idx);
126   uint8_t _key[NOISE_SYMMETRIC_KEY_LEN] = { 0 };
127   uint32_t key_idx;
128   uint8_t *key;
129   int ret = false;
130
131   key_idx =
132     vnet_crypto_key_add (vm, VNET_CRYPTO_ALG_CHACHA20_POLY1305, _key,
133                          NOISE_SYMMETRIC_KEY_LEN);
134   key = vnet_crypto_get_key (key_idx)->data;
135
136   noise_param_init (hs->hs_ck, hs->hs_hash, r->r_public);
137
138   /* e */
139   curve25519_gen_secret (hs->hs_e);
140   if (!curve25519_gen_public (ue, hs->hs_e))
141     goto error;
142   noise_msg_ephemeral (hs->hs_ck, hs->hs_hash, ue);
143
144   /* es */
145   if (!noise_mix_dh (hs->hs_ck, key, hs->hs_e, r->r_public))
146     goto error;
147
148   /* s */
149   noise_msg_encrypt (vm, es, l->l_public, NOISE_PUBLIC_KEY_LEN, key_idx,
150                      hs->hs_hash);
151
152   /* ss */
153   if (!noise_mix_ss (hs->hs_ck, key, r->r_ss))
154     goto error;
155
156   /* {t} */
157   noise_tai64n_now (ets);
158   noise_msg_encrypt (vm, ets, ets, NOISE_TIMESTAMP_LEN, key_idx, hs->hs_hash);
159   noise_remote_handshake_index_drop (vm, r);
160   hs->hs_state = CREATED_INITIATION;
161   hs->hs_local_index = noise_remote_handshake_index_get (vm, r);
162   *s_idx = hs->hs_local_index;
163   ret = true;
164 error:
165   wg_secure_zero_memory (key, NOISE_SYMMETRIC_KEY_LEN);
166   vnet_crypto_key_del (vm, key_idx);
167   return ret;
168 }
169
170 bool
171 noise_consume_initiation (vlib_main_t * vm, noise_local_t * l,
172                           noise_remote_t ** rp, uint32_t s_idx,
173                           uint8_t ue[NOISE_PUBLIC_KEY_LEN],
174                           uint8_t es[NOISE_PUBLIC_KEY_LEN +
175                                      NOISE_AUTHTAG_LEN],
176                           uint8_t ets[NOISE_TIMESTAMP_LEN +
177                                       NOISE_AUTHTAG_LEN])
178 {
179   noise_remote_t *r;
180   noise_handshake_t hs;
181   uint8_t _key[NOISE_SYMMETRIC_KEY_LEN] = { 0 };
182   uint8_t r_public[NOISE_PUBLIC_KEY_LEN] = { 0 };
183   uint8_t timestamp[NOISE_TIMESTAMP_LEN] = { 0 };
184   u32 key_idx;
185   uint8_t *key;
186   int ret = false;
187
188   key_idx =
189     vnet_crypto_key_add (vm, VNET_CRYPTO_ALG_CHACHA20_POLY1305, _key,
190                          NOISE_SYMMETRIC_KEY_LEN);
191   key = vnet_crypto_get_key (key_idx)->data;
192
193   noise_param_init (hs.hs_ck, hs.hs_hash, l->l_public);
194
195   /* e */
196   noise_msg_ephemeral (hs.hs_ck, hs.hs_hash, ue);
197
198   /* es */
199   if (!noise_mix_dh (hs.hs_ck, key, l->l_private, ue))
200     goto error;
201
202   /* s */
203
204   if (!noise_msg_decrypt (vm, r_public, es,
205                           NOISE_PUBLIC_KEY_LEN + NOISE_AUTHTAG_LEN, key_idx,
206                           hs.hs_hash))
207     goto error;
208
209   /* Lookup the remote we received from */
210   if ((r = l->l_upcall.u_remote_get (r_public)) == NULL)
211     goto error;
212
213   /* ss */
214   if (!noise_mix_ss (hs.hs_ck, key, r->r_ss))
215     goto error;
216
217   /* {t} */
218   if (!noise_msg_decrypt (vm, timestamp, ets,
219                           NOISE_TIMESTAMP_LEN + NOISE_AUTHTAG_LEN, key_idx,
220                           hs.hs_hash))
221     goto error;
222   ;
223
224   hs.hs_state = CONSUMED_INITIATION;
225   hs.hs_local_index = 0;
226   hs.hs_remote_index = s_idx;
227   clib_memcpy (hs.hs_e, ue, NOISE_PUBLIC_KEY_LEN);
228
229   /* Replay */
230   if (clib_memcmp (timestamp, r->r_timestamp, NOISE_TIMESTAMP_LEN) > 0)
231     clib_memcpy (r->r_timestamp, timestamp, NOISE_TIMESTAMP_LEN);
232   else
233     goto error;
234
235   /* Flood attack */
236   if (wg_birthdate_has_expired (r->r_last_init, REJECT_INTERVAL))
237     r->r_last_init = vlib_time_now (vm);
238   else
239     goto error;
240
241   /* Ok, we're happy to accept this initiation now */
242   noise_remote_handshake_index_drop (vm, r);
243   r->r_handshake = hs;
244   *rp = r;
245   ret = true;
246
247 error:
248   wg_secure_zero_memory (key, NOISE_SYMMETRIC_KEY_LEN);
249   vnet_crypto_key_del (vm, key_idx);
250   wg_secure_zero_memory (&hs, sizeof (hs));
251   return ret;
252 }
253
254 bool
255 noise_create_response (vlib_main_t * vm, noise_remote_t * r, uint32_t * s_idx,
256                        uint32_t * r_idx, uint8_t ue[NOISE_PUBLIC_KEY_LEN],
257                        uint8_t en[0 + NOISE_AUTHTAG_LEN])
258 {
259   noise_handshake_t *hs = &r->r_handshake;
260   uint8_t _key[NOISE_SYMMETRIC_KEY_LEN] = { 0 };
261   uint8_t e[NOISE_PUBLIC_KEY_LEN] = { 0 };
262   uint32_t key_idx;
263   uint8_t *key;
264   int ret = false;
265
266   key_idx =
267     vnet_crypto_key_add (vm, VNET_CRYPTO_ALG_CHACHA20_POLY1305, _key,
268                          NOISE_SYMMETRIC_KEY_LEN);
269   key = vnet_crypto_get_key (key_idx)->data;
270
271   if (hs->hs_state != CONSUMED_INITIATION)
272     goto error;
273
274   /* e */
275   curve25519_gen_secret (e);
276   if (!curve25519_gen_public (ue, e))
277     goto error;
278   noise_msg_ephemeral (hs->hs_ck, hs->hs_hash, ue);
279
280   /* ee */
281   if (!noise_mix_dh (hs->hs_ck, NULL, e, hs->hs_e))
282     goto error;
283
284   /* se */
285   if (!noise_mix_dh (hs->hs_ck, NULL, e, r->r_public))
286     goto error;
287
288   /* psk */
289   noise_mix_psk (hs->hs_ck, hs->hs_hash, key, r->r_psk);
290
291   /* {} */
292   noise_msg_encrypt (vm, en, NULL, 0, key_idx, hs->hs_hash);
293
294
295   hs->hs_state = CREATED_RESPONSE;
296   hs->hs_local_index = noise_remote_handshake_index_get (vm, r);
297   *r_idx = hs->hs_remote_index;
298   *s_idx = hs->hs_local_index;
299   ret = true;
300 error:
301   wg_secure_zero_memory (key, NOISE_SYMMETRIC_KEY_LEN);
302   vnet_crypto_key_del (vm, key_idx);
303   wg_secure_zero_memory (e, NOISE_PUBLIC_KEY_LEN);
304   return ret;
305 }
306
307 bool
308 noise_consume_response (vlib_main_t * vm, noise_remote_t * r, uint32_t s_idx,
309                         uint32_t r_idx, uint8_t ue[NOISE_PUBLIC_KEY_LEN],
310                         uint8_t en[0 + NOISE_AUTHTAG_LEN])
311 {
312   noise_local_t *l = noise_local_get (r->r_local_idx);
313   noise_handshake_t hs;
314   uint8_t _key[NOISE_SYMMETRIC_KEY_LEN] = { 0 };
315   uint8_t preshared_key[NOISE_PUBLIC_KEY_LEN] = { 0 };
316   uint32_t key_idx;
317   uint8_t *key;
318   int ret = false;
319
320   key_idx =
321     vnet_crypto_key_add (vm, VNET_CRYPTO_ALG_CHACHA20_POLY1305, _key,
322                          NOISE_SYMMETRIC_KEY_LEN);
323   key = vnet_crypto_get_key (key_idx)->data;
324
325   hs = r->r_handshake;
326   clib_memcpy (preshared_key, r->r_psk, NOISE_SYMMETRIC_KEY_LEN);
327
328   if (hs.hs_state != CREATED_INITIATION || hs.hs_local_index != r_idx)
329     goto error;
330
331   /* e */
332   noise_msg_ephemeral (hs.hs_ck, hs.hs_hash, ue);
333
334   /* ee */
335   if (!noise_mix_dh (hs.hs_ck, NULL, hs.hs_e, ue))
336     goto error;
337
338   /* se */
339   if (!noise_mix_dh (hs.hs_ck, NULL, l->l_private, ue))
340     goto error;
341
342   /* psk */
343   noise_mix_psk (hs.hs_ck, hs.hs_hash, key, preshared_key);
344
345   /* {} */
346
347   if (!noise_msg_decrypt
348       (vm, NULL, en, 0 + NOISE_AUTHTAG_LEN, key_idx, hs.hs_hash))
349     goto error;
350
351
352   hs.hs_remote_index = s_idx;
353
354   if (r->r_handshake.hs_state == hs.hs_state &&
355       r->r_handshake.hs_local_index == hs.hs_local_index)
356     {
357       r->r_handshake = hs;
358       r->r_handshake.hs_state = CONSUMED_RESPONSE;
359       ret = true;
360     }
361 error:
362   wg_secure_zero_memory (&hs, sizeof (hs));
363   wg_secure_zero_memory (key, NOISE_SYMMETRIC_KEY_LEN);
364   vnet_crypto_key_del (vm, key_idx);
365   return ret;
366 }
367
368 bool
369 noise_remote_begin_session (vlib_main_t * vm, noise_remote_t * r)
370 {
371   noise_handshake_t *hs = &r->r_handshake;
372   noise_keypair_t kp, *next, *current, *previous;
373
374   uint8_t key_send[NOISE_SYMMETRIC_KEY_LEN];
375   uint8_t key_recv[NOISE_SYMMETRIC_KEY_LEN];
376
377   /* We now derive the keypair from the handshake */
378   if (hs->hs_state == CONSUMED_RESPONSE)
379     {
380       kp.kp_is_initiator = 1;
381       noise_kdf (key_send, key_recv, NULL, NULL,
382                  NOISE_SYMMETRIC_KEY_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, 0,
383                  hs->hs_ck);
384     }
385   else if (hs->hs_state == CREATED_RESPONSE)
386     {
387       kp.kp_is_initiator = 0;
388       noise_kdf (key_recv, key_send, NULL, NULL,
389                  NOISE_SYMMETRIC_KEY_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, 0,
390                  hs->hs_ck);
391     }
392   else
393     {
394       return false;
395     }
396
397   kp.kp_valid = 1;
398   kp.kp_send_index = vnet_crypto_key_add (vm,
399                                           VNET_CRYPTO_ALG_CHACHA20_POLY1305,
400                                           key_send, NOISE_SYMMETRIC_KEY_LEN);
401   kp.kp_recv_index = vnet_crypto_key_add (vm,
402                                           VNET_CRYPTO_ALG_CHACHA20_POLY1305,
403                                           key_recv, NOISE_SYMMETRIC_KEY_LEN);
404   kp.kp_local_index = hs->hs_local_index;
405   kp.kp_remote_index = hs->hs_remote_index;
406   kp.kp_birthdate = vlib_time_now (vm);
407   clib_memset (&kp.kp_ctr, 0, sizeof (kp.kp_ctr));
408
409   /* Now we need to add_new_keypair */
410   clib_rwlock_writer_lock (&r->r_keypair_lock);
411   /* Activate barrier to synchronization keys between threads */
412   vlib_worker_thread_barrier_sync (vm);
413   next = r->r_next;
414   current = r->r_current;
415   previous = r->r_previous;
416
417   if (kp.kp_is_initiator)
418     {
419       if (next != NULL)
420         {
421           r->r_next = NULL;
422           r->r_previous = next;
423           noise_remote_keypair_free (vm, r, &current);
424         }
425       else
426         {
427           r->r_previous = current;
428         }
429
430       noise_remote_keypair_free (vm, r, &previous);
431
432       r->r_current = noise_remote_keypair_allocate (r);
433       *r->r_current = kp;
434     }
435   else
436     {
437       noise_remote_keypair_free (vm, r, &next);
438       r->r_previous = NULL;
439       noise_remote_keypair_free (vm, r, &previous);
440
441       r->r_next = noise_remote_keypair_allocate (r);
442       *r->r_next = kp;
443     }
444   vlib_worker_thread_barrier_release (vm);
445   clib_rwlock_writer_unlock (&r->r_keypair_lock);
446
447   wg_secure_zero_memory (&r->r_handshake, sizeof (r->r_handshake));
448
449   wg_secure_zero_memory (&kp, sizeof (kp));
450   return true;
451 }
452
453 void
454 noise_remote_clear (vlib_main_t * vm, noise_remote_t * r)
455 {
456   noise_remote_handshake_index_drop (vm, r);
457   wg_secure_zero_memory (&r->r_handshake, sizeof (r->r_handshake));
458
459   clib_rwlock_writer_lock (&r->r_keypair_lock);
460   noise_remote_keypair_free (vm, r, &r->r_next);
461   noise_remote_keypair_free (vm, r, &r->r_current);
462   noise_remote_keypair_free (vm, r, &r->r_previous);
463   r->r_next = NULL;
464   r->r_current = NULL;
465   r->r_previous = NULL;
466   clib_rwlock_writer_unlock (&r->r_keypair_lock);
467 }
468
469 void
470 noise_remote_expire_current (noise_remote_t * r)
471 {
472   clib_rwlock_writer_lock (&r->r_keypair_lock);
473   if (r->r_next != NULL)
474     r->r_next->kp_valid = 0;
475   if (r->r_current != NULL)
476     r->r_current->kp_valid = 0;
477   clib_rwlock_writer_unlock (&r->r_keypair_lock);
478 }
479
480 bool
481 noise_remote_ready (noise_remote_t * r)
482 {
483   noise_keypair_t *kp;
484   int ret;
485
486   clib_rwlock_reader_lock (&r->r_keypair_lock);
487   if ((kp = r->r_current) == NULL ||
488       !kp->kp_valid ||
489       wg_birthdate_has_expired (kp->kp_birthdate, REJECT_AFTER_TIME) ||
490       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES ||
491       kp->kp_ctr.c_send >= REJECT_AFTER_MESSAGES)
492     ret = false;
493   else
494     ret = true;
495   clib_rwlock_reader_unlock (&r->r_keypair_lock);
496   return ret;
497 }
498
499 enum noise_state_crypt
500 noise_remote_encrypt (vlib_main_t * vm, noise_remote_t * r, uint32_t * r_idx,
501                       uint64_t * nonce, uint8_t * src, size_t srclen,
502                       uint8_t * dst)
503 {
504   noise_keypair_t *kp;
505   enum noise_state_crypt ret = SC_FAILED;
506
507   if ((kp = r->r_current) == NULL)
508     goto error;
509
510   /* We confirm that our values are within our tolerances. We want:
511    *  - a valid keypair
512    *  - our keypair to be less than REJECT_AFTER_TIME seconds old
513    *  - our receive counter to be less than REJECT_AFTER_MESSAGES
514    *  - our send counter to be less than REJECT_AFTER_MESSAGES
515    */
516   if (!kp->kp_valid ||
517       wg_birthdate_has_expired (kp->kp_birthdate, REJECT_AFTER_TIME) ||
518       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES ||
519       ((*nonce = noise_counter_send (&kp->kp_ctr)) > REJECT_AFTER_MESSAGES))
520     goto error;
521
522   /* We encrypt into the same buffer, so the caller must ensure that buf
523    * has NOISE_AUTHTAG_LEN bytes to store the MAC. The nonce and index
524    * are passed back out to the caller through the provided data pointer. */
525   *r_idx = kp->kp_remote_index;
526
527   wg_chacha20poly1305_calc (vm, src, srclen, dst, NULL, 0, *nonce,
528                             VNET_CRYPTO_OP_CHACHA20_POLY1305_ENC,
529                             kp->kp_send_index);
530
531   /* If our values are still within tolerances, but we are approaching
532    * the tolerances, we notify the caller with ESTALE that they should
533    * establish a new keypair. The current keypair can continue to be used
534    * until the tolerances are hit. We notify if:
535    *  - our send counter is valid and not less than REKEY_AFTER_MESSAGES
536    *  - we're the initiator and our keypair is older than
537    *    REKEY_AFTER_TIME seconds */
538   ret = SC_KEEP_KEY_FRESH;
539   if ((kp->kp_valid && *nonce >= REKEY_AFTER_MESSAGES) ||
540       (kp->kp_is_initiator &&
541        wg_birthdate_has_expired (kp->kp_birthdate, REKEY_AFTER_TIME)))
542     goto error;
543
544   ret = SC_OK;
545 error:
546   return ret;
547 }
548
549 /* Private functions - these should not be called outside this file under any
550  * circumstances. */
551 static noise_keypair_t *
552 noise_remote_keypair_allocate (noise_remote_t * r)
553 {
554   noise_keypair_t *kp;
555   kp = clib_mem_alloc (sizeof (*kp));
556   return kp;
557 }
558
559 static uint32_t
560 noise_remote_handshake_index_get (vlib_main_t *vm, noise_remote_t *r)
561 {
562   noise_local_t *local = noise_local_get (r->r_local_idx);
563   struct noise_upcall *u = &local->l_upcall;
564   return u->u_index_set (vm, r);
565 }
566
567 static void
568 noise_remote_handshake_index_drop (vlib_main_t *vm, noise_remote_t *r)
569 {
570   noise_handshake_t *hs = &r->r_handshake;
571   noise_local_t *local = noise_local_get (r->r_local_idx);
572   struct noise_upcall *u = &local->l_upcall;
573   if (hs->hs_state != HS_ZEROED)
574     u->u_index_drop (vm, hs->hs_local_index);
575 }
576
577 static void
578 noise_kdf (uint8_t * a, uint8_t * b, uint8_t * c, const uint8_t * x,
579            size_t a_len, size_t b_len, size_t c_len, size_t x_len,
580            const uint8_t ck[NOISE_HASH_LEN])
581 {
582   uint8_t out[BLAKE2S_HASH_SIZE + 1];
583   uint8_t sec[BLAKE2S_HASH_SIZE];
584
585   /* Extract entropy from "x" into sec */
586   u32 l = 0;
587   HMAC (EVP_blake2s256 (), ck, NOISE_HASH_LEN, x, x_len, sec, &l);
588   ASSERT (l == BLAKE2S_HASH_SIZE);
589   if (a == NULL || a_len == 0)
590     goto out;
591
592   /* Expand first key: key = sec, data = 0x1 */
593   out[0] = 1;
594   HMAC (EVP_blake2s256 (), sec, BLAKE2S_HASH_SIZE, out, 1, out, &l);
595   ASSERT (l == BLAKE2S_HASH_SIZE);
596   clib_memcpy (a, out, a_len);
597
598   if (b == NULL || b_len == 0)
599     goto out;
600
601   /* Expand second key: key = sec, data = "a" || 0x2 */
602   out[BLAKE2S_HASH_SIZE] = 2;
603   HMAC (EVP_blake2s256 (), sec, BLAKE2S_HASH_SIZE, out, BLAKE2S_HASH_SIZE + 1,
604         out, &l);
605   ASSERT (l == BLAKE2S_HASH_SIZE);
606   clib_memcpy (b, out, b_len);
607
608   if (c == NULL || c_len == 0)
609     goto out;
610
611   /* Expand third key: key = sec, data = "b" || 0x3 */
612   out[BLAKE2S_HASH_SIZE] = 3;
613   HMAC (EVP_blake2s256 (), sec, BLAKE2S_HASH_SIZE, out, BLAKE2S_HASH_SIZE + 1,
614         out, &l);
615   ASSERT (l == BLAKE2S_HASH_SIZE);
616
617   clib_memcpy (c, out, c_len);
618
619 out:
620   /* Clear sensitive data from stack */
621   wg_secure_zero_memory (sec, BLAKE2S_HASH_SIZE);
622   wg_secure_zero_memory (out, BLAKE2S_HASH_SIZE + 1);
623 }
624
625 static bool
626 noise_mix_dh (uint8_t ck[NOISE_HASH_LEN],
627               uint8_t key[NOISE_SYMMETRIC_KEY_LEN],
628               const uint8_t private[NOISE_PUBLIC_KEY_LEN],
629               const uint8_t public[NOISE_PUBLIC_KEY_LEN])
630 {
631   uint8_t dh[NOISE_PUBLIC_KEY_LEN];
632   if (!curve25519_gen_shared (dh, private, public))
633     return false;
634   noise_kdf (ck, key, NULL, dh,
635              NOISE_HASH_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, NOISE_PUBLIC_KEY_LEN,
636              ck);
637   wg_secure_zero_memory (dh, NOISE_PUBLIC_KEY_LEN);
638   return true;
639 }
640
641 static bool
642 noise_mix_ss (uint8_t ck[NOISE_HASH_LEN],
643               uint8_t key[NOISE_SYMMETRIC_KEY_LEN],
644               const uint8_t ss[NOISE_PUBLIC_KEY_LEN])
645 {
646   static uint8_t null_point[NOISE_PUBLIC_KEY_LEN];
647   if (clib_memcmp (ss, null_point, NOISE_PUBLIC_KEY_LEN) == 0)
648     return false;
649   noise_kdf (ck, key, NULL, ss,
650              NOISE_HASH_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, NOISE_PUBLIC_KEY_LEN,
651              ck);
652   return true;
653 }
654
655 static void
656 noise_mix_hash (uint8_t hash[NOISE_HASH_LEN], const uint8_t * src,
657                 size_t src_len)
658 {
659   blake2s_state_t blake;
660
661   blake2s_init (&blake, NOISE_HASH_LEN);
662   blake2s_update (&blake, hash, NOISE_HASH_LEN);
663   blake2s_update (&blake, src, src_len);
664   blake2s_final (&blake, hash, NOISE_HASH_LEN);
665 }
666
667 static void
668 noise_mix_psk (uint8_t ck[NOISE_HASH_LEN], uint8_t hash[NOISE_HASH_LEN],
669                uint8_t key[NOISE_SYMMETRIC_KEY_LEN],
670                const uint8_t psk[NOISE_SYMMETRIC_KEY_LEN])
671 {
672   uint8_t tmp[NOISE_HASH_LEN];
673
674   noise_kdf (ck, tmp, key, psk,
675              NOISE_HASH_LEN, NOISE_HASH_LEN, NOISE_SYMMETRIC_KEY_LEN,
676              NOISE_SYMMETRIC_KEY_LEN, ck);
677   noise_mix_hash (hash, tmp, NOISE_HASH_LEN);
678   wg_secure_zero_memory (tmp, NOISE_HASH_LEN);
679 }
680
681 static void
682 noise_param_init (uint8_t ck[NOISE_HASH_LEN], uint8_t hash[NOISE_HASH_LEN],
683                   const uint8_t s[NOISE_PUBLIC_KEY_LEN])
684 {
685   blake2s_state_t blake;
686
687   blake2s (ck, NOISE_HASH_LEN, (uint8_t *) NOISE_HANDSHAKE_NAME,
688            strlen (NOISE_HANDSHAKE_NAME), NULL, 0);
689
690   blake2s_init (&blake, NOISE_HASH_LEN);
691   blake2s_update (&blake, ck, NOISE_HASH_LEN);
692   blake2s_update (&blake, (uint8_t *) NOISE_IDENTIFIER_NAME,
693                   strlen (NOISE_IDENTIFIER_NAME));
694   blake2s_final (&blake, hash, NOISE_HASH_LEN);
695
696   noise_mix_hash (hash, s, NOISE_PUBLIC_KEY_LEN);
697 }
698
699 static void
700 noise_msg_encrypt (vlib_main_t * vm, uint8_t * dst, uint8_t * src,
701                    size_t src_len, uint32_t key_idx,
702                    uint8_t hash[NOISE_HASH_LEN])
703 {
704   /* Nonce always zero for Noise_IK */
705   wg_chacha20poly1305_calc (vm, src, src_len, dst, hash, NOISE_HASH_LEN, 0,
706                             VNET_CRYPTO_OP_CHACHA20_POLY1305_ENC, key_idx);
707   noise_mix_hash (hash, dst, src_len + NOISE_AUTHTAG_LEN);
708 }
709
710 static bool
711 noise_msg_decrypt (vlib_main_t * vm, uint8_t * dst, uint8_t * src,
712                    size_t src_len, uint32_t key_idx,
713                    uint8_t hash[NOISE_HASH_LEN])
714 {
715   /* Nonce always zero for Noise_IK */
716   if (!wg_chacha20poly1305_calc (vm, src, src_len, dst, hash, NOISE_HASH_LEN,
717                                  0, VNET_CRYPTO_OP_CHACHA20_POLY1305_DEC,
718                                  key_idx))
719     return false;
720   noise_mix_hash (hash, src, src_len);
721   return true;
722 }
723
724 static void
725 noise_msg_ephemeral (uint8_t ck[NOISE_HASH_LEN], uint8_t hash[NOISE_HASH_LEN],
726                      const uint8_t src[NOISE_PUBLIC_KEY_LEN])
727 {
728   noise_mix_hash (hash, src, NOISE_PUBLIC_KEY_LEN);
729   noise_kdf (ck, NULL, NULL, src, NOISE_HASH_LEN, 0, 0,
730              NOISE_PUBLIC_KEY_LEN, ck);
731 }
732
733 static void
734 noise_tai64n_now (uint8_t output[NOISE_TIMESTAMP_LEN])
735 {
736   uint32_t unix_sec;
737   uint32_t unix_nanosec;
738
739   uint64_t sec;
740   uint32_t nsec;
741
742   unix_time_now_nsec_fraction (&unix_sec, &unix_nanosec);
743
744   /* Round down the nsec counter to limit precise timing leak. */
745   unix_nanosec &= REJECT_INTERVAL_MASK;
746
747   /* https://cr.yp.to/libtai/tai64.html */
748   sec = htobe64 (0x400000000000000aULL + unix_sec);
749   nsec = htobe32 (unix_nanosec);
750
751   /* memcpy to output buffer, assuming output could be unaligned. */
752   clib_memcpy (output, &sec, sizeof (sec));
753   clib_memcpy (output + sizeof (sec), &nsec, sizeof (nsec));
754 }
755
756 /*
757  * fd.io coding-style-patch-verification: ON
758  *
759  * Local Variables:
760  * eval: (c-set-style "gnu")
761  * End:
762  */