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