602b3f8570c89c8eaa497be3b3ef936fa395f8db
[vpp.git] / src / plugins / quic / quic_crypto.c
1 /*
2  * Copyright (c) 2021 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <quic/quic.h>
17 #include <quic/quic_crypto.h>
18
19 #include <quicly.h>
20 #include <picotls/openssl.h>
21
22 #define QUICLY_EPOCH_1RTT 3
23
24 extern quic_main_t quic_main;
25 extern quic_ctx_t *quic_get_conn_ctx (quicly_conn_t * conn);
26 vnet_crypto_main_t *cm = &crypto_main;
27
28 struct cipher_context_t
29 {
30   ptls_cipher_context_t super;
31   vnet_crypto_op_t op;
32   vnet_crypto_op_id_t id;
33   u32 key_index;
34 };
35
36 struct aead_crypto_context_t
37 {
38   ptls_aead_context_t super;
39   EVP_CIPHER_CTX *evp_ctx;
40   uint8_t static_iv[PTLS_MAX_IV_SIZE];
41   vnet_crypto_op_t op;
42   u32 key_index;
43   vnet_crypto_op_id_t id;
44   uint8_t iv[PTLS_MAX_IV_SIZE];
45 };
46
47 static int
48 quic_crypto_setup_cipher (quicly_crypto_engine_t *engine, quicly_conn_t *conn,
49                           size_t epoch, int is_enc,
50                           ptls_cipher_context_t **header_protect_ctx,
51                           ptls_aead_context_t **packet_protect_ctx,
52                           ptls_aead_algorithm_t *aead,
53                           ptls_hash_algorithm_t *hash, const void *secret)
54 {
55   uint8_t hpkey[PTLS_MAX_SECRET_SIZE];
56   int ret;
57
58   *packet_protect_ctx = NULL;
59   /* generate new header protection key */
60   if (header_protect_ctx != NULL)
61     {
62       *header_protect_ctx = NULL;
63       ret =
64         ptls_hkdf_expand_label (hash, hpkey, aead->ctr_cipher->key_size,
65                                 ptls_iovec_init (secret, hash->digest_size),
66                                 "quic hp", ptls_iovec_init (NULL, 0), NULL);
67       if (ret)
68         goto Exit;
69       *header_protect_ctx = ptls_cipher_new (aead->ctr_cipher, is_enc, hpkey);
70       if (NULL == *header_protect_ctx)
71         {
72           ret = PTLS_ERROR_NO_MEMORY;
73           goto Exit;
74         }
75     }
76
77   /* generate new AEAD context */
78   *packet_protect_ctx =
79     ptls_aead_new (aead, hash, is_enc, secret, QUICLY_AEAD_BASE_LABEL);
80   if (NULL == *packet_protect_ctx)
81     {
82       ret = PTLS_ERROR_NO_MEMORY;
83       goto Exit;
84     }
85
86   if (epoch == QUICLY_EPOCH_1RTT && !is_enc)
87     {
88       quic_ctx_t *qctx = quic_get_conn_ctx (conn);
89       if (qctx->ingress_keys.aead_ctx != NULL)
90         qctx->key_phase_ingress++;
91
92       qctx->ingress_keys.aead_ctx = *packet_protect_ctx;
93       if (header_protect_ctx != NULL)
94         qctx->ingress_keys.hp_ctx = *header_protect_ctx;
95     }
96
97   ret = 0;
98
99 Exit:
100   if (ret)
101     {
102       if (*packet_protect_ctx != NULL)
103         {
104           ptls_aead_free (*packet_protect_ctx);
105           *packet_protect_ctx = NULL;
106         }
107       if (header_protect_ctx && *header_protect_ctx != NULL)
108         {
109           ptls_cipher_free (*header_protect_ctx);
110           *header_protect_ctx = NULL;
111         }
112     }
113   ptls_clear_memory (hpkey, sizeof (hpkey));
114   return ret;
115 }
116
117 static size_t
118 quic_crypto_aead_decrypt (quic_ctx_t *qctx, ptls_aead_context_t *_ctx,
119                           void *_output, const void *input, size_t inlen,
120                           uint64_t decrypted_pn, const void *aad,
121                           size_t aadlen)
122 {
123   vlib_main_t *vm = vlib_get_main ();
124
125   struct aead_crypto_context_t *ctx = (struct aead_crypto_context_t *) _ctx;
126
127   vnet_crypto_op_init (&ctx->op, ctx->id);
128   ctx->op.aad = (u8 *) aad;
129   ctx->op.aad_len = aadlen;
130   ctx->op.iv = ctx->iv;
131   ptls_aead__build_iv (ctx->super.algo, ctx->op.iv, ctx->static_iv,
132                        decrypted_pn);
133   ctx->op.src = (u8 *) input;
134   ctx->op.dst = _output;
135   ctx->op.key_index = ctx->key_index;
136   ctx->op.len = inlen - ctx->super.algo->tag_size;
137   ctx->op.tag_len = ctx->super.algo->tag_size;
138   ctx->op.tag = ctx->op.src + ctx->op.len;
139
140   vnet_crypto_process_ops (vm, &(ctx->op), 1);
141
142   return ctx->op.len;
143 }
144
145 void
146 quic_crypto_decrypt_packet (quic_ctx_t * qctx, quic_rx_packet_ctx_t * pctx)
147 {
148   ptls_cipher_context_t *header_protection = NULL;
149   ptls_aead_context_t *aead = NULL;
150   int pn;
151
152   /* Long Header packets are not decrypted by vpp */
153   if (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]))
154     return;
155
156   uint64_t next_expected_packet_number =
157     quicly_get_next_expected_packet_number (qctx->conn);
158   if (next_expected_packet_number == UINT64_MAX)
159     return;
160
161   aead = qctx->ingress_keys.aead_ctx;
162   header_protection = qctx->ingress_keys.hp_ctx;
163
164   if (!aead || !header_protection)
165     return;
166
167   size_t encrypted_len = pctx->packet.octets.len - pctx->packet.encrypted_off;
168   uint8_t hpmask[5] = { 0 };
169   uint32_t pnbits = 0;
170   size_t pnlen, ptlen, i;
171
172   /* decipher the header protection, as well as obtaining pnbits, pnlen */
173   if (encrypted_len < header_protection->algo->iv_size + QUICLY_MAX_PN_SIZE)
174     return;
175   ptls_cipher_init (header_protection,
176                     pctx->packet.octets.base + pctx->packet.encrypted_off +
177                     QUICLY_MAX_PN_SIZE);
178   ptls_cipher_encrypt (header_protection, hpmask, hpmask, sizeof (hpmask));
179   pctx->packet.octets.base[0] ^=
180     hpmask[0] & (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]) ?
181                  0xf : 0x1f);
182   pnlen = (pctx->packet.octets.base[0] & 0x3) + 1;
183   for (i = 0; i != pnlen; ++i)
184     {
185       pctx->packet.octets.base[pctx->packet.encrypted_off + i] ^=
186         hpmask[i + 1];
187       pnbits =
188         (pnbits << 8) | pctx->packet.octets.base[pctx->packet.encrypted_off +
189                                                  i];
190     }
191
192   size_t aead_off = pctx->packet.encrypted_off + pnlen;
193
194   pn =
195     quicly_determine_packet_number (pnbits, pnlen * 8,
196                                     next_expected_packet_number);
197
198   int key_phase_bit =
199     (pctx->packet.octets.base[0] & QUICLY_KEY_PHASE_BIT) != 0;
200
201   if (key_phase_bit != (qctx->key_phase_ingress & 1))
202     {
203       pctx->packet.octets.base[0] ^=
204         hpmask[0] &
205         (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]) ? 0xf :
206          0x1f);
207       for (i = 0; i != pnlen; ++i)
208         {
209           pctx->packet.octets.base[pctx->packet.encrypted_off + i] ^=
210             hpmask[i + 1];
211         }
212       return;
213     }
214
215   if ((ptlen = quic_crypto_aead_decrypt (
216          qctx, aead, pctx->packet.octets.base + aead_off,
217          pctx->packet.octets.base + aead_off,
218          pctx->packet.octets.len - aead_off, pn, pctx->packet.octets.base,
219          aead_off)) == SIZE_MAX)
220     {
221       fprintf (stderr,
222                "%s: aead decryption failure (pn: %d)\n", __FUNCTION__, pn);
223       return;
224     }
225
226   pctx->packet.encrypted_off = aead_off;
227   pctx->packet.octets.len = ptlen + aead_off;
228
229   pctx->packet.decrypted.pn = pn;
230   pctx->packet.decrypted.key_phase = qctx->key_phase_ingress;
231 }
232
233 void
234 quic_crypto_encrypt_packet (struct st_quicly_crypto_engine_t *engine,
235                             quicly_conn_t *conn,
236                             ptls_cipher_context_t *header_protect_ctx,
237                             ptls_aead_context_t *packet_protect_ctx,
238                             ptls_iovec_t datagram, size_t first_byte_at,
239                             size_t payload_from, uint64_t packet_number,
240                             int coalesced)
241 {
242   vlib_main_t *vm = vlib_get_main ();
243
244   struct cipher_context_t *hp_ctx =
245     (struct cipher_context_t *) header_protect_ctx;
246   struct aead_crypto_context_t *aead_ctx =
247     (struct aead_crypto_context_t *) packet_protect_ctx;
248
249   void *input = datagram.base + payload_from;
250   void *output = input;
251   size_t inlen =
252     datagram.len - payload_from - packet_protect_ctx->algo->tag_size;
253   const void *aad = datagram.base + first_byte_at;
254   size_t aadlen = payload_from - first_byte_at;
255
256   /* Build AEAD encrypt crypto operation */
257   vnet_crypto_op_init (&aead_ctx->op, aead_ctx->id);
258   aead_ctx->op.aad = (u8 *) aad;
259   aead_ctx->op.aad_len = aadlen;
260   aead_ctx->op.iv = aead_ctx->iv;
261   ptls_aead__build_iv (aead_ctx->super.algo, aead_ctx->op.iv,
262                        aead_ctx->static_iv, packet_number);
263   aead_ctx->op.key_index = aead_ctx->key_index;
264   aead_ctx->op.src = (u8 *) input;
265   aead_ctx->op.dst = output;
266   aead_ctx->op.len = inlen;
267   aead_ctx->op.tag_len = aead_ctx->super.algo->tag_size;
268   aead_ctx->op.tag = aead_ctx->op.src + inlen;
269   vnet_crypto_process_ops (vm, &(aead_ctx->op), 1);
270   assert (aead_ctx->op.status == VNET_CRYPTO_OP_STATUS_COMPLETED);
271
272   /* Build Header protection crypto operation */
273   ptls_aead_supplementary_encryption_t supp = {
274     .ctx = header_protect_ctx,
275     .input =
276       datagram.base + payload_from - QUICLY_SEND_PN_SIZE + QUICLY_MAX_PN_SIZE
277   };
278
279   /* Build Header protection crypto operation */
280   vnet_crypto_op_init (&hp_ctx->op, hp_ctx->id);
281   memset (supp.output, 0, sizeof (supp.output));
282   hp_ctx->op.iv = (u8 *) supp.input;
283   hp_ctx->op.key_index = hp_ctx->key_index;
284   hp_ctx->op.src = (u8 *) supp.output;
285   hp_ctx->op.dst = (u8 *) supp.output;
286   hp_ctx->op.len = sizeof (supp.output);
287   vnet_crypto_process_ops (vm, &(hp_ctx->op), 1);
288   assert (hp_ctx->op.status == VNET_CRYPTO_OP_STATUS_COMPLETED);
289
290   datagram.base[first_byte_at] ^=
291     supp.output[0] &
292     (QUICLY_PACKET_IS_LONG_HEADER (datagram.base[first_byte_at]) ? 0xf : 0x1f);
293   for (size_t i = 0; i != QUICLY_SEND_PN_SIZE; ++i)
294     datagram.base[payload_from + i - QUICLY_SEND_PN_SIZE] ^=
295       supp.output[i + 1];
296 }
297
298 static int
299 quic_crypto_cipher_setup_crypto (ptls_cipher_context_t *_ctx, int is_enc,
300                                  const void *key, const EVP_CIPHER *cipher)
301 {
302   struct cipher_context_t *ctx = (struct cipher_context_t *) _ctx;
303
304   vlib_main_t *vm = vlib_get_main ();
305   vnet_crypto_alg_t algo;
306   if (!strcmp (ctx->super.algo->name, "AES128-CTR"))
307     {
308       algo = VNET_CRYPTO_ALG_AES_128_CTR;
309       ctx->id = is_enc ? VNET_CRYPTO_OP_AES_128_CTR_ENC :
310                          VNET_CRYPTO_OP_AES_128_CTR_DEC;
311       ptls_openssl_aes128ctr.setup_crypto (_ctx, is_enc, key);
312     }
313   else if (!strcmp (ctx->super.algo->name, "AES256-CTR"))
314     {
315       algo = VNET_CRYPTO_ALG_AES_256_CTR;
316       ctx->id = is_enc ? VNET_CRYPTO_OP_AES_256_CTR_ENC :
317                          VNET_CRYPTO_OP_AES_256_CTR_DEC;
318       ptls_openssl_aes256ctr.setup_crypto (_ctx, is_enc, key);
319     }
320   else
321     {
322       QUIC_DBG (1, "%s, Invalid crypto cipher : ", __FUNCTION__,
323                 _ctx->algo->name);
324       assert (0);
325     }
326
327   if (quic_main.vnet_crypto_enabled)
328     {
329       clib_rwlock_writer_lock (&quic_main.crypto_keys_quic_rw_lock);
330       ctx->key_index =
331         vnet_crypto_key_add (vm, algo, (u8 *) key, _ctx->algo->key_size);
332       clib_rwlock_writer_unlock (&quic_main.crypto_keys_quic_rw_lock);
333     }
334
335   return 0;
336 }
337
338 static int
339 quic_crypto_aes128ctr_setup_crypto (ptls_cipher_context_t * ctx, int is_enc,
340                                     const void *key)
341 {
342   return quic_crypto_cipher_setup_crypto (ctx, 1, key, EVP_aes_128_ctr ());
343 }
344
345 static int
346 quic_crypto_aes256ctr_setup_crypto (ptls_cipher_context_t * ctx, int is_enc,
347                                     const void *key)
348 {
349   return quic_crypto_cipher_setup_crypto (ctx, 1, key, EVP_aes_256_ctr ());
350 }
351
352 static int
353 quic_crypto_aead_setup_crypto (ptls_aead_context_t *_ctx, int is_enc,
354                                const void *key, const void *iv,
355                                const EVP_CIPHER *cipher)
356 {
357   vlib_main_t *vm = vlib_get_main ();
358   struct aead_crypto_context_t *ctx = (struct aead_crypto_context_t *) _ctx;
359
360   vnet_crypto_alg_t algo;
361   if (!strcmp (ctx->super.algo->name, "AES128-GCM"))
362     {
363       algo = VNET_CRYPTO_ALG_AES_128_GCM;
364       ctx->id = is_enc ? VNET_CRYPTO_OP_AES_128_GCM_ENC :
365                          VNET_CRYPTO_OP_AES_128_GCM_DEC;
366       ptls_openssl_aes128gcm.setup_crypto (_ctx, is_enc, key, iv);
367     }
368   else if (!strcmp (ctx->super.algo->name, "AES256-GCM"))
369     {
370       algo = VNET_CRYPTO_ALG_AES_256_GCM;
371       ctx->id = is_enc ? VNET_CRYPTO_OP_AES_256_GCM_ENC :
372                          VNET_CRYPTO_OP_AES_256_GCM_DEC;
373       ptls_openssl_aes256gcm.setup_crypto (_ctx, is_enc, key, iv);
374     }
375   else
376     {
377       QUIC_DBG (1, "%s, invalied aead cipher %s", __FUNCTION__,
378                 _ctx->algo->name);
379       assert (0);
380     }
381
382   if (quic_main.vnet_crypto_enabled)
383     {
384       clib_memcpy (ctx->static_iv, iv, ctx->super.algo->iv_size);
385
386       clib_rwlock_writer_lock (&quic_main.crypto_keys_quic_rw_lock);
387       ctx->key_index = vnet_crypto_key_add (vm, algo,
388                                             (u8 *) key, _ctx->algo->key_size);
389       clib_rwlock_writer_unlock (&quic_main.crypto_keys_quic_rw_lock);
390     }
391
392   return 0;
393 }
394
395 static int
396 quic_crypto_aead_aes128gcm_setup_crypto (ptls_aead_context_t *ctx, int is_enc,
397                                          const void *key, const void *iv)
398 {
399   return quic_crypto_aead_setup_crypto (ctx, is_enc, key, iv,
400                                         EVP_aes_128_gcm ());
401 }
402
403 static int
404 quic_crypto_aead_aes256gcm_setup_crypto (ptls_aead_context_t *ctx, int is_enc,
405                                          const void *key, const void *iv)
406 {
407   return quic_crypto_aead_setup_crypto (ctx, is_enc, key, iv,
408                                         EVP_aes_256_gcm ());
409 }
410
411 int
412 quic_encrypt_ticket_cb (ptls_encrypt_ticket_t *_self, ptls_t *tls,
413                         int is_encrypt, ptls_buffer_t *dst, ptls_iovec_t src)
414 {
415   quic_session_cache_t *self = (void *) _self;
416   int ret;
417
418   if (is_encrypt)
419     {
420
421       /* replace the cached entry along with a newly generated session id */
422       clib_mem_free (self->data.base);
423       if ((self->data.base = clib_mem_alloc (src.len)) == NULL)
424         return PTLS_ERROR_NO_MEMORY;
425
426       ptls_get_context (tls)->random_bytes (self->id, sizeof (self->id));
427       clib_memcpy (self->data.base, src.base, src.len);
428       self->data.len = src.len;
429
430       /* store the session id in buffer */
431       if ((ret = ptls_buffer_reserve (dst, sizeof (self->id))) != 0)
432         return ret;
433       clib_memcpy (dst->base + dst->off, self->id, sizeof (self->id));
434       dst->off += sizeof (self->id);
435     }
436   else
437     {
438       /* check if session id is the one stored in cache */
439       if (src.len != sizeof (self->id))
440         return PTLS_ERROR_SESSION_NOT_FOUND;
441       if (clib_memcmp (self->id, src.base, sizeof (self->id)) != 0)
442         return PTLS_ERROR_SESSION_NOT_FOUND;
443
444       /* return the cached value */
445       if ((ret = ptls_buffer_reserve (dst, self->data.len)) != 0)
446         return ret;
447       clib_memcpy (dst->base + dst->off, self->data.base, self->data.len);
448       dst->off += self->data.len;
449     }
450
451   return 0;
452 }
453
454 ptls_cipher_algorithm_t quic_crypto_aes128ctr = {
455   "AES128-CTR",
456   PTLS_AES128_KEY_SIZE,
457   1,
458   PTLS_AES_IV_SIZE,
459   sizeof (struct cipher_context_t),
460   quic_crypto_aes128ctr_setup_crypto
461 };
462
463 ptls_cipher_algorithm_t quic_crypto_aes256ctr = {
464   "AES256-CTR",
465   PTLS_AES256_KEY_SIZE,
466   1 /* block size */,
467   PTLS_AES_IV_SIZE,
468   sizeof (struct cipher_context_t),
469   quic_crypto_aes256ctr_setup_crypto
470 };
471
472 ptls_aead_algorithm_t quic_crypto_aes128gcm = {
473   "AES128-GCM",
474   PTLS_AESGCM_CONFIDENTIALITY_LIMIT,
475   PTLS_AESGCM_INTEGRITY_LIMIT,
476   &quic_crypto_aes128ctr,
477   &ptls_openssl_aes128ecb,
478   PTLS_AES128_KEY_SIZE,
479   PTLS_AESGCM_IV_SIZE,
480   PTLS_AESGCM_TAG_SIZE,
481   sizeof (struct aead_crypto_context_t),
482   quic_crypto_aead_aes128gcm_setup_crypto
483 };
484
485 ptls_aead_algorithm_t quic_crypto_aes256gcm = {
486   "AES256-GCM",
487   PTLS_AESGCM_CONFIDENTIALITY_LIMIT,
488   PTLS_AESGCM_INTEGRITY_LIMIT,
489   &quic_crypto_aes256ctr,
490   &ptls_openssl_aes256ecb,
491   PTLS_AES256_KEY_SIZE,
492   PTLS_AESGCM_IV_SIZE,
493   PTLS_AESGCM_TAG_SIZE,
494   sizeof (struct aead_crypto_context_t),
495   quic_crypto_aead_aes256gcm_setup_crypto
496 };
497
498 ptls_cipher_suite_t quic_crypto_aes128gcmsha256 = {
499   PTLS_CIPHER_SUITE_AES_128_GCM_SHA256,
500   &quic_crypto_aes128gcm, &ptls_openssl_sha256
501 };
502
503 ptls_cipher_suite_t quic_crypto_aes256gcmsha384 = {
504   PTLS_CIPHER_SUITE_AES_256_GCM_SHA384,
505   &quic_crypto_aes256gcm, &ptls_openssl_sha384
506 };
507
508 ptls_cipher_suite_t *quic_crypto_cipher_suites[] = {
509   &quic_crypto_aes256gcmsha384, &quic_crypto_aes128gcmsha256, NULL
510 };
511
512 quicly_crypto_engine_t quic_crypto_engine = { quic_crypto_setup_cipher,
513                                               quic_crypto_encrypt_packet };
514
515 /*
516  * fd.io coding-style-patch-verification: ON
517  *
518  * Local Variables:
519  * eval: (c-set-style "gnu")
520  * End:
521  */