crypto: improve key handling
[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
22 #include <vnet/ipsec/ipsec.h>
23 #include <vnet/ipsec/esp.h>
24 #include <vnet/ipsec/ipsec_io.h>
25
26 #define foreach_esp_decrypt_next                \
27 _(DROP, "error-drop")                           \
28 _(IP4_INPUT, "ip4-input-no-checksum")           \
29 _(IP6_INPUT, "ip6-input")                       \
30 _(IPSEC_GRE_INPUT, "ipsec-gre-input")
31
32 #define _(v, s) ESP_DECRYPT_NEXT_##v,
33 typedef enum
34 {
35   foreach_esp_decrypt_next
36 #undef _
37     ESP_DECRYPT_N_NEXT,
38 } esp_decrypt_next_t;
39
40
41 #define foreach_esp_decrypt_error                               \
42  _(RX_PKTS, "ESP pkts received")                                \
43  _(DECRYPTION_FAILED, "ESP decryption failed")                  \
44  _(INTEG_ERROR, "Integrity check failed")                       \
45  _(CRYPTO_ENGINE_ERROR, "crypto engine error (packet dropped)") \
46  _(REPLAY, "SA replayed packet")                                \
47  _(CHAINED_BUFFER, "chained buffers (packet dropped)")          \
48  _(OVERSIZED_HEADER, "buffer with oversized header (dropped)")  \
49  _(NO_TAIL_SPACE, "no enough buffer tail space (dropped)")
50
51
52 typedef enum
53 {
54 #define _(sym,str) ESP_DECRYPT_ERROR_##sym,
55   foreach_esp_decrypt_error
56 #undef _
57     ESP_DECRYPT_N_ERROR,
58 } esp_decrypt_error_t;
59
60 static char *esp_decrypt_error_strings[] = {
61 #define _(sym,string) string,
62   foreach_esp_decrypt_error
63 #undef _
64 };
65
66 typedef struct
67 {
68   u32 seq;
69   ipsec_crypto_alg_t crypto_alg;
70   ipsec_integ_alg_t integ_alg;
71 } esp_decrypt_trace_t;
72
73 /* packet trace format function */
74 static u8 *
75 format_esp_decrypt_trace (u8 * s, va_list * args)
76 {
77   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
78   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
79   esp_decrypt_trace_t *t = va_arg (*args, esp_decrypt_trace_t *);
80
81   s = format (s, "esp: crypto %U integrity %U seq %u",
82               format_ipsec_crypto_alg, t->crypto_alg,
83               format_ipsec_integ_alg, t->integ_alg, t->seq);
84   return s;
85 }
86
87 typedef struct
88 {
89   union
90   {
91     struct
92     {
93       u8 icv_sz;
94       u8 iv_sz;
95       ipsec_sa_flags_t flags:8;
96       u32 sa_index;
97     };
98     u64 sa_data;
99   };
100
101   i16 current_data;
102   i16 current_length;
103   u16 hdr_sz;
104 } esp_decrypt_packet_data_t;
105
106 STATIC_ASSERT_SIZEOF (esp_decrypt_packet_data_t, 2 * sizeof (u64));
107
108 #define ESP_ENCRYPT_PD_F_FD_TRANSPORT (1 << 2)
109
110 always_inline uword
111 esp_decrypt_inline (vlib_main_t * vm,
112                     vlib_node_runtime_t * node, vlib_frame_t * from_frame,
113                     int is_ip6)
114 {
115   ipsec_main_t *im = &ipsec_main;
116   u32 thread_index = vm->thread_index;
117   u16 buffer_data_size = vlib_buffer_get_default_data_size (vm);
118   u16 len;
119   ipsec_per_thread_data_t *ptd = vec_elt_at_index (im->ptd, thread_index);
120   u32 *from = vlib_frame_vector_args (from_frame);
121   u32 n, n_left = from_frame->n_vectors;
122   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
123   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
124   esp_decrypt_packet_data_t pkt_data[VLIB_FRAME_SIZE], *pd = pkt_data;
125   esp_decrypt_packet_data_t cpd = { };
126   u32 current_sa_index = ~0, current_sa_bytes = 0, current_sa_pkts = 0;
127   const u8 esp_sz = sizeof (esp_header_t);
128   ipsec_sa_t *sa0 = 0;
129
130   vlib_get_buffers (vm, from, b, n_left);
131   vec_reset_length (ptd->crypto_ops);
132   vec_reset_length (ptd->integ_ops);
133   clib_memset_u16 (nexts, -1, n_left);
134
135   while (n_left > 0)
136     {
137       u8 *payload;
138
139       if (n_left > 2)
140         {
141           u8 *p;
142           vlib_prefetch_buffer_header (b[2], LOAD);
143           p = vlib_buffer_get_current (b[1]);
144           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
145           p -= CLIB_CACHE_LINE_BYTES;
146           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
147         }
148
149       if (vlib_buffer_chain_linearize (vm, b[0]) != 1)
150         {
151           b[0]->error = node->errors[ESP_DECRYPT_ERROR_CHAINED_BUFFER];
152           next[0] = ESP_DECRYPT_NEXT_DROP;
153           goto next;
154         }
155
156       if (vnet_buffer (b[0])->ipsec.sad_index != current_sa_index)
157         {
158           current_sa_index = vnet_buffer (b[0])->ipsec.sad_index;
159           sa0 = pool_elt_at_index (im->sad, current_sa_index);
160           cpd.icv_sz = sa0->integ_icv_size;
161           cpd.iv_sz = sa0->crypto_iv_size;
162           cpd.flags = sa0->flags;
163           cpd.sa_index = current_sa_index;
164
165           vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
166                                            current_sa_index, current_sa_pkts,
167                                            current_sa_bytes);
168
169           current_sa_bytes = current_sa_pkts = 0;
170         }
171
172       /* store packet data for next round for easier prefetch */
173       pd->sa_data = cpd.sa_data;
174       pd->current_data = b[0]->current_data;
175       pd->current_length = b[0]->current_length;
176       pd->hdr_sz = pd->current_data - vnet_buffer (b[0])->l3_hdr_offset;
177       payload = b[0]->data + pd->current_data;
178
179       /* we need 4 extra bytes for HMAC calculation when ESN are used */
180       if (ipsec_sa_is_set_USE_ESN (sa0) && pd->icv_sz &&
181           (pd->current_data + pd->current_length + 4 > buffer_data_size))
182         {
183           b[0]->error = node->errors[ESP_DECRYPT_ERROR_NO_TAIL_SPACE];
184           next[0] = ESP_DECRYPT_NEXT_DROP;
185           goto next;
186         }
187
188       /* anti-reply check */
189       if (ipsec_sa_anti_replay_check (sa0, &((esp_header_t *) payload)->seq))
190         {
191           b[0]->error = node->errors[ESP_DECRYPT_ERROR_REPLAY];
192           next[0] = ESP_DECRYPT_NEXT_DROP;
193           goto next;
194         }
195
196       len = pd->current_length - cpd.icv_sz;
197       current_sa_pkts += 1;
198       current_sa_bytes += pd->current_length;
199
200       if (PREDICT_TRUE (sa0->integ_op_id != VNET_CRYPTO_OP_NONE))
201         {
202           vnet_crypto_op_t *op;
203           vec_add2_aligned (ptd->integ_ops, op, 1, CLIB_CACHE_LINE_BYTES);
204
205           vnet_crypto_op_init (op, sa0->integ_op_id);
206           op->key_index = sa0->integ_key_index;
207           op->src = payload;
208           op->flags = VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
209           op->user_data = b - bufs;
210           op->digest = payload + len;
211           op->digest_len = cpd.icv_sz;
212           op->len = len;
213           if (ipsec_sa_is_set_USE_ESN (sa0))
214             {
215               /* shift ICV for 4 bytes to insert ESN */
216               u8 tmp[ESP_MAX_ICV_SIZE], sz = sizeof (sa0->seq_hi);
217               clib_memcpy_fast (tmp, payload + len, ESP_MAX_ICV_SIZE);
218               clib_memcpy_fast (payload + len, &sa0->seq_hi, sz);
219               clib_memcpy_fast (payload + len + sz, tmp, ESP_MAX_ICV_SIZE);
220               op->len += sz;
221               op->digest += sz;
222             }
223         }
224
225       payload += esp_sz;
226       len -= esp_sz;
227
228       if (sa0->crypto_enc_op_id != VNET_CRYPTO_OP_NONE)
229         {
230           vnet_crypto_op_t *op;
231           vec_add2_aligned (ptd->crypto_ops, op, 1, CLIB_CACHE_LINE_BYTES);
232           vnet_crypto_op_init (op, sa0->crypto_dec_op_id);
233           op->key_index = sa0->crypto_key_index;
234           op->iv = payload;
235
236           if (ipsec_sa_is_set_IS_AEAD (sa0))
237             {
238               esp_header_t *esp0;
239               esp_aead_t *aad;
240               u8 *scratch;
241
242               /*
243                * construct the AAD and the nonce (Salt || IV) in a scratch
244                * space in front of the IP header.
245                */
246               scratch = payload - esp_sz;
247               esp0 = (esp_header_t *) (scratch);
248
249               scratch -= (sizeof (*aad) + pd->hdr_sz);
250               op->aad = scratch;
251
252               esp_aad_fill (op, esp0, sa0);
253
254               /*
255                * we don't need to refer to the ESP header anymore so we
256                * can overwrite it with the salt and use the IV where it is
257                * to form the nonce = (Salt + IV)
258                */
259               op->iv -= sizeof (sa0->salt);
260               clib_memcpy_fast (op->iv, &sa0->salt, sizeof (sa0->salt));
261               op->iv_len = cpd.iv_sz + sizeof (sa0->salt);
262
263               op->tag = payload + len;
264               op->tag_len = 16;
265             }
266           op->src = op->dst = payload += cpd.iv_sz;
267           op->len = len - cpd.iv_sz;
268           op->user_data = b - bufs;
269         }
270
271       /* next */
272     next:
273       n_left -= 1;
274       next += 1;
275       pd += 1;
276       b += 1;
277     }
278
279   vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
280                                    current_sa_index, current_sa_pkts,
281                                    current_sa_bytes);
282
283   if ((n = vec_len (ptd->integ_ops)))
284     {
285       vnet_crypto_op_t *op = ptd->integ_ops;
286       n -= vnet_crypto_process_ops (vm, op, n);
287       while (n)
288         {
289           ASSERT (op - ptd->integ_ops < vec_len (ptd->integ_ops));
290           if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
291             {
292               u32 err, bi = op->user_data;
293               if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
294                 err = ESP_DECRYPT_ERROR_INTEG_ERROR;
295               else
296                 err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
297               bufs[bi]->error = node->errors[err];
298               nexts[bi] = ESP_DECRYPT_NEXT_DROP;
299               n--;
300             }
301           op++;
302         }
303     }
304   if ((n = vec_len (ptd->crypto_ops)))
305     {
306       vnet_crypto_op_t *op = ptd->crypto_ops;
307       n -= vnet_crypto_process_ops (vm, op, n);
308       while (n)
309         {
310           ASSERT (op - ptd->crypto_ops < vec_len (ptd->crypto_ops));
311           if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
312             {
313               u32 err, bi;
314
315               bi = op->user_data;
316
317               if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
318                 err = ESP_DECRYPT_ERROR_DECRYPTION_FAILED;
319               else
320                 err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
321
322               bufs[bi]->error = node->errors[err];
323               nexts[bi] = ESP_DECRYPT_NEXT_DROP;
324               n--;
325             }
326           op++;
327         }
328     }
329
330   /* Post decryption ronud - adjust packet data start and length and next
331      node */
332
333   n_left = from_frame->n_vectors;
334   next = nexts;
335   pd = pkt_data;
336   b = bufs;
337
338   while (n_left)
339     {
340       const u8 tun_flags = IPSEC_SA_FLAG_IS_TUNNEL |
341         IPSEC_SA_FLAG_IS_TUNNEL_V6;
342
343       if (n_left >= 2)
344         {
345           void *data = b[1]->data + pd[1].current_data;
346
347           /* buffer metadata */
348           vlib_prefetch_buffer_header (b[1], LOAD);
349
350           /* esp_footer_t */
351           CLIB_PREFETCH (data + pd[1].current_length - pd[1].icv_sz - 2,
352                          CLIB_CACHE_LINE_BYTES, LOAD);
353
354           /* packet headers */
355           CLIB_PREFETCH (data - CLIB_CACHE_LINE_BYTES,
356                          CLIB_CACHE_LINE_BYTES * 2, LOAD);
357         }
358
359       if (next[0] < ESP_DECRYPT_N_NEXT)
360         goto trace;
361
362       sa0 = vec_elt_at_index (im->sad, pd->sa_index);
363       u8 *payload = b[0]->data + pd->current_data;
364
365       ipsec_sa_anti_replay_advance (sa0, &((esp_header_t *) payload)->seq);
366
367       esp_footer_t *f = (esp_footer_t *) (b[0]->data + pd->current_data +
368                                           pd->current_length - sizeof (*f) -
369                                           pd->icv_sz);
370       u16 adv = pd->iv_sz + esp_sz;
371       u16 tail = sizeof (esp_footer_t) + f->pad_length + pd->icv_sz;
372
373       if ((pd->flags & tun_flags) == 0) /* transport mode */
374         {
375           u8 udp_sz = (is_ip6 == 0 && pd->flags & IPSEC_SA_FLAG_UDP_ENCAP) ?
376             sizeof (udp_header_t) : 0;
377           u16 ip_hdr_sz = pd->hdr_sz - udp_sz;
378           u8 *old_ip = b[0]->data + pd->current_data - ip_hdr_sz - udp_sz;
379           u8 *ip = old_ip + adv + udp_sz;
380
381           if (is_ip6 && ip_hdr_sz > 64)
382             memmove (ip, old_ip, ip_hdr_sz);
383           else
384             clib_memcpy_le64 (ip, old_ip, ip_hdr_sz);
385
386           b[0]->current_data = pd->current_data + adv - ip_hdr_sz;
387           b[0]->current_length = pd->current_length + ip_hdr_sz - tail - adv;
388
389           if (is_ip6)
390             {
391               ip6_header_t *ip6 = (ip6_header_t *) ip;
392               u16 len = clib_net_to_host_u16 (ip6->payload_length);
393               len -= adv + tail;
394               ip6->payload_length = clib_host_to_net_u16 (len);
395               ip6->protocol = f->next_header;
396               next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
397             }
398           else
399             {
400               ip4_header_t *ip4 = (ip4_header_t *) ip;
401               ip_csum_t sum = ip4->checksum;
402               u16 len = clib_net_to_host_u16 (ip4->length);
403               len = clib_host_to_net_u16 (len - adv - tail - udp_sz);
404               sum = ip_csum_update (sum, ip4->protocol, f->next_header,
405                                     ip4_header_t, protocol);
406               sum = ip_csum_update (sum, ip4->length, len,
407                                     ip4_header_t, length);
408               ip4->checksum = ip_csum_fold (sum);
409               ip4->protocol = f->next_header;
410               ip4->length = len;
411               next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
412             }
413         }
414       else
415         {
416           if (PREDICT_TRUE (f->next_header == IP_PROTOCOL_IP_IN_IP))
417             {
418               next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
419               b[0]->current_data = pd->current_data + adv;
420               b[0]->current_length = pd->current_length + adv - tail;
421             }
422           else if (f->next_header == IP_PROTOCOL_IPV6)
423             {
424               next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
425               b[0]->current_data = pd->current_data + adv;
426               b[0]->current_length = pd->current_length + adv - tail;
427             }
428           else
429             {
430               next[0] = ESP_DECRYPT_NEXT_DROP;
431               b[0]->error = node->errors[ESP_DECRYPT_ERROR_DECRYPTION_FAILED];
432             }
433         }
434
435       if (PREDICT_FALSE (ipsec_sa_is_set_IS_GRE (sa0)))
436         next[0] = ESP_DECRYPT_NEXT_IPSEC_GRE_INPUT;
437
438     trace:
439       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
440         {
441           esp_decrypt_trace_t *tr;
442           u8 *payload = b[0]->data + pd->current_data;
443           tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
444           sa0 = pool_elt_at_index (im->sad,
445                                    vnet_buffer (b[0])->ipsec.sad_index);
446           tr->crypto_alg = sa0->crypto_alg;
447           tr->integ_alg = sa0->integ_alg;
448           tr->seq = clib_host_to_net_u32 (((esp_header_t *) payload)->seq);
449         }
450
451       /* next */
452       n_left -= 1;
453       next += 1;
454       pd += 1;
455       b += 1;
456     }
457
458   n_left = from_frame->n_vectors;
459   vlib_node_increment_counter (vm, node->node_index,
460                                ESP_DECRYPT_ERROR_RX_PKTS, n_left);
461
462   vlib_buffer_enqueue_to_next (vm, node, from, nexts, n_left);
463
464   b = bufs;
465   return n_left;
466 }
467
468 VLIB_NODE_FN (esp4_decrypt_node) (vlib_main_t * vm,
469                                   vlib_node_runtime_t * node,
470                                   vlib_frame_t * from_frame)
471 {
472   return esp_decrypt_inline (vm, node, from_frame, 0 /* is_ip6 */ );
473 }
474
475 /* *INDENT-OFF* */
476 VLIB_REGISTER_NODE (esp4_decrypt_node) = {
477   .name = "esp4-decrypt",
478   .vector_size = sizeof (u32),
479   .format_trace = format_esp_decrypt_trace,
480   .type = VLIB_NODE_TYPE_INTERNAL,
481
482   .n_errors = ARRAY_LEN(esp_decrypt_error_strings),
483   .error_strings = esp_decrypt_error_strings,
484
485   .n_next_nodes = ESP_DECRYPT_N_NEXT,
486   .next_nodes = {
487 #define _(s,n) [ESP_DECRYPT_NEXT_##s] = n,
488     foreach_esp_decrypt_next
489 #undef _
490   },
491 };
492 /* *INDENT-ON* */
493
494 VLIB_NODE_FN (esp6_decrypt_node) (vlib_main_t * vm,
495                                   vlib_node_runtime_t * node,
496                                   vlib_frame_t * from_frame)
497 {
498   return esp_decrypt_inline (vm, node, from_frame, 1 /* is_ip6 */ );
499 }
500
501 /* *INDENT-OFF* */
502 VLIB_REGISTER_NODE (esp6_decrypt_node) = {
503   .name = "esp6-decrypt",
504   .vector_size = sizeof (u32),
505   .format_trace = format_esp_decrypt_trace,
506   .type = VLIB_NODE_TYPE_INTERNAL,
507
508   .n_errors = ARRAY_LEN(esp_decrypt_error_strings),
509   .error_strings = esp_decrypt_error_strings,
510
511   .n_next_nodes = ESP_DECRYPT_N_NEXT,
512   .next_nodes = {
513 #define _(s,n) [ESP_DECRYPT_NEXT_##s] = n,
514     foreach_esp_decrypt_next
515 #undef _
516   },
517 };
518 /* *INDENT-ON* */
519
520 /*
521  * fd.io coding-style-patch-verification: ON
522  *
523  * Local Variables:
524  * eval: (c-set-style "gnu")
525  * End:
526  */