ipsec: add per-SA error counters
[vpp.git] / src / vnet / ipsec / esp_decrypt.c
1 /*
2  * esp_decrypt.c : IPSec ESP decrypt node
3  *
4  * Copyright (c) 2015 Cisco and/or its affiliates.
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 #include <vnet/vnet.h>
18 #include <vnet/api_errno.h>
19 #include <vnet/ip/ip.h>
20 #include <vnet/l2/l2_input.h>
21
22 #include <vnet/ipsec/ipsec.h>
23 #include <vnet/ipsec/esp.h>
24 #include <vnet/ipsec/ipsec_io.h>
25 #include <vnet/ipsec/ipsec_tun.h>
26
27 #include <vnet/gre/packet.h>
28
29 #define foreach_esp_decrypt_next                                              \
30   _ (DROP, "error-drop")                                                      \
31   _ (IP4_INPUT, "ip4-input-no-checksum")                                      \
32   _ (IP6_INPUT, "ip6-input")                                                  \
33   _ (L2_INPUT, "l2-input")                                                    \
34   _ (MPLS_INPUT, "mpls-input")                                                \
35   _ (HANDOFF, "handoff")
36
37 #define _(v, s) ESP_DECRYPT_NEXT_##v,
38 typedef enum
39 {
40   foreach_esp_decrypt_next
41 #undef _
42     ESP_DECRYPT_N_NEXT,
43 } esp_decrypt_next_t;
44
45 #define foreach_esp_decrypt_post_next                                         \
46   _ (DROP, "error-drop")                                                      \
47   _ (IP4_INPUT, "ip4-input-no-checksum")                                      \
48   _ (IP6_INPUT, "ip6-input")                                                  \
49   _ (MPLS_INPUT, "mpls-input")                                                \
50   _ (L2_INPUT, "l2-input")
51
52 #define _(v, s) ESP_DECRYPT_POST_NEXT_##v,
53 typedef enum
54 {
55   foreach_esp_decrypt_post_next
56 #undef _
57     ESP_DECRYPT_POST_N_NEXT,
58 } esp_decrypt_post_next_t;
59
60 typedef struct
61 {
62   u32 seq;
63   u32 sa_seq;
64   u32 sa_seq_hi;
65   u32 pkt_seq_hi;
66   ipsec_crypto_alg_t crypto_alg;
67   ipsec_integ_alg_t integ_alg;
68 } esp_decrypt_trace_t;
69
70 typedef vl_counter_esp_decrypt_enum_t esp_decrypt_error_t;
71
72 /* The number of byres in the hisequence number */
73 #define N_HI_ESN_BYTES 4
74
75 /* packet trace format function */
76 static u8 *
77 format_esp_decrypt_trace (u8 * s, va_list * args)
78 {
79   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
80   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
81   esp_decrypt_trace_t *t = va_arg (*args, esp_decrypt_trace_t *);
82
83   s = format (s,
84               "esp: crypto %U integrity %U pkt-seq %d sa-seq %u sa-seq-hi %u "
85               "pkt-seq-hi %u",
86               format_ipsec_crypto_alg, t->crypto_alg, format_ipsec_integ_alg,
87               t->integ_alg, t->seq, t->sa_seq, t->sa_seq_hi, t->pkt_seq_hi);
88   return s;
89 }
90
91 #define ESP_ENCRYPT_PD_F_FD_TRANSPORT (1 << 2)
92
93 static_always_inline void
94 esp_process_ops (vlib_main_t * vm, vlib_node_runtime_t * node,
95                  vnet_crypto_op_t * ops, vlib_buffer_t * b[], u16 * nexts,
96                  int e)
97 {
98   vnet_crypto_op_t *op = ops;
99   u32 n_fail, n_ops = vec_len (ops);
100
101   if (n_ops == 0)
102     return;
103
104   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
105
106   while (n_fail)
107     {
108       ASSERT (op - ops < n_ops);
109       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
110         {
111           u32 err, bi = op->user_data;
112           if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
113             err = e;
114           else
115             err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
116           esp_decrypt_set_next_index (b[bi], node, vm->thread_index, err, bi,
117                                       nexts, ESP_DECRYPT_NEXT_DROP,
118                                       vnet_buffer (b[bi])->ipsec.sad_index);
119           n_fail--;
120         }
121       op++;
122     }
123 }
124
125 static_always_inline void
126 esp_process_chained_ops (vlib_main_t * vm, vlib_node_runtime_t * node,
127                          vnet_crypto_op_t * ops, vlib_buffer_t * b[],
128                          u16 * nexts, vnet_crypto_op_chunk_t * chunks, int e)
129 {
130
131   vnet_crypto_op_t *op = ops;
132   u32 n_fail, n_ops = vec_len (ops);
133
134   if (PREDICT_TRUE (n_ops == 0))
135     return;
136
137   n_fail = n_ops - vnet_crypto_process_chained_ops (vm, op, chunks, n_ops);
138
139   while (n_fail)
140     {
141       ASSERT (op - ops < n_ops);
142       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
143         {
144           u32 err, bi = op->user_data;
145           if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
146             err = e;
147           else
148             err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
149           esp_decrypt_set_next_index (b[bi], node, vm->thread_index, err, bi,
150                                       nexts, ESP_DECRYPT_NEXT_DROP,
151                                       vnet_buffer (b[bi])->ipsec.sad_index);
152           n_fail--;
153         }
154       op++;
155     }
156 }
157
158 always_inline void
159 esp_remove_tail (vlib_main_t * vm, vlib_buffer_t * b, vlib_buffer_t * last,
160                  u16 tail)
161 {
162   vlib_buffer_t *before_last = b;
163
164   if (last->current_length > tail)
165     {
166       last->current_length -= tail;
167       return;
168     }
169   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
170
171   while (b->flags & VLIB_BUFFER_NEXT_PRESENT)
172     {
173       before_last = b;
174       b = vlib_get_buffer (vm, b->next_buffer);
175     }
176   before_last->current_length -= tail - last->current_length;
177   vlib_buffer_free_one (vm, before_last->next_buffer);
178   before_last->flags &= ~VLIB_BUFFER_NEXT_PRESENT;
179 }
180
181 /* ICV is splitted in last two buffers so move it to the last buffer and
182    return pointer to it */
183 static_always_inline u8 *
184 esp_move_icv (vlib_main_t * vm, vlib_buffer_t * first,
185               esp_decrypt_packet_data_t * pd,
186               esp_decrypt_packet_data2_t * pd2, u16 icv_sz, u16 * dif)
187 {
188   vlib_buffer_t *before_last, *bp;
189   u16 last_sz = pd2->lb->current_length;
190   u16 first_sz = icv_sz - last_sz;
191
192   bp = before_last = first;
193   while (bp->flags & VLIB_BUFFER_NEXT_PRESENT)
194     {
195       before_last = bp;
196       bp = vlib_get_buffer (vm, bp->next_buffer);
197     }
198
199   u8 *lb_curr = vlib_buffer_get_current (pd2->lb);
200   memmove (lb_curr + first_sz, lb_curr, last_sz);
201   clib_memcpy_fast (lb_curr, vlib_buffer_get_tail (before_last) - first_sz,
202                     first_sz);
203   before_last->current_length -= first_sz;
204   if (before_last == first)
205     pd->current_length -= first_sz;
206   clib_memset (vlib_buffer_get_tail (before_last), 0, first_sz);
207   if (dif)
208     dif[0] = first_sz;
209   pd2->lb = before_last;
210   pd2->icv_removed = 1;
211   pd2->free_buffer_index = before_last->next_buffer;
212   before_last->flags &= ~VLIB_BUFFER_NEXT_PRESENT;
213   return lb_curr;
214 }
215
216 static_always_inline u16
217 esp_insert_esn (vlib_main_t *vm, ipsec_sa_t *sa, esp_decrypt_packet_data_t *pd,
218                 esp_decrypt_packet_data2_t *pd2, u32 *data_len, u8 **digest,
219                 u16 *len, vlib_buffer_t *b, u8 *payload)
220 {
221   if (!ipsec_sa_is_set_USE_ESN (sa))
222     return 0;
223   /* shift ICV by 4 bytes to insert ESN */
224   u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
225   u8 tmp[ESP_MAX_ICV_SIZE];
226
227   if (pd2->icv_removed)
228     {
229       u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
230       if (space_left >= N_HI_ESN_BYTES)
231         {
232           clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb), &seq_hi,
233                             N_HI_ESN_BYTES);
234           *data_len += N_HI_ESN_BYTES;
235         }
236       else
237         return N_HI_ESN_BYTES;
238
239       len[0] = b->current_length;
240     }
241   else
242     {
243       clib_memcpy_fast (tmp, payload + len[0], ESP_MAX_ICV_SIZE);
244       clib_memcpy_fast (payload + len[0], &seq_hi, N_HI_ESN_BYTES);
245       clib_memcpy_fast (payload + len[0] + N_HI_ESN_BYTES, tmp,
246                         ESP_MAX_ICV_SIZE);
247       *data_len += N_HI_ESN_BYTES;
248       *digest += N_HI_ESN_BYTES;
249     }
250   return N_HI_ESN_BYTES;
251 }
252
253 static_always_inline u8 *
254 esp_move_icv_esn (vlib_main_t * vm, vlib_buffer_t * first,
255                   esp_decrypt_packet_data_t * pd,
256                   esp_decrypt_packet_data2_t * pd2, u16 icv_sz,
257                   ipsec_sa_t * sa, u8 * extra_esn, u32 * len)
258 {
259   u16 dif = 0;
260   u8 *digest = esp_move_icv (vm, first, pd, pd2, icv_sz, &dif);
261   if (dif)
262     *len -= dif;
263
264   if (ipsec_sa_is_set_USE_ESN (sa))
265     {
266       u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
267       u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
268
269       if (space_left >= N_HI_ESN_BYTES)
270         {
271           clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb), &seq_hi,
272                             N_HI_ESN_BYTES);
273           *len += N_HI_ESN_BYTES;
274         }
275       else
276         {
277           /* no space for ESN at the tail, use the next buffer
278            * (with ICV data) */
279           ASSERT (pd2->icv_removed);
280           vlib_buffer_t *tmp = vlib_get_buffer (vm, pd2->free_buffer_index);
281           clib_memcpy_fast (vlib_buffer_get_current (tmp) - N_HI_ESN_BYTES,
282                             &seq_hi, N_HI_ESN_BYTES);
283           extra_esn[0] = 1;
284         }
285     }
286   return digest;
287 }
288
289 static_always_inline int
290 esp_decrypt_chain_integ (vlib_main_t *vm, ipsec_per_thread_data_t *ptd,
291                          const esp_decrypt_packet_data_t *pd,
292                          esp_decrypt_packet_data2_t *pd2, ipsec_sa_t *sa0,
293                          vlib_buffer_t *b, u8 icv_sz, u8 *start_src,
294                          u32 start_len, u8 **digest, u16 *n_ch,
295                          u32 *integ_total_len)
296 {
297   vnet_crypto_op_chunk_t *ch;
298   vlib_buffer_t *cb = vlib_get_buffer (vm, b->next_buffer);
299   u16 n_chunks = 1;
300   u32 total_len;
301   vec_add2 (ptd->chunks, ch, 1);
302   total_len = ch->len = start_len;
303   ch->src = start_src;
304
305   while (1)
306     {
307       vec_add2 (ptd->chunks, ch, 1);
308       n_chunks += 1;
309       ch->src = vlib_buffer_get_current (cb);
310       if (pd2->lb == cb)
311         {
312           if (pd2->icv_removed)
313             ch->len = cb->current_length;
314           else
315             ch->len = cb->current_length - icv_sz;
316           if (ipsec_sa_is_set_USE_ESN (sa0))
317             {
318               u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
319               u8 tmp[ESP_MAX_ICV_SIZE];
320               u8 *esn;
321               vlib_buffer_t *tmp_b;
322               u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
323               if (space_left < N_HI_ESN_BYTES)
324                 {
325                   if (pd2->icv_removed)
326                     {
327                       /* use pre-data area from the last bufer
328                          that was removed from the chain */
329                       tmp_b = vlib_get_buffer (vm, pd2->free_buffer_index);
330                       esn = tmp_b->data - N_HI_ESN_BYTES;
331                     }
332                   else
333                     {
334                       /* no space, need to allocate new buffer */
335                       u32 tmp_bi = 0;
336                       if (vlib_buffer_alloc (vm, &tmp_bi, 1) != 1)
337                         return -1;
338                       tmp_b = vlib_get_buffer (vm, tmp_bi);
339                       esn = tmp_b->data;
340                       pd2->free_buffer_index = tmp_bi;
341                     }
342                   clib_memcpy_fast (esn, &seq_hi, N_HI_ESN_BYTES);
343
344                   vec_add2 (ptd->chunks, ch, 1);
345                   n_chunks += 1;
346                   ch->src = esn;
347                   ch->len = N_HI_ESN_BYTES;
348                 }
349               else
350                 {
351                   if (pd2->icv_removed)
352                     {
353                       clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb),
354                                         &seq_hi, N_HI_ESN_BYTES);
355                     }
356                   else
357                     {
358                       clib_memcpy_fast (tmp, *digest, ESP_MAX_ICV_SIZE);
359                       clib_memcpy_fast (*digest, &seq_hi, N_HI_ESN_BYTES);
360                       clib_memcpy_fast (*digest + N_HI_ESN_BYTES, tmp,
361                                         ESP_MAX_ICV_SIZE);
362                       *digest += N_HI_ESN_BYTES;
363                     }
364                   ch->len += N_HI_ESN_BYTES;
365                 }
366             }
367           total_len += ch->len;
368           break;
369         }
370       else
371         total_len += ch->len = cb->current_length;
372
373       if (!(cb->flags & VLIB_BUFFER_NEXT_PRESENT))
374         break;
375
376       cb = vlib_get_buffer (vm, cb->next_buffer);
377     }
378
379   if (n_ch)
380     *n_ch = n_chunks;
381   if (integ_total_len)
382     *integ_total_len = total_len;
383
384   return 0;
385 }
386
387 static_always_inline u32
388 esp_decrypt_chain_crypto (vlib_main_t * vm, ipsec_per_thread_data_t * ptd,
389                           esp_decrypt_packet_data_t * pd,
390                           esp_decrypt_packet_data2_t * pd2,
391                           ipsec_sa_t * sa0, vlib_buffer_t * b, u8 icv_sz,
392                           u8 * start, u32 start_len, u8 ** tag, u16 * n_ch)
393 {
394   vnet_crypto_op_chunk_t *ch;
395   vlib_buffer_t *cb = b;
396   u16 n_chunks = 1;
397   u32 total_len;
398   vec_add2 (ptd->chunks, ch, 1);
399   total_len = ch->len = start_len;
400   ch->src = ch->dst = start;
401   cb = vlib_get_buffer (vm, cb->next_buffer);
402   n_chunks = 1;
403
404   while (1)
405     {
406       vec_add2 (ptd->chunks, ch, 1);
407       n_chunks += 1;
408       ch->src = ch->dst = vlib_buffer_get_current (cb);
409       if (pd2->lb == cb)
410         {
411           if (ipsec_sa_is_set_IS_AEAD (sa0))
412             {
413               if (pd2->lb->current_length < icv_sz)
414                 {
415                   u16 dif = 0;
416                   *tag = esp_move_icv (vm, b, pd, pd2, icv_sz, &dif);
417
418                   /* this chunk does not contain crypto data */
419                   n_chunks -= 1;
420                   /* and fix previous chunk's length as it might have
421                      been changed */
422                   ASSERT (n_chunks > 0);
423                   if (pd2->lb == b)
424                     {
425                       total_len -= dif;
426                       ch[-1].len -= dif;
427                     }
428                   else
429                     {
430                       total_len = total_len + pd2->lb->current_length -
431                         ch[-1].len;
432                       ch[-1].len = pd2->lb->current_length;
433                     }
434                   break;
435                 }
436               else
437                 *tag = vlib_buffer_get_tail (pd2->lb) - icv_sz;
438             }
439
440           if (pd2->icv_removed)
441             total_len += ch->len = cb->current_length;
442           else
443             total_len += ch->len = cb->current_length - icv_sz;
444         }
445       else
446         total_len += ch->len = cb->current_length;
447
448       if (!(cb->flags & VLIB_BUFFER_NEXT_PRESENT))
449         break;
450
451       cb = vlib_get_buffer (vm, cb->next_buffer);
452     }
453
454   if (n_ch)
455     *n_ch = n_chunks;
456
457   return total_len;
458 }
459
460 static_always_inline void
461 esp_decrypt_prepare_sync_op (vlib_main_t * vm, vlib_node_runtime_t * node,
462                              ipsec_per_thread_data_t * ptd,
463                              vnet_crypto_op_t *** crypto_ops,
464                              vnet_crypto_op_t *** integ_ops,
465                              vnet_crypto_op_t * op,
466                              ipsec_sa_t * sa0, u8 * payload,
467                              u16 len, u8 icv_sz, u8 iv_sz,
468                              esp_decrypt_packet_data_t * pd,
469                              esp_decrypt_packet_data2_t * pd2,
470                              vlib_buffer_t * b, u16 * next, u32 index)
471 {
472   const u8 esp_sz = sizeof (esp_header_t);
473
474   if (PREDICT_TRUE (sa0->integ_op_id != VNET_CRYPTO_OP_NONE))
475     {
476       vnet_crypto_op_init (op, sa0->integ_op_id);
477       op->key_index = sa0->integ_key_index;
478       op->src = payload;
479       op->flags = VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
480       op->user_data = index;
481       op->digest = payload + len;
482       op->digest_len = icv_sz;
483       op->len = len;
484
485       if (pd->is_chain)
486         {
487           /* buffer is chained */
488           op->len = pd->current_length;
489
490           /* special case when ICV is splitted and needs to be reassembled
491            * first -> move it to the last buffer. Also take into account
492            * that ESN needs to be added after encrypted data and may or
493            * may not fit in the tail.*/
494           if (pd2->lb->current_length < icv_sz)
495             {
496               u8 extra_esn = 0;
497               op->digest =
498                 esp_move_icv_esn (vm, b, pd, pd2, icv_sz, sa0,
499                                   &extra_esn, &op->len);
500
501               if (extra_esn)
502                 {
503                   /* esn is in the last buffer, that was unlinked from
504                    * the chain */
505                   op->len = b->current_length;
506                 }
507               else
508                 {
509                   if (pd2->lb == b)
510                     {
511                       /* we now have a single buffer of crypto data, adjust
512                        * the length (second buffer contains only ICV) */
513                       *integ_ops = &ptd->integ_ops;
514                       *crypto_ops = &ptd->crypto_ops;
515                       len = b->current_length;
516                       goto out;
517                     }
518                 }
519             }
520           else
521             op->digest = vlib_buffer_get_tail (pd2->lb) - icv_sz;
522
523           op->flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
524           op->chunk_index = vec_len (ptd->chunks);
525           if (esp_decrypt_chain_integ (vm, ptd, pd, pd2, sa0, b, icv_sz,
526                                        payload, pd->current_length,
527                                        &op->digest, &op->n_chunks, 0) < 0)
528             {
529               esp_decrypt_set_next_index (
530                 b, node, vm->thread_index, ESP_DECRYPT_ERROR_NO_BUFFERS, 0,
531                 next, ESP_DECRYPT_NEXT_DROP, pd->sa_index);
532               return;
533             }
534         }
535       else
536         esp_insert_esn (vm, sa0, pd, pd2, &op->len, &op->digest, &len, b,
537                         payload);
538     out:
539       vec_add_aligned (*(integ_ops[0]), op, 1, CLIB_CACHE_LINE_BYTES);
540     }
541
542   payload += esp_sz;
543   len -= esp_sz;
544
545   if (sa0->crypto_dec_op_id != VNET_CRYPTO_OP_NONE)
546     {
547       vnet_crypto_op_init (op, sa0->crypto_dec_op_id);
548       op->key_index = sa0->crypto_key_index;
549       op->iv = payload;
550
551       if (ipsec_sa_is_set_IS_CTR (sa0))
552         {
553           /* construct nonce in a scratch space in front of the IP header */
554           esp_ctr_nonce_t *nonce =
555             (esp_ctr_nonce_t *) (payload - esp_sz - pd->hdr_sz -
556                                  sizeof (*nonce));
557           if (ipsec_sa_is_set_IS_AEAD (sa0))
558             {
559               /* constuct aad in a scratch space in front of the nonce */
560               esp_header_t *esp0 = (esp_header_t *) (payload - esp_sz);
561               op->aad = (u8 *) nonce - sizeof (esp_aead_t);
562               op->aad_len = esp_aad_fill (op->aad, esp0, sa0, pd->seq_hi);
563               op->tag = payload + len;
564               op->tag_len = 16;
565             }
566           else
567             {
568               nonce->ctr = clib_host_to_net_u32 (1);
569             }
570           nonce->salt = sa0->salt;
571           ASSERT (sizeof (u64) == iv_sz);
572           nonce->iv = *(u64 *) op->iv;
573           op->iv = (u8 *) nonce;
574         }
575       op->src = op->dst = payload += iv_sz;
576       op->len = len - iv_sz;
577       op->user_data = index;
578
579       if (pd->is_chain && (pd2->lb != b))
580         {
581           /* buffer is chained */
582           op->flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
583           op->chunk_index = vec_len (ptd->chunks);
584           esp_decrypt_chain_crypto (vm, ptd, pd, pd2, sa0, b, icv_sz,
585                                     payload, len - pd->iv_sz + pd->icv_sz,
586                                     &op->tag, &op->n_chunks);
587         }
588
589       vec_add_aligned (*(crypto_ops[0]), op, 1, CLIB_CACHE_LINE_BYTES);
590     }
591 }
592
593 static_always_inline esp_decrypt_error_t
594 esp_decrypt_prepare_async_frame (vlib_main_t *vm, vlib_node_runtime_t *node,
595                                  ipsec_per_thread_data_t *ptd,
596                                  vnet_crypto_async_frame_t *f, ipsec_sa_t *sa0,
597                                  u8 *payload, u16 len, u8 icv_sz, u8 iv_sz,
598                                  esp_decrypt_packet_data_t *pd,
599                                  esp_decrypt_packet_data2_t *pd2, u32 bi,
600                                  vlib_buffer_t *b, u16 *next, u16 async_next)
601 {
602   const u8 esp_sz = sizeof (esp_header_t);
603   esp_decrypt_packet_data_t *async_pd = &(esp_post_data (b))->decrypt_data;
604   esp_decrypt_packet_data2_t *async_pd2 = esp_post_data2 (b);
605   u8 *tag = payload + len, *iv = payload + esp_sz, *aad = 0;
606   u32 key_index;
607   u32 crypto_len, integ_len = 0;
608   i16 crypto_start_offset, integ_start_offset = 0;
609   u8 flags = 0;
610
611   if (!ipsec_sa_is_set_IS_AEAD (sa0))
612     {
613       /* linked algs */
614       key_index = sa0->linked_key_index;
615       integ_start_offset = payload - b->data;
616       integ_len = len;
617       if (PREDICT_TRUE (sa0->integ_op_id != VNET_CRYPTO_OP_NONE))
618         flags |= VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
619
620       if (pd->is_chain)
621         {
622           /* buffer is chained */
623           integ_len = pd->current_length;
624
625           /* special case when ICV is splitted and needs to be reassembled
626            * first -> move it to the last buffer. Also take into account
627            * that ESN needs to be added after encrypted data and may or
628            * may not fit in the tail.*/
629           if (pd2->lb->current_length < icv_sz)
630             {
631               u8 extra_esn = 0;
632               tag = esp_move_icv_esn (vm, b, pd, pd2, icv_sz, sa0,
633                                       &extra_esn, &integ_len);
634
635               if (extra_esn)
636                 {
637                   /* esn is in the last buffer, that was unlinked from
638                    * the chain */
639                   integ_len = b->current_length;
640                 }
641               else
642                 {
643                   if (pd2->lb == b)
644                     {
645                       /* we now have a single buffer of crypto data, adjust
646                        * the length (second buffer contains only ICV) */
647                       len = b->current_length;
648                       goto out;
649                     }
650                 }
651             }
652           else
653             tag = vlib_buffer_get_tail (pd2->lb) - icv_sz;
654
655           flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
656           if (esp_decrypt_chain_integ (vm, ptd, pd, pd2, sa0, b, icv_sz,
657                                        payload, pd->current_length, &tag, 0,
658                                        &integ_len) < 0)
659             {
660               /* allocate buffer failed, will not add to frame and drop */
661               return (ESP_DECRYPT_ERROR_NO_BUFFERS);
662             }
663         }
664       else
665         esp_insert_esn (vm, sa0, pd, pd2, &integ_len, &tag, &len, b, payload);
666     }
667   else
668     key_index = sa0->crypto_key_index;
669
670 out:
671   /* crypto */
672   payload += esp_sz;
673   len -= esp_sz;
674   iv = payload;
675
676   if (ipsec_sa_is_set_IS_CTR (sa0))
677     {
678       /* construct nonce in a scratch space in front of the IP header */
679       esp_ctr_nonce_t *nonce =
680         (esp_ctr_nonce_t *) (payload - esp_sz - pd->hdr_sz - sizeof (*nonce));
681       if (ipsec_sa_is_set_IS_AEAD (sa0))
682         {
683           /* constuct aad in a scratch space in front of the nonce */
684           esp_header_t *esp0 = (esp_header_t *) (payload - esp_sz);
685           aad = (u8 *) nonce - sizeof (esp_aead_t);
686           esp_aad_fill (aad, esp0, sa0, pd->seq_hi);
687           tag = payload + len;
688         }
689       else
690         {
691           nonce->ctr = clib_host_to_net_u32 (1);
692         }
693       nonce->salt = sa0->salt;
694       ASSERT (sizeof (u64) == iv_sz);
695       nonce->iv = *(u64 *) iv;
696       iv = (u8 *) nonce;
697     }
698
699   crypto_start_offset = (payload += iv_sz) - b->data;
700   crypto_len = len - iv_sz;
701
702   if (pd->is_chain && (pd2->lb != b))
703     {
704       /* buffer is chained */
705       flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
706
707       crypto_len = esp_decrypt_chain_crypto (vm, ptd, pd, pd2, sa0, b, icv_sz,
708                                              payload,
709                                              len - pd->iv_sz + pd->icv_sz,
710                                              &tag, 0);
711     }
712
713   *async_pd = *pd;
714   *async_pd2 = *pd2;
715
716   /* for AEAD integ_len - crypto_len will be negative, it is ok since it
717    * is ignored by the engine. */
718   vnet_crypto_async_add_to_frame (
719     vm, f, key_index, crypto_len, integ_len - crypto_len, crypto_start_offset,
720     integ_start_offset, bi, async_next, iv, tag, aad, flags);
721
722   return (ESP_DECRYPT_ERROR_RX_PKTS);
723 }
724
725 static_always_inline void
726 esp_decrypt_post_crypto (vlib_main_t *vm, vlib_node_runtime_t *node,
727                          const u16 *next_by_next_header,
728                          const esp_decrypt_packet_data_t *pd,
729                          const esp_decrypt_packet_data2_t *pd2,
730                          vlib_buffer_t *b, u16 *next, int is_ip6, int is_tun,
731                          int is_async)
732 {
733   ipsec_sa_t *sa0 = ipsec_sa_get (pd->sa_index);
734   vlib_buffer_t *lb = b;
735   const u8 esp_sz = sizeof (esp_header_t);
736   const u8 tun_flags = IPSEC_SA_FLAG_IS_TUNNEL | IPSEC_SA_FLAG_IS_TUNNEL_V6;
737   u8 pad_length = 0, next_header = 0;
738   u16 icv_sz;
739
740   /*
741    * redo the anti-reply check
742    * in this frame say we have sequence numbers, s, s+1, s+1, s+1
743    * and s and s+1 are in the window. When we did the anti-replay
744    * check above we did so against the state of the window (W),
745    * after packet s-1. So each of the packets in the sequence will be
746    * accepted.
747    * This time s will be cheked against Ws-1, s+1 chceked against Ws
748    * (i.e. the window state is updated/advnaced)
749    * so this time the successive s+! packet will be dropped.
750    * This is a consequence of batching the decrypts. If the
751    * check-dcrypt-advance process was done for each packet it would
752    * be fine. But we batch the decrypts because it's much more efficient
753    * to do so in SW and if we offload to HW and the process is async.
754    *
755    * You're probably thinking, but this means an attacker can send the
756    * above sequence and cause VPP to perform decrpyts that will fail,
757    * and that's true. But if the attacker can determine s (a valid
758    * sequence number in the window) which is non-trivial, it can generate
759    * a sequence s, s+1, s+2, s+3, ... s+n and nothing will prevent any
760    * implementation, sequential or batching, from decrypting these.
761    */
762   if (ipsec_sa_anti_replay_and_sn_advance (sa0, pd->seq, pd->seq_hi, true,
763                                            NULL))
764     {
765       esp_decrypt_set_next_index (b, node, vm->thread_index,
766                                   ESP_DECRYPT_ERROR_REPLAY, 0, next,
767                                   ESP_DECRYPT_NEXT_DROP, pd->sa_index);
768       return;
769     }
770
771   u64 n_lost =
772     ipsec_sa_anti_replay_advance (sa0, vm->thread_index, pd->seq, pd->seq_hi);
773
774   vlib_prefetch_simple_counter (&ipsec_sa_err_counters[IPSEC_SA_ERROR_LOST],
775                                 vm->thread_index, pd->sa_index);
776
777   if (pd->is_chain)
778     {
779       lb = pd2->lb;
780       icv_sz = pd2->icv_removed ? 0 : pd->icv_sz;
781       if (pd2->free_buffer_index)
782         {
783           vlib_buffer_free_one (vm, pd2->free_buffer_index);
784           lb->next_buffer = 0;
785         }
786       if (lb->current_length < sizeof (esp_footer_t) + icv_sz)
787         {
788           /* esp footer is either splitted in two buffers or in the before
789            * last buffer */
790
791           vlib_buffer_t *before_last = b, *bp = b;
792           while (bp->flags & VLIB_BUFFER_NEXT_PRESENT)
793             {
794               before_last = bp;
795               bp = vlib_get_buffer (vm, bp->next_buffer);
796             }
797           u8 *bt = vlib_buffer_get_tail (before_last);
798
799           if (lb->current_length == icv_sz)
800             {
801               esp_footer_t *f = (esp_footer_t *) (bt - sizeof (*f));
802               pad_length = f->pad_length;
803               next_header = f->next_header;
804             }
805           else
806             {
807               pad_length = (bt - 1)[0];
808               next_header = ((u8 *) vlib_buffer_get_current (lb))[0];
809             }
810         }
811       else
812         {
813           esp_footer_t *f =
814             (esp_footer_t *) (lb->data + lb->current_data +
815                               lb->current_length - sizeof (esp_footer_t) -
816                               icv_sz);
817           pad_length = f->pad_length;
818           next_header = f->next_header;
819         }
820     }
821   else
822     {
823       icv_sz = pd->icv_sz;
824       esp_footer_t *f =
825         (esp_footer_t *) (lb->data + lb->current_data + lb->current_length -
826                           sizeof (esp_footer_t) - icv_sz);
827       pad_length = f->pad_length;
828       next_header = f->next_header;
829     }
830
831   u16 adv = pd->iv_sz + esp_sz;
832   u16 tail = sizeof (esp_footer_t) + pad_length + icv_sz;
833   u16 tail_orig = sizeof (esp_footer_t) + pad_length + pd->icv_sz;
834   b->flags &= ~VLIB_BUFFER_TOTAL_LENGTH_VALID;
835
836   if ((pd->flags & tun_flags) == 0 && !is_tun)  /* transport mode */
837     {
838       u8 udp_sz = (is_ip6 == 0 && pd->flags & IPSEC_SA_FLAG_UDP_ENCAP) ?
839         sizeof (udp_header_t) : 0;
840       u16 ip_hdr_sz = pd->hdr_sz - udp_sz;
841       u8 *old_ip = b->data + pd->current_data - ip_hdr_sz - udp_sz;
842       u8 *ip = old_ip + adv + udp_sz;
843
844       if (is_ip6 && ip_hdr_sz > 64)
845         memmove (ip, old_ip, ip_hdr_sz);
846       else
847         clib_memcpy_le64 (ip, old_ip, ip_hdr_sz);
848
849       b->current_data = pd->current_data + adv - ip_hdr_sz;
850       b->current_length += ip_hdr_sz - adv;
851       esp_remove_tail (vm, b, lb, tail);
852
853       if (is_ip6)
854         {
855           ip6_header_t *ip6 = (ip6_header_t *) ip;
856           u16 len = clib_net_to_host_u16 (ip6->payload_length);
857           len -= adv + tail_orig;
858           ip6->payload_length = clib_host_to_net_u16 (len);
859           ip6->protocol = next_header;
860           next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
861         }
862       else
863         {
864           ip4_header_t *ip4 = (ip4_header_t *) ip;
865           ip_csum_t sum = ip4->checksum;
866           u16 len = clib_net_to_host_u16 (ip4->length);
867           len = clib_host_to_net_u16 (len - adv - tail_orig - udp_sz);
868           sum = ip_csum_update (sum, ip4->protocol, next_header,
869                                 ip4_header_t, protocol);
870           sum = ip_csum_update (sum, ip4->length, len, ip4_header_t, length);
871           ip4->checksum = ip_csum_fold (sum);
872           ip4->protocol = next_header;
873           ip4->length = len;
874           next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
875         }
876     }
877   else
878     {
879       if (PREDICT_TRUE (next_header == IP_PROTOCOL_IP_IN_IP))
880         {
881           next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
882           b->current_data = pd->current_data + adv;
883           b->current_length = pd->current_length - adv;
884           esp_remove_tail (vm, b, lb, tail);
885         }
886       else if (next_header == IP_PROTOCOL_IPV6)
887         {
888           next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
889           b->current_data = pd->current_data + adv;
890           b->current_length = pd->current_length - adv;
891           esp_remove_tail (vm, b, lb, tail);
892         }
893       else if (next_header == IP_PROTOCOL_MPLS_IN_IP)
894         {
895           next[0] = ESP_DECRYPT_NEXT_MPLS_INPUT;
896           b->current_data = pd->current_data + adv;
897           b->current_length = pd->current_length - adv;
898           esp_remove_tail (vm, b, lb, tail);
899         }
900       else if (is_tun && next_header == IP_PROTOCOL_GRE)
901         {
902           gre_header_t *gre;
903
904           b->current_data = pd->current_data + adv;
905           b->current_length = pd->current_length - adv - tail;
906
907           gre = vlib_buffer_get_current (b);
908
909           vlib_buffer_advance (b, sizeof (*gre));
910
911           switch (clib_net_to_host_u16 (gre->protocol))
912             {
913             case GRE_PROTOCOL_teb:
914               vnet_update_l2_len (b);
915               next[0] = ESP_DECRYPT_NEXT_L2_INPUT;
916               break;
917             case GRE_PROTOCOL_ip4:
918               next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
919               break;
920             case GRE_PROTOCOL_ip6:
921               next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
922               break;
923             default:
924               esp_decrypt_set_next_index (
925                 b, node, vm->thread_index, ESP_DECRYPT_ERROR_UNSUP_PAYLOAD, 0,
926                 next, ESP_DECRYPT_NEXT_DROP, pd->sa_index);
927               break;
928             }
929         }
930       else if ((next[0] = vec_elt (next_by_next_header, next_header)) !=
931                (u16) ~0)
932         {
933           b->current_data = pd->current_data + adv;
934           b->current_length = pd->current_length - adv;
935           esp_remove_tail (vm, b, lb, tail);
936         }
937       else
938         {
939           esp_decrypt_set_next_index (b, node, vm->thread_index,
940                                       ESP_DECRYPT_ERROR_UNSUP_PAYLOAD, 0, next,
941                                       ESP_DECRYPT_NEXT_DROP, pd->sa_index);
942           return;
943         }
944
945       if (is_tun)
946         {
947           if (ipsec_sa_is_set_IS_PROTECT (sa0))
948             {
949               /*
950                * There are two encap possibilities
951                * 1) the tunnel and ths SA are prodiving encap, i.e. it's
952                *   MAC | SA-IP | TUN-IP | ESP | PAYLOAD
953                * implying the SA is in tunnel mode (on a tunnel interface)
954                * 2) only the tunnel provides encap
955                *   MAC | TUN-IP | ESP | PAYLOAD
956                * implying the SA is in transport mode.
957                *
958                * For 2) we need only strip the tunnel encap and we're good.
959                *  since the tunnel and crypto ecnap (int the tun=protect
960                * object) are the same and we verified above that these match
961                * for 1) we need to strip the SA-IP outer headers, to
962                * reveal the tunnel IP and then check that this matches
963                * the configured tunnel.
964                */
965               const ipsec_tun_protect_t *itp;
966
967               itp =
968                 ipsec_tun_protect_get (vnet_buffer (b)->ipsec.protect_index);
969
970               if (PREDICT_TRUE (next_header == IP_PROTOCOL_IP_IN_IP))
971                 {
972                   const ip4_header_t *ip4;
973
974                   ip4 = vlib_buffer_get_current (b);
975
976                   if (!ip46_address_is_equal_v4 (&itp->itp_tun.src,
977                                                  &ip4->dst_address) ||
978                       !ip46_address_is_equal_v4 (&itp->itp_tun.dst,
979                                                  &ip4->src_address))
980                     {
981                       esp_decrypt_set_next_index (
982                         b, node, vm->thread_index,
983                         ESP_DECRYPT_ERROR_TUN_NO_PROTO, 0, next,
984                         ESP_DECRYPT_NEXT_DROP, pd->sa_index);
985                     }
986                 }
987               else if (next_header == IP_PROTOCOL_IPV6)
988                 {
989                   const ip6_header_t *ip6;
990
991                   ip6 = vlib_buffer_get_current (b);
992
993                   if (!ip46_address_is_equal_v6 (&itp->itp_tun.src,
994                                                  &ip6->dst_address) ||
995                       !ip46_address_is_equal_v6 (&itp->itp_tun.dst,
996                                                  &ip6->src_address))
997                     {
998                       esp_decrypt_set_next_index (
999                         b, node, vm->thread_index,
1000                         ESP_DECRYPT_ERROR_TUN_NO_PROTO, 0, next,
1001                         ESP_DECRYPT_NEXT_DROP, pd->sa_index);
1002                     }
1003                 }
1004             }
1005         }
1006     }
1007
1008   if (PREDICT_FALSE (n_lost))
1009     vlib_increment_simple_counter (&ipsec_sa_err_counters[IPSEC_SA_ERROR_LOST],
1010                                    vm->thread_index, pd->sa_index, n_lost);
1011 }
1012
1013 always_inline uword
1014 esp_decrypt_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
1015                     vlib_frame_t *from_frame, int is_ip6, int is_tun,
1016                     u16 async_next_node)
1017 {
1018   ipsec_main_t *im = &ipsec_main;
1019   const u16 *next_by_next_header = im->next_header_registrations;
1020   u32 thread_index = vm->thread_index;
1021   u16 len;
1022   ipsec_per_thread_data_t *ptd = vec_elt_at_index (im->ptd, thread_index);
1023   u32 *from = vlib_frame_vector_args (from_frame);
1024   u32 n_left = from_frame->n_vectors;
1025   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
1026   vlib_buffer_t *sync_bufs[VLIB_FRAME_SIZE];
1027   u16 sync_nexts[VLIB_FRAME_SIZE], *sync_next = sync_nexts, n_sync = 0;
1028   u16 async_nexts[VLIB_FRAME_SIZE], *async_next = async_nexts;
1029   u16 noop_nexts[VLIB_FRAME_SIZE], n_noop = 0;
1030   u32 sync_bi[VLIB_FRAME_SIZE];
1031   u32 noop_bi[VLIB_FRAME_SIZE];
1032   esp_decrypt_packet_data_t pkt_data[VLIB_FRAME_SIZE], *pd = pkt_data;
1033   esp_decrypt_packet_data2_t pkt_data2[VLIB_FRAME_SIZE], *pd2 = pkt_data2;
1034   esp_decrypt_packet_data_t cpd = { };
1035   u32 current_sa_index = ~0, current_sa_bytes = 0, current_sa_pkts = 0;
1036   const u8 esp_sz = sizeof (esp_header_t);
1037   ipsec_sa_t *sa0 = 0;
1038   vnet_crypto_op_t _op, *op = &_op;
1039   vnet_crypto_op_t **crypto_ops;
1040   vnet_crypto_op_t **integ_ops;
1041   int is_async = im->async_mode;
1042   vnet_crypto_async_op_id_t async_op = ~0;
1043   vnet_crypto_async_frame_t *async_frames[VNET_CRYPTO_ASYNC_OP_N_IDS];
1044   esp_decrypt_error_t err;
1045
1046   vlib_get_buffers (vm, from, b, n_left);
1047   if (!is_async)
1048     {
1049       vec_reset_length (ptd->crypto_ops);
1050       vec_reset_length (ptd->integ_ops);
1051       vec_reset_length (ptd->chained_crypto_ops);
1052       vec_reset_length (ptd->chained_integ_ops);
1053     }
1054   vec_reset_length (ptd->async_frames);
1055   vec_reset_length (ptd->chunks);
1056   clib_memset (sync_nexts, -1, sizeof (sync_nexts));
1057   clib_memset (async_frames, 0, sizeof (async_frames));
1058
1059   while (n_left > 0)
1060     {
1061       u8 *payload;
1062
1063       err = ESP_DECRYPT_ERROR_RX_PKTS;
1064       if (n_left > 2)
1065         {
1066           u8 *p;
1067           vlib_prefetch_buffer_header (b[2], LOAD);
1068           p = vlib_buffer_get_current (b[1]);
1069           clib_prefetch_load (p);
1070           p -= CLIB_CACHE_LINE_BYTES;
1071           clib_prefetch_load (p);
1072         }
1073
1074       u32 n_bufs = vlib_buffer_chain_linearize (vm, b[0]);
1075       if (n_bufs == 0)
1076         {
1077           err = ESP_DECRYPT_ERROR_NO_BUFFERS;
1078           esp_decrypt_set_next_index (b[0], node, thread_index, err, n_noop,
1079                                       noop_nexts, ESP_DECRYPT_NEXT_DROP,
1080                                       vnet_buffer (b[0])->ipsec.sad_index);
1081           goto next;
1082         }
1083
1084       if (vnet_buffer (b[0])->ipsec.sad_index != current_sa_index)
1085         {
1086           if (current_sa_pkts)
1087             vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
1088                                              current_sa_index, current_sa_pkts,
1089                                              current_sa_bytes);
1090           current_sa_bytes = current_sa_pkts = 0;
1091
1092           current_sa_index = vnet_buffer (b[0])->ipsec.sad_index;
1093           vlib_prefetch_combined_counter (&ipsec_sa_counters, thread_index,
1094                                           current_sa_index);
1095           sa0 = ipsec_sa_get (current_sa_index);
1096
1097           /* fetch the second cacheline ASAP */
1098           clib_prefetch_load (sa0->cacheline1);
1099           cpd.icv_sz = sa0->integ_icv_size;
1100           cpd.iv_sz = sa0->crypto_iv_size;
1101           cpd.flags = sa0->flags;
1102           cpd.sa_index = current_sa_index;
1103           is_async = im->async_mode | ipsec_sa_is_set_IS_ASYNC (sa0);
1104         }
1105
1106       if (PREDICT_FALSE (~0 == sa0->thread_index))
1107         {
1108           /* this is the first packet to use this SA, claim the SA
1109            * for this thread. this could happen simultaneously on
1110            * another thread */
1111           clib_atomic_cmp_and_swap (&sa0->thread_index, ~0,
1112                                     ipsec_sa_assign_thread (thread_index));
1113         }
1114
1115       if (PREDICT_FALSE (thread_index != sa0->thread_index))
1116         {
1117           vnet_buffer (b[0])->ipsec.thread_index = sa0->thread_index;
1118           err = ESP_DECRYPT_ERROR_HANDOFF;
1119           esp_decrypt_set_next_index (b[0], node, thread_index, err, n_noop,
1120                                       noop_nexts, ESP_DECRYPT_NEXT_HANDOFF,
1121                                       current_sa_index);
1122           goto next;
1123         }
1124
1125       /* store packet data for next round for easier prefetch */
1126       pd->sa_data = cpd.sa_data;
1127       pd->current_data = b[0]->current_data;
1128       pd->hdr_sz = pd->current_data - vnet_buffer (b[0])->l3_hdr_offset;
1129       payload = b[0]->data + pd->current_data;
1130       pd->seq = clib_host_to_net_u32 (((esp_header_t *) payload)->seq);
1131       pd->is_chain = 0;
1132       pd2->lb = b[0];
1133       pd2->free_buffer_index = 0;
1134       pd2->icv_removed = 0;
1135
1136       if (n_bufs > 1)
1137         {
1138           pd->is_chain = 1;
1139           /* find last buffer in the chain */
1140           while (pd2->lb->flags & VLIB_BUFFER_NEXT_PRESENT)
1141             pd2->lb = vlib_get_buffer (vm, pd2->lb->next_buffer);
1142
1143           crypto_ops = &ptd->chained_crypto_ops;
1144           integ_ops = &ptd->chained_integ_ops;
1145         }
1146       else
1147         {
1148           crypto_ops = &ptd->crypto_ops;
1149           integ_ops = &ptd->integ_ops;
1150         }
1151
1152       pd->current_length = b[0]->current_length;
1153
1154       /* anti-reply check */
1155       if (ipsec_sa_anti_replay_and_sn_advance (sa0, pd->seq, ~0, false,
1156                                                &pd->seq_hi))
1157         {
1158           err = ESP_DECRYPT_ERROR_REPLAY;
1159           esp_decrypt_set_next_index (b[0], node, thread_index, err, n_noop,
1160                                       noop_nexts, ESP_DECRYPT_NEXT_DROP,
1161                                       current_sa_index);
1162           goto next;
1163         }
1164
1165       if (pd->current_length < cpd.icv_sz + esp_sz + cpd.iv_sz)
1166         {
1167           err = ESP_DECRYPT_ERROR_RUNT;
1168           esp_decrypt_set_next_index (b[0], node, thread_index, err, n_noop,
1169                                       noop_nexts, ESP_DECRYPT_NEXT_DROP,
1170                                       current_sa_index);
1171           goto next;
1172         }
1173
1174       len = pd->current_length - cpd.icv_sz;
1175       current_sa_pkts += 1;
1176       current_sa_bytes += vlib_buffer_length_in_chain (vm, b[0]);
1177
1178       if (is_async)
1179         {
1180           async_op = sa0->crypto_async_dec_op_id;
1181
1182           /* get a frame for this op if we don't yet have one or it's full
1183            */
1184           if (NULL == async_frames[async_op] ||
1185               vnet_crypto_async_frame_is_full (async_frames[async_op]))
1186             {
1187               async_frames[async_op] =
1188                 vnet_crypto_async_get_frame (vm, async_op);
1189               /* Save the frame to the list we'll submit at the end */
1190               vec_add1 (ptd->async_frames, async_frames[async_op]);
1191             }
1192
1193           err = esp_decrypt_prepare_async_frame (
1194             vm, node, ptd, async_frames[async_op], sa0, payload, len,
1195             cpd.icv_sz, cpd.iv_sz, pd, pd2, from[b - bufs], b[0], async_next,
1196             async_next_node);
1197           if (ESP_DECRYPT_ERROR_RX_PKTS != err)
1198             {
1199               esp_decrypt_set_next_index (
1200                 b[0], node, thread_index, err, n_noop, noop_nexts,
1201                 ESP_DECRYPT_NEXT_DROP, current_sa_index);
1202             }
1203         }
1204       else
1205         esp_decrypt_prepare_sync_op (
1206           vm, node, ptd, &crypto_ops, &integ_ops, op, sa0, payload, len,
1207           cpd.icv_sz, cpd.iv_sz, pd, pd2, b[0], sync_next, n_sync);
1208       /* next */
1209     next:
1210       if (ESP_DECRYPT_ERROR_RX_PKTS != err)
1211         {
1212           noop_bi[n_noop] = from[b - bufs];
1213           n_noop++;
1214         }
1215       else if (!is_async)
1216         {
1217           sync_bi[n_sync] = from[b - bufs];
1218           sync_bufs[n_sync] = b[0];
1219           n_sync++;
1220           sync_next++;
1221           pd += 1;
1222           pd2 += 1;
1223         }
1224       else
1225         async_next++;
1226
1227       n_left -= 1;
1228       b += 1;
1229     }
1230
1231   if (PREDICT_TRUE (~0 != current_sa_index))
1232     vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
1233                                      current_sa_index, current_sa_pkts,
1234                                      current_sa_bytes);
1235
1236   /* submit or free all of the open frames */
1237   vnet_crypto_async_frame_t **async_frame;
1238
1239   vec_foreach (async_frame, ptd->async_frames)
1240     {
1241       /* free frame and move on if no ops were successfully added */
1242       if (PREDICT_FALSE (!(*async_frame)->n_elts))
1243         {
1244           vnet_crypto_async_free_frame (vm, *async_frame);
1245           continue;
1246         }
1247       if (vnet_crypto_async_submit_open_frame (vm, *async_frame) < 0)
1248         {
1249           n_noop += esp_async_recycle_failed_submit (
1250             vm, *async_frame, node, ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR,
1251             IPSEC_SA_ERROR_CRYPTO_ENGINE_ERROR, n_noop, noop_bi, noop_nexts,
1252             ESP_DECRYPT_NEXT_DROP);
1253           vnet_crypto_async_reset_frame (*async_frame);
1254           vnet_crypto_async_free_frame (vm, *async_frame);
1255         }
1256     }
1257
1258   if (n_sync)
1259     {
1260       esp_process_ops (vm, node, ptd->integ_ops, sync_bufs, sync_nexts,
1261                        ESP_DECRYPT_ERROR_INTEG_ERROR);
1262       esp_process_chained_ops (vm, node, ptd->chained_integ_ops, sync_bufs,
1263                                sync_nexts, ptd->chunks,
1264                                ESP_DECRYPT_ERROR_INTEG_ERROR);
1265
1266       esp_process_ops (vm, node, ptd->crypto_ops, sync_bufs, sync_nexts,
1267                        ESP_DECRYPT_ERROR_DECRYPTION_FAILED);
1268       esp_process_chained_ops (vm, node, ptd->chained_crypto_ops, sync_bufs,
1269                                sync_nexts, ptd->chunks,
1270                                ESP_DECRYPT_ERROR_DECRYPTION_FAILED);
1271     }
1272
1273   /* Post decryption ronud - adjust packet data start and length and next
1274      node */
1275
1276   n_left = n_sync;
1277   sync_next = sync_nexts;
1278   pd = pkt_data;
1279   pd2 = pkt_data2;
1280   b = sync_bufs;
1281
1282   while (n_left)
1283     {
1284       if (n_left >= 2)
1285         {
1286           void *data = b[1]->data + pd[1].current_data;
1287
1288           /* buffer metadata */
1289           vlib_prefetch_buffer_header (b[1], LOAD);
1290
1291           /* esp_footer_t */
1292           CLIB_PREFETCH (data + pd[1].current_length - pd[1].icv_sz - 2,
1293                          CLIB_CACHE_LINE_BYTES, LOAD);
1294
1295           /* packet headers */
1296           CLIB_PREFETCH (data - CLIB_CACHE_LINE_BYTES,
1297                          CLIB_CACHE_LINE_BYTES * 2, LOAD);
1298         }
1299
1300       /* save the sa_index as GRE_teb post_crypto changes L2 opaque */
1301       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1302         current_sa_index = vnet_buffer (b[0])->ipsec.sad_index;
1303
1304       if (sync_next[0] >= ESP_DECRYPT_N_NEXT)
1305         esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, pd2, b[0],
1306                                  sync_next, is_ip6, is_tun, 0);
1307
1308       /* trace: */
1309       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1310         {
1311           esp_decrypt_trace_t *tr;
1312           tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
1313           sa0 = ipsec_sa_get (current_sa_index);
1314           tr->crypto_alg = sa0->crypto_alg;
1315           tr->integ_alg = sa0->integ_alg;
1316           tr->seq = pd->seq;
1317           tr->sa_seq = sa0->seq;
1318           tr->sa_seq_hi = sa0->seq_hi;
1319           tr->pkt_seq_hi = pd->seq_hi;
1320         }
1321
1322       /* next */
1323       n_left -= 1;
1324       sync_next += 1;
1325       pd += 1;
1326       pd2 += 1;
1327       b += 1;
1328     }
1329
1330   vlib_node_increment_counter (vm, node->node_index, ESP_DECRYPT_ERROR_RX_PKTS,
1331                                from_frame->n_vectors);
1332
1333   if (n_sync)
1334     vlib_buffer_enqueue_to_next (vm, node, sync_bi, sync_nexts, n_sync);
1335
1336   if (n_noop)
1337     vlib_buffer_enqueue_to_next (vm, node, noop_bi, noop_nexts, n_noop);
1338
1339   return (from_frame->n_vectors);
1340 }
1341
1342 always_inline uword
1343 esp_decrypt_post_inline (vlib_main_t * vm,
1344                          vlib_node_runtime_t * node,
1345                          vlib_frame_t * from_frame, int is_ip6, int is_tun)
1346 {
1347   const ipsec_main_t *im = &ipsec_main;
1348   const u16 *next_by_next_header = im->next_header_registrations;
1349   u32 *from = vlib_frame_vector_args (from_frame);
1350   u32 n_left = from_frame->n_vectors;
1351   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
1352   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
1353   vlib_get_buffers (vm, from, b, n_left);
1354
1355   while (n_left > 0)
1356     {
1357       esp_decrypt_packet_data_t *pd = &(esp_post_data (b[0]))->decrypt_data;
1358
1359       if (n_left > 2)
1360         {
1361           vlib_prefetch_buffer_header (b[2], LOAD);
1362           vlib_prefetch_buffer_header (b[1], LOAD);
1363         }
1364
1365       if (!pd->is_chain)
1366         esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, 0, b[0],
1367                                  next, is_ip6, is_tun, 1);
1368       else
1369         {
1370           esp_decrypt_packet_data2_t *pd2 = esp_post_data2 (b[0]);
1371           esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, pd2,
1372                                    b[0], next, is_ip6, is_tun, 1);
1373         }
1374
1375       /*trace: */
1376       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1377         {
1378           ipsec_sa_t *sa0 = ipsec_sa_get (pd->sa_index);
1379           esp_decrypt_trace_t *tr;
1380           esp_decrypt_packet_data_t *async_pd =
1381             &(esp_post_data (b[0]))->decrypt_data;
1382           tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
1383           sa0 = ipsec_sa_get (async_pd->sa_index);
1384
1385           tr->crypto_alg = sa0->crypto_alg;
1386           tr->integ_alg = sa0->integ_alg;
1387           tr->seq = pd->seq;
1388           tr->sa_seq = sa0->seq;
1389           tr->sa_seq_hi = sa0->seq_hi;
1390         }
1391
1392       n_left--;
1393       next++;
1394       b++;
1395     }
1396
1397   n_left = from_frame->n_vectors;
1398   vlib_node_increment_counter (vm, node->node_index,
1399                                ESP_DECRYPT_ERROR_RX_POST_PKTS, n_left);
1400
1401   vlib_buffer_enqueue_to_next (vm, node, from, nexts, n_left);
1402
1403   return n_left;
1404 }
1405
1406 VLIB_NODE_FN (esp4_decrypt_node) (vlib_main_t * vm,
1407                                   vlib_node_runtime_t * node,
1408                                   vlib_frame_t * from_frame)
1409 {
1410   return esp_decrypt_inline (vm, node, from_frame, 0, 0,
1411                              esp_decrypt_async_next.esp4_post_next);
1412 }
1413
1414 VLIB_NODE_FN (esp4_decrypt_post_node) (vlib_main_t * vm,
1415                                        vlib_node_runtime_t * node,
1416                                        vlib_frame_t * from_frame)
1417 {
1418   return esp_decrypt_post_inline (vm, node, from_frame, 0, 0);
1419 }
1420
1421 VLIB_NODE_FN (esp4_decrypt_tun_node) (vlib_main_t * vm,
1422                                       vlib_node_runtime_t * node,
1423                                       vlib_frame_t * from_frame)
1424 {
1425   return esp_decrypt_inline (vm, node, from_frame, 0, 1,
1426                              esp_decrypt_async_next.esp4_tun_post_next);
1427 }
1428
1429 VLIB_NODE_FN (esp4_decrypt_tun_post_node) (vlib_main_t * vm,
1430                                            vlib_node_runtime_t * node,
1431                                            vlib_frame_t * from_frame)
1432 {
1433   return esp_decrypt_post_inline (vm, node, from_frame, 0, 1);
1434 }
1435
1436 VLIB_NODE_FN (esp6_decrypt_node) (vlib_main_t * vm,
1437                                   vlib_node_runtime_t * node,
1438                                   vlib_frame_t * from_frame)
1439 {
1440   return esp_decrypt_inline (vm, node, from_frame, 1, 0,
1441                              esp_decrypt_async_next.esp6_post_next);
1442 }
1443
1444 VLIB_NODE_FN (esp6_decrypt_post_node) (vlib_main_t * vm,
1445                                        vlib_node_runtime_t * node,
1446                                        vlib_frame_t * from_frame)
1447 {
1448   return esp_decrypt_post_inline (vm, node, from_frame, 1, 0);
1449 }
1450
1451 VLIB_NODE_FN (esp6_decrypt_tun_node) (vlib_main_t * vm,
1452                                       vlib_node_runtime_t * node,
1453                                       vlib_frame_t * from_frame)
1454 {
1455   return esp_decrypt_inline (vm, node, from_frame, 1, 1,
1456                              esp_decrypt_async_next.esp6_tun_post_next);
1457 }
1458
1459 VLIB_NODE_FN (esp6_decrypt_tun_post_node) (vlib_main_t * vm,
1460                                            vlib_node_runtime_t * node,
1461                                            vlib_frame_t * from_frame)
1462 {
1463   return esp_decrypt_post_inline (vm, node, from_frame, 1, 1);
1464 }
1465
1466 /* *INDENT-OFF* */
1467 VLIB_REGISTER_NODE (esp4_decrypt_node) = {
1468   .name = "esp4-decrypt",
1469   .vector_size = sizeof (u32),
1470   .format_trace = format_esp_decrypt_trace,
1471   .type = VLIB_NODE_TYPE_INTERNAL,
1472
1473   .n_errors = ESP_DECRYPT_N_ERROR,
1474   .error_counters = esp_decrypt_error_counters,
1475
1476   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1477   .next_nodes = {
1478     [ESP_DECRYPT_NEXT_DROP] = "ip4-drop",
1479     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1480     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1481     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-drop",
1482     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1483     [ESP_DECRYPT_NEXT_HANDOFF] = "esp4-decrypt-handoff",
1484   },
1485 };
1486
1487 VLIB_REGISTER_NODE (esp4_decrypt_post_node) = {
1488   .name = "esp4-decrypt-post",
1489   .vector_size = sizeof (u32),
1490   .format_trace = format_esp_decrypt_trace,
1491   .type = VLIB_NODE_TYPE_INTERNAL,
1492
1493   .n_errors = ESP_DECRYPT_N_ERROR,
1494   .error_counters = esp_decrypt_error_counters,
1495
1496   .sibling_of = "esp4-decrypt",
1497 };
1498
1499 VLIB_REGISTER_NODE (esp6_decrypt_node) = {
1500   .name = "esp6-decrypt",
1501   .vector_size = sizeof (u32),
1502   .format_trace = format_esp_decrypt_trace,
1503   .type = VLIB_NODE_TYPE_INTERNAL,
1504
1505   .n_errors = ESP_DECRYPT_N_ERROR,
1506   .error_counters = esp_decrypt_error_counters,
1507
1508   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1509   .next_nodes = {
1510     [ESP_DECRYPT_NEXT_DROP] = "ip6-drop",
1511     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1512     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1513     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-drop",
1514     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1515     [ESP_DECRYPT_NEXT_HANDOFF]=  "esp6-decrypt-handoff",
1516   },
1517 };
1518
1519 VLIB_REGISTER_NODE (esp6_decrypt_post_node) = {
1520   .name = "esp6-decrypt-post",
1521   .vector_size = sizeof (u32),
1522   .format_trace = format_esp_decrypt_trace,
1523   .type = VLIB_NODE_TYPE_INTERNAL,
1524
1525   .n_errors = ESP_DECRYPT_N_ERROR,
1526   .error_counters = esp_decrypt_error_counters,
1527
1528   .sibling_of = "esp6-decrypt",
1529 };
1530
1531 VLIB_REGISTER_NODE (esp4_decrypt_tun_node) = {
1532   .name = "esp4-decrypt-tun",
1533   .vector_size = sizeof (u32),
1534   .format_trace = format_esp_decrypt_trace,
1535   .type = VLIB_NODE_TYPE_INTERNAL,
1536   .n_errors = ESP_DECRYPT_N_ERROR,
1537   .error_counters = esp_decrypt_error_counters,
1538   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1539   .next_nodes = {
1540     [ESP_DECRYPT_NEXT_DROP] = "ip4-drop",
1541     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1542     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1543     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-input",
1544     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1545     [ESP_DECRYPT_NEXT_HANDOFF] = "esp4-decrypt-tun-handoff",
1546   },
1547 };
1548
1549 VLIB_REGISTER_NODE (esp4_decrypt_tun_post_node) = {
1550   .name = "esp4-decrypt-tun-post",
1551   .vector_size = sizeof (u32),
1552   .format_trace = format_esp_decrypt_trace,
1553   .type = VLIB_NODE_TYPE_INTERNAL,
1554
1555   .n_errors = ESP_DECRYPT_N_ERROR,
1556   .error_counters = esp_decrypt_error_counters,
1557
1558   .sibling_of = "esp4-decrypt-tun",
1559 };
1560
1561 VLIB_REGISTER_NODE (esp6_decrypt_tun_node) = {
1562   .name = "esp6-decrypt-tun",
1563   .vector_size = sizeof (u32),
1564   .format_trace = format_esp_decrypt_trace,
1565   .type = VLIB_NODE_TYPE_INTERNAL,
1566   .n_errors = ESP_DECRYPT_N_ERROR,
1567   .error_counters = esp_decrypt_error_counters,
1568   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1569   .next_nodes = {
1570     [ESP_DECRYPT_NEXT_DROP] = "ip6-drop",
1571     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1572     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1573     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-input",
1574     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1575     [ESP_DECRYPT_NEXT_HANDOFF]=  "esp6-decrypt-tun-handoff",
1576   },
1577 };
1578
1579 VLIB_REGISTER_NODE (esp6_decrypt_tun_post_node) = {
1580   .name = "esp6-decrypt-tun-post",
1581   .vector_size = sizeof (u32),
1582   .format_trace = format_esp_decrypt_trace,
1583   .type = VLIB_NODE_TYPE_INTERNAL,
1584
1585   .n_errors = ESP_DECRYPT_N_ERROR,
1586   .error_counters = esp_decrypt_error_counters,
1587
1588   .sibling_of = "esp6-decrypt-tun",
1589 };
1590 /* *INDENT-ON* */
1591
1592 #ifndef CLIB_MARCH_VARIANT
1593
1594 static clib_error_t *
1595 esp_decrypt_init (vlib_main_t *vm)
1596 {
1597   ipsec_main_t *im = &ipsec_main;
1598
1599   im->esp4_dec_fq_index =
1600     vlib_frame_queue_main_init (esp4_decrypt_node.index, 0);
1601   im->esp6_dec_fq_index =
1602     vlib_frame_queue_main_init (esp6_decrypt_node.index, 0);
1603   im->esp4_dec_tun_fq_index =
1604     vlib_frame_queue_main_init (esp4_decrypt_tun_node.index, 0);
1605   im->esp6_dec_tun_fq_index =
1606     vlib_frame_queue_main_init (esp6_decrypt_tun_node.index, 0);
1607
1608   return 0;
1609 }
1610
1611 VLIB_INIT_FUNCTION (esp_decrypt_init);
1612
1613 #endif
1614
1615 /*
1616  * fd.io coding-style-patch-verification: ON
1617  *
1618  * Local Variables:
1619  * eval: (c-set-style "gnu")
1620  * End:
1621  */