Initial commit of vpp code.
[vpp.git] / vnet / vnet / ipsec / esp_encrypt.c
1 /*
2  * esp_encrypt.c : IPSec ESP encrypt 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
25 #define ESP_SEQ_MAX (4294967295UL)
26
27 #define foreach_esp_encrypt_next                   \
28 _(DROP, "error-drop")                              \
29 _(IP4_INPUT, "ip4-input")                          \
30 _(IP6_INPUT, "ip6-input")                          \
31 _(INTERFACE_OUTPUT, "interface-output")
32
33 #define _(v, s) ESP_ENCRYPT_NEXT_##v,
34 typedef enum {
35   foreach_esp_encrypt_next
36 #undef _
37   ESP_ENCRYPT_N_NEXT,
38 } esp_encrypt_next_t;
39
40 #define foreach_esp_encrypt_error                   \
41  _(RX_PKTS, "ESP pkts received")                    \
42  _(NO_BUFFER, "No buffer (packet dropped)")         \
43  _(DECRYPTION_FAILED, "ESP encryption failed")      \
44  _(SEQ_CYCLED, "sequence number cycled")
45
46
47 typedef enum {
48 #define _(sym,str) ESP_ENCRYPT_ERROR_##sym,
49   foreach_esp_encrypt_error
50 #undef _
51   ESP_ENCRYPT_N_ERROR,
52 } esp_encrypt_error_t;
53
54 static char * esp_encrypt_error_strings[] = {
55 #define _(sym,string) string,
56   foreach_esp_encrypt_error
57 #undef _
58 };
59
60 vlib_node_registration_t esp_encrypt_node;
61
62 typedef struct {
63   u32 spi;
64   u32 seq;
65   ipsec_crypto_alg_t crypto_alg;
66   ipsec_integ_alg_t integ_alg;
67 } esp_encrypt_trace_t;
68
69 /* packet trace format function */
70 static u8 * format_esp_encrypt_trace (u8 * s, va_list * args)
71 {
72   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
73   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
74   esp_encrypt_trace_t * t = va_arg (*args, esp_encrypt_trace_t *);
75
76   s = format (s, "esp: spi %u seq %u crypto %U integrity %U",
77               t->spi, t->seq,
78               format_ipsec_crypto_alg, t->crypto_alg,
79               format_ipsec_integ_alg, t->integ_alg);
80   return s;
81 }
82
83 always_inline void
84 esp_encrypt_aes_cbc(ipsec_crypto_alg_t alg,
85                     u8 * in,
86                     u8 * out,
87                     size_t in_len,
88                     u8 * key,
89                     u8 * iv)
90 {
91   esp_main_t * em = &esp_main;
92   EVP_CIPHER_CTX * ctx = &(em->encrypt_ctx);
93   const EVP_CIPHER * cipher = NULL;
94   int out_len;
95
96   ASSERT(alg < IPSEC_CRYPTO_N_ALG);
97
98   if (PREDICT_FALSE(em->esp_crypto_algs[alg].type == IPSEC_CRYPTO_ALG_NONE))
99     return;
100
101   if (PREDICT_FALSE(alg != em->last_encrytp_alg)) {
102     cipher = em->esp_crypto_algs[alg].type;
103     em->last_encrytp_alg = alg;
104   }
105
106   EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv);
107
108   EVP_EncryptUpdate(ctx, out, &out_len, in, in_len);
109   EVP_EncryptFinal_ex(ctx, out + out_len, &out_len);
110 }
111
112 always_inline int
113 esp_seq_advance (ipsec_sa_t * sa)
114 {
115   if (PREDICT_TRUE(sa->use_esn))
116     {
117       if (PREDICT_FALSE(sa->seq == ESP_SEQ_MAX))
118         {
119           if (PREDICT_FALSE(sa->use_anti_replay && sa->seq_hi == ESP_SEQ_MAX))
120             return 1;
121           sa->seq_hi++;
122         }
123       sa->seq++;
124     }
125   else
126     {
127       if (PREDICT_FALSE(sa->use_anti_replay && sa->seq == ESP_SEQ_MAX))
128         return 1;
129       sa->seq++;
130     }
131
132   return 0;
133 }
134
135 static uword
136 esp_encrypt_node_fn (vlib_main_t * vm,
137                      vlib_node_runtime_t * node,
138                      vlib_frame_t * from_frame)
139 {
140   u32 n_left_from, *from, * to_next = 0, next_index;
141   from = vlib_frame_vector_args (from_frame);
142   n_left_from = from_frame->n_vectors;
143   ipsec_main_t *im = &ipsec_main;
144   u32 * recycle = 0;
145
146   ipsec_alloc_empty_buffers(vm, im);
147
148   if (PREDICT_FALSE(vec_len (im->empty_buffers) < n_left_from)){
149     vlib_node_increment_counter (vm, esp_encrypt_node.index,
150                                  ESP_ENCRYPT_ERROR_NO_BUFFER, n_left_from);
151     clib_warning("no enough empty buffers. discarding frame");
152     goto free_buffers_and_exit;
153   }
154
155   next_index = node->cached_next_index;
156
157   while (n_left_from > 0)
158     {
159       u32 n_left_to_next;
160
161       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
162
163       while (n_left_from > 0 && n_left_to_next > 0)
164         {
165           u32 i_bi0, o_bi0, next0;
166           vlib_buffer_t * i_b0, *o_b0 = 0;
167           u32 sa_index0;
168           ipsec_sa_t * sa0;
169           ip4_and_esp_header_t * ih0, * oh0 = 0;
170           ip6_and_esp_header_t * ih6_0, * oh6_0 = 0;
171           uword last_empty_buffer;
172           esp_header_t * o_esp0;
173           esp_footer_t *f0;
174           u8 is_ipv6;
175           u8 ip_hdr_size;
176           u8 next_hdr_type;
177
178           i_bi0 = from[0];
179           from += 1;
180           n_left_from -= 1;
181           n_left_to_next -= 1;
182
183           next0 = ESP_ENCRYPT_NEXT_DROP;
184
185           i_b0 = vlib_get_buffer (vm, i_bi0);
186           sa_index0 = vnet_buffer(i_b0)->output_features.ipsec_sad_index;
187           sa0 = pool_elt_at_index(im->sad, sa_index0);
188
189           if (PREDICT_FALSE(esp_seq_advance(sa0)))
190             {
191               clib_warning("sequence number counter has cycled SPI %u", sa0->spi);
192               vlib_node_increment_counter (vm, esp_encrypt_node.index,
193                                            ESP_ENCRYPT_ERROR_SEQ_CYCLED, 1);
194               //TODO: rekey SA
195               o_bi0 = i_bi0;
196               goto trace;
197             }
198
199           /* grab free buffer */
200           last_empty_buffer = vec_len (im->empty_buffers) - 1;
201           o_bi0 = im->empty_buffers[last_empty_buffer];
202           o_b0 = vlib_get_buffer (vm, o_bi0);
203           o_b0->current_data = sizeof(ethernet_header_t);
204           ih0 = vlib_buffer_get_current (i_b0);
205           vlib_prefetch_buffer_with_index (vm, im->empty_buffers[last_empty_buffer-1], STORE);
206           _vec_len (im->empty_buffers) = last_empty_buffer;
207           to_next[0] = o_bi0;
208           to_next += 1;
209
210           /* add old buffer to the recycle list */
211           vec_add1(recycle, i_bi0);
212
213           /* is ipv6 */
214           if (PREDICT_FALSE((ih0->ip4.ip_version_and_header_length & 0xF0 ) == 0x60))
215             {
216               is_ipv6 = 1;
217               ih6_0 = vlib_buffer_get_current (i_b0);
218               ip_hdr_size = sizeof(ip6_header_t);
219               next_hdr_type = IP_PROTOCOL_IPV6;
220               oh6_0 = vlib_buffer_get_current (o_b0);
221               o_esp0 = vlib_buffer_get_current (o_b0) + sizeof(ip6_header_t);
222
223               oh6_0->ip6.ip_version_traffic_class_and_flow_label =
224                   ih6_0->ip6.ip_version_traffic_class_and_flow_label;
225               oh6_0->ip6.protocol = IP_PROTOCOL_IPSEC_ESP;
226               oh6_0->ip6.hop_limit = 254;
227               oh6_0->esp.spi = clib_net_to_host_u32(sa0->spi);
228               oh6_0->esp.seq = clib_net_to_host_u32(sa0->seq);
229             }
230           else
231             {
232               is_ipv6 = 0;
233               ip_hdr_size = sizeof(ip4_header_t);
234               next_hdr_type = IP_PROTOCOL_IP_IN_IP;
235               oh0 = vlib_buffer_get_current (o_b0);
236               o_esp0 = vlib_buffer_get_current (o_b0) + sizeof(ip4_header_t);
237
238               oh0->ip4.ip_version_and_header_length = 0x45;
239               oh0->ip4.tos = ih0->ip4.tos;
240               oh0->ip4.fragment_id = 0;
241               oh0->ip4.flags_and_fragment_offset = 0;
242               oh0->ip4.ttl = 254;
243               oh0->ip4.protocol = IP_PROTOCOL_IPSEC_ESP;
244               oh0->esp.spi = clib_net_to_host_u32(sa0->spi);
245               oh0->esp.seq = clib_net_to_host_u32(sa0->seq);
246             }
247
248           if (PREDICT_TRUE(sa0->is_tunnel && !sa0->is_tunnel_ip6))
249             {
250               oh0->ip4.src_address.as_u32 = sa0->tunnel_src_addr.ip4.as_u32;
251               oh0->ip4.dst_address.as_u32 = sa0->tunnel_dst_addr.ip4.as_u32;
252
253               /* in tunnel mode send it back to FIB */
254               next0 = ESP_ENCRYPT_NEXT_IP4_INPUT;
255               vnet_buffer (o_b0)->sw_if_index[VLIB_TX] = (u32)~0;
256             }
257           else if(sa0->is_tunnel && sa0->is_tunnel_ip6)
258             {
259               oh6_0->ip6.src_address.as_u64[0] = sa0->tunnel_src_addr.ip6.as_u64[0];
260               oh6_0->ip6.src_address.as_u64[1] = sa0->tunnel_src_addr.ip6.as_u64[1];
261               oh6_0->ip6.dst_address.as_u64[0] = sa0->tunnel_dst_addr.ip6.as_u64[0];
262               oh6_0->ip6.dst_address.as_u64[1] = sa0->tunnel_dst_addr.ip6.as_u64[1];
263
264               /* in tunnel mode send it back to FIB */
265               next0 = ESP_ENCRYPT_NEXT_IP6_INPUT;
266               vnet_buffer (o_b0)->sw_if_index[VLIB_TX] = (u32)~0;
267             }
268           else
269             {
270               next0 = ESP_ENCRYPT_NEXT_INTERFACE_OUTPUT;
271               vnet_buffer (o_b0)->sw_if_index[VLIB_TX] =
272                 vnet_buffer (i_b0)->sw_if_index[VLIB_TX];
273             }
274
275           ASSERT(sa0->crypto_alg < IPSEC_CRYPTO_N_ALG);
276
277           if (PREDICT_TRUE(sa0->crypto_alg != IPSEC_CRYPTO_ALG_NONE)) {
278
279             const int BLOCK_SIZE = 16;
280             const int IV_SIZE = 16;
281             int blocks = 1 + (i_b0->current_length + 1) / BLOCK_SIZE;
282
283             /* pad packet in input buffer */
284             u8 pad_bytes = BLOCK_SIZE * blocks - 2 - i_b0->current_length;
285             u8 i;
286             u8 * padding = vlib_buffer_get_current (i_b0) + i_b0->current_length;
287             i_b0->current_length = BLOCK_SIZE * blocks;
288             for (i = 0; i < pad_bytes; ++i)
289               {
290                 padding[i] = i + 1;
291               }
292             f0 = vlib_buffer_get_current (i_b0) + i_b0->current_length - 2;
293             f0->pad_length = pad_bytes;
294             f0->next_header = next_hdr_type;
295
296             o_b0->current_length = ip_hdr_size + sizeof(esp_header_t) +
297                   BLOCK_SIZE * blocks + IV_SIZE;
298
299             vnet_buffer (o_b0)->sw_if_index[VLIB_RX] =
300               vnet_buffer (i_b0)->sw_if_index[VLIB_RX];
301             o_b0->flags = VLIB_BUFFER_TOTAL_LENGTH_VALID;
302
303             u8 iv[16];
304             RAND_bytes(iv, sizeof(iv));
305
306             memcpy((u8 *) vlib_buffer_get_current (o_b0) + ip_hdr_size +
307                    sizeof(esp_header_t), iv, 16 );
308
309             esp_encrypt_aes_cbc(sa0->crypto_alg,
310                                 (u8 *) vlib_buffer_get_current (i_b0),
311                                 (u8 *) vlib_buffer_get_current (o_b0) +
312                                   ip_hdr_size + sizeof(esp_header_t) + IV_SIZE,
313                                 BLOCK_SIZE * blocks,
314                                 sa0->crypto_key,
315                                 iv);
316           }
317
318           o_b0->current_length += hmac_calc(sa0->integ_alg, sa0->integ_key,
319                                             sa0->integ_key_len,
320                                             (u8 *) o_esp0,
321                                             o_b0->current_length - ip_hdr_size,
322                                             vlib_buffer_get_current (o_b0) +
323                                             o_b0->current_length,
324                                             sa0->use_esn,
325                                             sa0->seq_hi);
326
327
328           if (PREDICT_FALSE(is_ipv6))
329             {
330               oh6_0->ip6.payload_length = clib_host_to_net_u16 (
331                   vlib_buffer_length_in_chain (vm, o_b0) - sizeof(ip6_header_t));
332             }
333           else
334             {
335               oh0->ip4.length = clib_host_to_net_u16 (
336                   vlib_buffer_length_in_chain (vm, o_b0));
337               oh0->ip4.checksum = ip4_header_checksum (&oh0->ip4);
338             }
339
340 trace:
341           if (PREDICT_FALSE(i_b0->flags & VLIB_BUFFER_IS_TRACED)) {
342             if (o_b0) {
343               o_b0->flags |= VLIB_BUFFER_IS_TRACED;
344               o_b0->trace_index = i_b0->trace_index;
345             }
346             esp_encrypt_trace_t *tr = vlib_add_trace (vm, node, o_b0, sizeof (*tr));
347             tr->spi = sa0->spi;
348             tr->seq = sa0->seq - 1;
349             tr->crypto_alg = sa0->crypto_alg;
350             tr->integ_alg = sa0->integ_alg;
351           }
352
353           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
354               to_next, n_left_to_next, o_bi0, next0);
355         }
356       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
357     }
358   vlib_node_increment_counter (vm, esp_encrypt_node.index,
359                                ESP_ENCRYPT_ERROR_RX_PKTS,
360                                from_frame->n_vectors);
361
362 free_buffers_and_exit:
363   vlib_buffer_free (vm, recycle, vec_len(recycle));
364   vec_free(recycle);
365   return from_frame->n_vectors;
366 }
367
368
369 VLIB_REGISTER_NODE (esp_encrypt_node) = {
370   .function = esp_encrypt_node_fn,
371   .name = "esp-encrypt",
372   .vector_size = sizeof (u32),
373   .format_trace = format_esp_encrypt_trace,
374   .type = VLIB_NODE_TYPE_INTERNAL,
375
376   .n_errors = ARRAY_LEN(esp_encrypt_error_strings),
377   .error_strings = esp_encrypt_error_strings,
378
379   .n_next_nodes = ESP_ENCRYPT_N_NEXT,
380   .next_nodes = {
381 #define _(s,n) [ESP_ENCRYPT_NEXT_##s] = n,
382     foreach_esp_encrypt_next
383 #undef _
384   },
385 };
386