2feb0570a3154fb9605f2f6fcaa346ef84866584
[vpp.git] / src / plugins / wireguard / wireguard_output_tun.c
1 /*
2  * Copyright (c) 2020 Doc.ai and/or its affiliates.
3  * Copyright (c) 2020 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <vlib/vlib.h>
18 #include <vnet/vnet.h>
19 #include <vppinfra/error.h>
20
21 #include <wireguard/wireguard.h>
22 #include <wireguard/wireguard_send.h>
23
24 #define foreach_wg_output_error                                         \
25  _(NONE, "No error")                                                    \
26  _(PEER, "Peer error")                                                  \
27  _(KEYPAIR, "Keypair error")                                            \
28  _(TOO_BIG, "packet too big")                                           \
29
30 typedef enum
31 {
32 #define _(sym,str) WG_OUTPUT_ERROR_##sym,
33   foreach_wg_output_error
34 #undef _
35     WG_OUTPUT_N_ERROR,
36 } wg_output_error_t;
37
38 static char *wg_output_error_strings[] = {
39 #define _(sym,string) string,
40   foreach_wg_output_error
41 #undef _
42 };
43
44 typedef enum
45 {
46   WG_OUTPUT_NEXT_ERROR,
47   WG_OUTPUT_NEXT_HANDOFF,
48   WG_OUTPUT_NEXT_INTERFACE_OUTPUT,
49   WG_OUTPUT_N_NEXT,
50 } wg_output_next_t;
51
52 typedef struct
53 {
54   index_t peer;
55   u8 header[sizeof (ip6_udp_header_t)];
56   u8 is_ip4;
57 } wg_output_tun_trace_t;
58
59 u8 *
60 format_ip4_udp_header (u8 * s, va_list * args)
61 {
62   ip4_udp_header_t *hdr4 = va_arg (*args, ip4_udp_header_t *);
63
64   s = format (s, "%U:$U", format_ip4_header, &hdr4->ip4, format_udp_header,
65               &hdr4->udp);
66   return (s);
67 }
68
69 u8 *
70 format_ip6_udp_header (u8 *s, va_list *args)
71 {
72   ip6_udp_header_t *hdr6 = va_arg (*args, ip6_udp_header_t *);
73
74   s = format (s, "%U:$U", format_ip6_header, &hdr6->ip6, format_udp_header,
75               &hdr6->udp);
76   return (s);
77 }
78
79 /* packet trace format function */
80 static u8 *
81 format_wg_output_tun_trace (u8 * s, va_list * args)
82 {
83   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
84   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
85
86   wg_output_tun_trace_t *t = va_arg (*args, wg_output_tun_trace_t *);
87
88   s = format (s, "peer: %d\n", t->peer);
89   s = format (s, "  Encrypted packet: ");
90
91   s = t->is_ip4 ? format (s, "%U", format_ip4_udp_header, t->header) :
92                   format (s, "%U", format_ip6_udp_header, t->header);
93   return s;
94 }
95
96 static_always_inline void
97 wg_output_process_ops (vlib_main_t *vm, vlib_node_runtime_t *node,
98                        vnet_crypto_op_t *ops, vlib_buffer_t *b[], u16 *nexts,
99                        u16 drop_next)
100 {
101   u32 n_fail, n_ops = vec_len (ops);
102   vnet_crypto_op_t *op = ops;
103
104   if (n_ops == 0)
105     return;
106
107   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
108
109   while (n_fail)
110     {
111       ASSERT (op - ops < n_ops);
112
113       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
114         {
115           u32 bi = op->user_data;
116           b[bi]->error = node->errors[WG_OUTPUT_ERROR_KEYPAIR];
117           nexts[bi] = drop_next;
118           n_fail--;
119         }
120       op++;
121     }
122 }
123
124 /* is_ip4 - inner header flag */
125 always_inline uword
126 wg_output_tun_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
127                       vlib_frame_t *frame, u8 is_ip4)
128 {
129   wg_main_t *wmp = &wg_main;
130   wg_per_thread_data_t *ptd =
131     vec_elt_at_index (wmp->per_thread_data, vm->thread_index);
132   u32 *from = vlib_frame_vector_args (frame);
133   u32 n_left_from = frame->n_vectors;
134   ip4_udp_wg_header_t *hdr4_out = NULL;
135   ip6_udp_wg_header_t *hdr6_out = NULL;
136   message_data_t *message_data_wg = NULL;
137   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
138   vnet_crypto_op_t **crypto_ops = &ptd->crypto_ops;
139   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
140   vlib_buffer_t *sync_bufs[VLIB_FRAME_SIZE];
141   u32 thread_index = vm->thread_index;
142   u16 n_sync = 0;
143   u16 drop_next = WG_OUTPUT_NEXT_ERROR;
144
145   vlib_get_buffers (vm, from, bufs, n_left_from);
146   vec_reset_length (ptd->crypto_ops);
147
148   wg_peer_t *peer = NULL;
149   u32 adj_index = 0;
150   u32 last_adj_index = ~0;
151   index_t peeri = INDEX_INVALID;
152
153   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
154
155   while (n_left_from > 0)
156     {
157       u8 iph_offset = 0;
158       u8 is_ip4_out = 1;
159       u8 *plain_data;
160       u16 plain_data_len;
161
162       if (n_left_from > 2)
163         {
164           u8 *p;
165           vlib_prefetch_buffer_header (b[2], LOAD);
166           p = vlib_buffer_get_current (b[1]);
167           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
168           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
169                          LOAD);
170         }
171
172       next[0] = WG_OUTPUT_NEXT_ERROR;
173
174       adj_index = vnet_buffer (b[0])->ip.adj_index[VLIB_TX];
175
176       if (PREDICT_FALSE (last_adj_index != adj_index))
177         {
178           peeri = wg_peer_get_by_adj_index (adj_index);
179           peer = wg_peer_get (peeri);
180         }
181
182       if (!peer || wg_peer_is_dead (peer))
183         {
184           b[0]->error = node->errors[WG_OUTPUT_ERROR_PEER];
185           goto out;
186         }
187       if (PREDICT_FALSE (~0 == peer->output_thread_index))
188         {
189           /* this is the first packet to use this peer, claim the peer
190            * for this thread.
191            */
192           clib_atomic_cmp_and_swap (&peer->output_thread_index, ~0,
193                                     wg_peer_assign_thread (thread_index));
194         }
195
196       if (PREDICT_TRUE (thread_index != peer->output_thread_index))
197         {
198           next[0] = WG_OUTPUT_NEXT_HANDOFF;
199           goto next;
200         }
201
202       if (PREDICT_FALSE (!peer->remote.r_current))
203         {
204           wg_send_handshake_from_mt (peeri, false);
205           b[0]->error = node->errors[WG_OUTPUT_ERROR_KEYPAIR];
206           goto out;
207         }
208
209       is_ip4_out = ip46_address_is_ip4 (&peer->src.addr);
210       if (is_ip4_out)
211         {
212           hdr4_out = vlib_buffer_get_current (b[0]);
213           message_data_wg = &hdr4_out->wg;
214         }
215       else
216         {
217           hdr6_out = vlib_buffer_get_current (b[0]);
218           message_data_wg = &hdr6_out->wg;
219         }
220
221       iph_offset = vnet_buffer (b[0])->ip.save_rewrite_length;
222       plain_data = vlib_buffer_get_current (b[0]) + iph_offset;
223       plain_data_len = vlib_buffer_length_in_chain (vm, b[0]) - iph_offset;
224       u8 *iv_data = b[0]->pre_data;
225
226       size_t encrypted_packet_len = message_data_len (plain_data_len);
227
228       /*
229        * Ensure there is enough space to write the encrypted data
230        * into the packet
231        */
232       if (PREDICT_FALSE (encrypted_packet_len >= WG_DEFAULT_DATA_SIZE) ||
233           PREDICT_FALSE ((b[0]->current_data + encrypted_packet_len) >=
234                          vlib_buffer_get_default_data_size (vm)))
235         {
236           b[0]->error = node->errors[WG_OUTPUT_ERROR_TOO_BIG];
237           goto out;
238         }
239
240       if (PREDICT_FALSE (last_adj_index != adj_index))
241         {
242           wg_timers_any_authenticated_packet_sent_opt (peer, time);
243           wg_timers_data_sent_opt (peer, time);
244           wg_timers_any_authenticated_packet_traversal (peer);
245           last_adj_index = adj_index;
246         }
247
248       enum noise_state_crypt state;
249
250       state = noise_sync_remote_encrypt (
251         vm, crypto_ops, &peer->remote, &message_data_wg->receiver_index,
252         &message_data_wg->counter, plain_data, plain_data_len, plain_data,
253         n_sync, iv_data, time);
254
255       if (PREDICT_FALSE (state == SC_KEEP_KEY_FRESH))
256         {
257           wg_send_handshake_from_mt (peeri, false);
258         }
259       else if (PREDICT_FALSE (state == SC_FAILED))
260         {
261           // TODO: Maybe wrong
262           wg_send_handshake_from_mt (peeri, false);
263           wg_peer_update_flags (peeri, WG_PEER_ESTABLISHED, false);
264           goto out;
265         }
266
267       /* Here we are sure that can send packet to next node */
268       next[0] = WG_OUTPUT_NEXT_INTERFACE_OUTPUT;
269
270       if (is_ip4_out)
271         {
272           hdr4_out->wg.header.type = MESSAGE_DATA;
273           hdr4_out->udp.length = clib_host_to_net_u16 (encrypted_packet_len +
274                                                        sizeof (udp_header_t));
275           b[0]->current_length =
276             (encrypted_packet_len + sizeof (ip4_udp_header_t));
277           ip4_header_set_len_w_chksum (
278             &hdr4_out->ip4, clib_host_to_net_u16 (b[0]->current_length));
279         }
280       else
281         {
282           hdr6_out->wg.header.type = MESSAGE_DATA;
283           hdr6_out->udp.length = clib_host_to_net_u16 (encrypted_packet_len +
284                                                        sizeof (udp_header_t));
285           b[0]->current_length =
286             (encrypted_packet_len + sizeof (ip6_udp_header_t));
287           hdr6_out->ip6.payload_length =
288             clib_host_to_net_u16 (b[0]->current_length);
289         }
290
291     out:
292       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
293                          && (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
294         {
295           wg_output_tun_trace_t *t =
296             vlib_add_trace (vm, node, b[0], sizeof (*t));
297
298           t->peer = peeri;
299           t->is_ip4 = is_ip4_out;
300           if (hdr4_out)
301             clib_memcpy (t->header, hdr4_out, sizeof (ip4_udp_header_t));
302           else if (hdr6_out)
303             clib_memcpy (t->header, hdr6_out, sizeof (ip6_udp_header_t));
304         }
305
306     next:
307       sync_bufs[n_sync] = b[0];
308       n_sync += 1;
309       n_left_from -= 1;
310       next += 1;
311       b += 1;
312     }
313
314   /* wg-output-process-ops */
315   wg_output_process_ops (vm, node, ptd->crypto_ops, sync_bufs, nexts,
316                          drop_next);
317
318   vlib_buffer_enqueue_to_next (vm, node, from, nexts, n_sync);
319   return frame->n_vectors;
320 }
321
322 VLIB_NODE_FN (wg4_output_tun_node)
323 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
324 {
325   return wg_output_tun_inline (vm, node, frame, /* is_ip4 */ 1);
326 }
327
328 VLIB_NODE_FN (wg6_output_tun_node)
329 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
330 {
331   return wg_output_tun_inline (vm, node, frame, /* is_ip4 */ 0);
332 }
333
334 /* *INDENT-OFF* */
335 VLIB_REGISTER_NODE (wg4_output_tun_node) =
336 {
337   .name = "wg4-output-tun",
338   .vector_size = sizeof (u32),
339   .format_trace = format_wg_output_tun_trace,
340   .type = VLIB_NODE_TYPE_INTERNAL,
341   .n_errors = ARRAY_LEN (wg_output_error_strings),
342   .error_strings = wg_output_error_strings,
343   .n_next_nodes = WG_OUTPUT_N_NEXT,
344   .next_nodes = {
345         [WG_OUTPUT_NEXT_HANDOFF] = "wg4-output-tun-handoff",
346         [WG_OUTPUT_NEXT_INTERFACE_OUTPUT] = "adj-midchain-tx",
347         [WG_OUTPUT_NEXT_ERROR] = "error-drop",
348   },
349 };
350
351 VLIB_REGISTER_NODE (wg6_output_tun_node) =
352 {
353   .name = "wg6-output-tun",
354   .vector_size = sizeof (u32),
355   .format_trace = format_wg_output_tun_trace,
356   .type = VLIB_NODE_TYPE_INTERNAL,
357   .n_errors = ARRAY_LEN (wg_output_error_strings),
358   .error_strings = wg_output_error_strings,
359   .n_next_nodes = WG_OUTPUT_N_NEXT,
360   .next_nodes = {
361         [WG_OUTPUT_NEXT_HANDOFF] = "wg6-output-tun-handoff",
362         [WG_OUTPUT_NEXT_INTERFACE_OUTPUT] = "adj-midchain-tx",
363         [WG_OUTPUT_NEXT_ERROR] = "error-drop",
364   },
365 };
366 /* *INDENT-ON* */
367
368 /*
369  * fd.io coding-style-patch-verification: ON
370  *
371  * Local Variables:
372  * eval: (c-set-style "gnu")
373  * End:
374  */