hs-test: fixed timed out tests passing in the CI
[vpp.git] / src / plugins / nat / det44 / det44.c
1 /*
2  * det44.c - deterministic NAT
3  *
4  * Copyright (c) 2020 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  * @file
19  * @brief deterministic NAT (CGN)
20  */
21
22 #include <vnet/vnet.h>
23 #include <vnet/ip/ip.h>
24 #include <vnet/ip/ip4.h>
25 #include <vpp/app/version.h>
26 #include <vnet/plugin/plugin.h>
27
28 #include <nat/det44/det44.h>
29
30 det44_main_t det44_main;
31
32 VNET_FEATURE_INIT (ip4_det44_in2out, static) = {
33   .arc_name = "ip4-unicast",
34   .node_name = "det44-in2out",
35   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
36                                "ip4-sv-reassembly-feature"),
37 };
38 VNET_FEATURE_INIT (ip4_det44_out2in, static) = {
39   .arc_name = "ip4-unicast",
40   .node_name = "det44-out2in",
41   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
42                                "ip4-sv-reassembly-feature",
43                                "ip4-dhcp-client-detect"),
44 };
45 VLIB_PLUGIN_REGISTER () = {
46     .version = VPP_BUILD_VER,
47     .description = "Deterministic NAT (CGN)",
48 };
49
50 void
51 det44_add_del_addr_to_fib (ip4_address_t * addr, u8 p_len, u32 sw_if_index,
52                            int is_add)
53 {
54   det44_main_t *dm = &det44_main;
55   fib_prefix_t prefix = {
56     .fp_len = p_len,
57     .fp_proto = FIB_PROTOCOL_IP4,
58     .fp_addr = {
59                 .ip4.as_u32 = addr->as_u32,
60                 },
61   };
62   u32 fib_index = ip4_fib_table_get_index_for_sw_if_index (sw_if_index);
63
64   if (is_add)
65     {
66       fib_table_entry_update_one_path (fib_index,
67                                        &prefix,
68                                        dm->fib_src_low,
69                                        (FIB_ENTRY_FLAG_CONNECTED |
70                                         FIB_ENTRY_FLAG_LOCAL |
71                                         FIB_ENTRY_FLAG_EXCLUSIVE),
72                                        DPO_PROTO_IP4,
73                                        NULL,
74                                        sw_if_index,
75                                        ~0, 1, NULL, FIB_ROUTE_PATH_FLAG_NONE);
76     }
77   else
78     {
79       fib_table_entry_delete (fib_index, &prefix, dm->fib_src_low);
80     }
81 }
82
83 /**
84  * @brief Add/delete deterministic NAT mapping.
85  *
86  * Create bijective mapping of inside address to outside address and port range
87  * pairs, with the purpose of enabling deterministic NAT to reduce logging in
88  * CGN deployments.
89  *
90  * @param in_addr  Inside network address.
91  * @param in_plen  Inside network prefix length.
92  * @param out_addr Outside network address.
93  * @param out_plen Outside network prefix length.
94  * @param is_add   If 0 delete, otherwise add.
95  */
96 int
97 snat_det_add_map (ip4_address_t * in_addr, u8 in_plen,
98                   ip4_address_t * out_addr, u8 out_plen, int is_add)
99 {
100   static snat_det_session_t empty_snat_det_session = { 0 };
101   det44_main_t *dm = &det44_main;
102   ip4_address_t in_cmp, out_cmp;
103   det44_interface_t *i;
104   snat_det_map_t *mp;
105   u8 found = 0;
106
107   in_cmp.as_u32 = in_addr->as_u32 & ip4_main.fib_masks[in_plen];
108   out_cmp.as_u32 = out_addr->as_u32 & ip4_main.fib_masks[out_plen];
109   vec_foreach (mp, dm->det_maps)
110   {
111     /* Checking for overlapping addresses to be added here */
112     if (mp->in_addr.as_u32 == in_cmp.as_u32 &&
113         mp->in_plen == in_plen &&
114         mp->out_addr.as_u32 == out_cmp.as_u32 && mp->out_plen == out_plen)
115       {
116         found = 1;
117         break;
118       }
119   }
120
121   /* If found, don't add again */
122   if (found && is_add)
123     return VNET_API_ERROR_VALUE_EXIST;
124
125   /* If not found, don't delete */
126   if (!found && !is_add)
127     return VNET_API_ERROR_NO_SUCH_ENTRY;
128
129   if (is_add)
130     {
131       pool_get (dm->det_maps, mp);
132       clib_memset (mp, 0, sizeof (*mp));
133       mp->in_addr.as_u32 = in_cmp.as_u32;
134       mp->in_plen = in_plen;
135       mp->out_addr.as_u32 = out_cmp.as_u32;
136       mp->out_plen = out_plen;
137       mp->sharing_ratio = (1 << (32 - in_plen)) / (1 << (32 - out_plen));
138       mp->ports_per_host = (65535 - 1023) / mp->sharing_ratio;
139
140       vec_validate_init_empty (mp->sessions,
141                                DET44_SES_PER_USER * (1 << (32 - in_plen)) -
142                                1, empty_snat_det_session);
143     }
144   else
145     {
146       vec_free (mp->sessions);
147       vec_del1 (dm->det_maps, mp - dm->det_maps);
148     }
149
150   /* Add/del external address range to FIB */
151   pool_foreach (i, dm->interfaces)  {
152     if (det44_interface_is_inside(i))
153       continue;
154     det44_add_del_addr_to_fib(out_addr, out_plen, i->sw_if_index, is_add);
155     goto out;
156   }
157 out:
158   return 0;
159 }
160
161 int
162 det44_set_timeouts (nat_timeouts_t * timeouts)
163 {
164   det44_main_t *dm = &det44_main;
165   if (timeouts->udp)
166     dm->timeouts.udp = timeouts->udp;
167   if (timeouts->tcp.established)
168     dm->timeouts.tcp.established = timeouts->tcp.established;
169   if (timeouts->tcp.transitory)
170     dm->timeouts.tcp.transitory = timeouts->tcp.transitory;
171   if (timeouts->icmp)
172     dm->timeouts.icmp = timeouts->icmp;
173   return 0;
174 }
175
176 nat_timeouts_t
177 det44_get_timeouts ()
178 {
179   det44_main_t *dm = &det44_main;
180   return dm->timeouts;
181 }
182
183 void
184 det44_reset_timeouts ()
185 {
186   det44_main_t *dm = &det44_main;
187   nat_reset_timeouts (&dm->timeouts);
188 }
189
190 int
191 det44_interface_add_del (u32 sw_if_index, u8 is_inside, int is_del)
192 {
193   det44_main_t *dm = &det44_main;
194   det44_interface_t *tmp, *i = 0;
195   const char *feature_name;
196   int rv;
197
198   // TODO: if plugin is not enabled do not register nodes on interfaces
199   // rather make a structure and when enable call is used
200   // then register nodes
201
202   pool_foreach (tmp, dm->interfaces)  {
203     if (tmp->sw_if_index == sw_if_index)
204       {
205         i = tmp;
206         goto out;
207       }
208   }
209 out:
210
211   feature_name = is_inside ? "det44-in2out" : "det44-out2in";
212
213   if (is_del)
214     {
215       if (!i)
216         {
217           det44_log_err ("det44 is not enabled on this interface");
218           return VNET_API_ERROR_INVALID_VALUE;
219         }
220
221       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
222       if (rv)
223         return rv;
224
225       rv = vnet_feature_enable_disable ("ip4-unicast", feature_name,
226                                         sw_if_index, 1, 0, 0);
227       if (rv)
228         return rv;
229
230       pool_put (dm->interfaces, i);
231     }
232   else
233     {
234       if (i)
235         {
236           det44_log_err ("det44 is already enabled on this interface");
237           return VNET_API_ERROR_INVALID_VALUE;
238         }
239
240       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
241       if (rv)
242         return rv;
243
244       rv = vnet_feature_enable_disable ("ip4-unicast", feature_name,
245                                         sw_if_index, 1, 0, 0);
246       if (rv)
247         return rv;
248
249       pool_get (dm->interfaces, i);
250       clib_memset (i, 0, sizeof (*i));
251
252       i->sw_if_index = sw_if_index;
253
254       if (is_inside)
255         i->flags |= DET44_INTERFACE_FLAG_IS_INSIDE;
256       else
257         i->flags |= DET44_INTERFACE_FLAG_IS_OUTSIDE;
258     }
259
260   if (!is_inside)
261     {
262       u32 fib_index = fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4,
263                                                            sw_if_index);
264       // add/del outside interface fib to registry
265       u8 found = 0;
266       det44_fib_t *outside_fib;
267       vec_foreach (outside_fib, dm->outside_fibs)
268         {
269           if (outside_fib->fib_index == fib_index)
270             {
271               if (!is_del)
272                 {
273                   outside_fib->refcount++;
274                 }
275               else
276                 {
277                   outside_fib->refcount--;
278                   if (!outside_fib->refcount)
279                     {
280                       vec_del1 (dm->outside_fibs,
281                                 outside_fib - dm->outside_fibs);
282                     }
283                 }
284               found = 1;
285               break;
286             }
287         }
288       if (!is_del && !found)
289         {
290           vec_add2 (dm->outside_fibs, outside_fib, 1);
291           outside_fib->fib_index = fib_index;
292           outside_fib->refcount = 1;
293         }
294       // add/del outside address to FIB
295       snat_det_map_t *mp;
296       pool_foreach (mp, dm->det_maps)  {
297         det44_add_del_addr_to_fib(&mp->out_addr,
298                                   mp->out_plen, sw_if_index, !is_del);
299       }
300     }
301   return 0;
302 }
303
304 /**
305  * @brief The 'det44-expire-walk' process's main loop.
306  *
307  * Check expire time for active sessions.
308  */
309 static uword
310 det44_expire_walk_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
311                       vlib_frame_t * f)
312 {
313   det44_main_t *dm = &det44_main;
314   snat_det_session_t *ses;
315   snat_det_map_t *mp;
316
317   while (1)
318     {
319       vlib_process_wait_for_event_or_clock (vm, 10.0);
320       vlib_process_get_events (vm, NULL);
321       u32 now = (u32) vlib_time_now (vm);
322
323       if (!plugin_enabled ())
324         {
325           continue;
326         }
327
328       pool_foreach (mp, dm->det_maps)
329         {
330           vec_foreach (ses, mp->sessions)
331             {
332               // close expired sessions
333               if (ses->in_port && (ses->expire < now))
334                 {
335                   snat_det_ses_close (mp, ses);
336                 }
337             }
338         }
339     }
340   return 0;
341 }
342
343 void
344 det44_create_expire_walk_process ()
345 {
346   det44_main_t *dm = &det44_main;
347
348   if (dm->expire_walk_node_index)
349     return;
350
351   dm->expire_walk_node_index = vlib_process_create (vlib_get_main (),
352                                                     "det44-expire-walk",
353                                                     det44_expire_walk_fn,
354                                                     16 /* stack_bytes */ );
355 }
356
357 int
358 det44_plugin_enable (det44_config_t c)
359 {
360   det44_main_t *dm = &det44_main;
361
362   if (plugin_enabled () == 1)
363     {
364       det44_log_err ("plugin already enabled!");
365       return 1;
366     }
367
368   det44_log_err ("inside %u, outside %u", c.inside_vrf_id, c.outside_vrf_id);
369
370   dm->outside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
371                                                              c.outside_vrf_id,
372                                                              dm->fib_src_hi);
373   dm->inside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
374                                                             c.inside_vrf_id,
375                                                             dm->fib_src_hi);
376
377   dm->mss_clamping = 0;
378   dm->config = c;
379   dm->enabled = 1;
380
381   det44_create_expire_walk_process ();
382   return 0;
383 }
384
385 int
386 det44_plugin_disable ()
387 {
388   det44_main_t *dm = &det44_main;
389   det44_interface_t *i, *interfaces;
390   snat_det_map_t *mp;
391   int rv = 0;
392
393   if (plugin_enabled () == 0)
394     {
395       det44_log_err ("plugin already disabled!");
396       return 1;
397     }
398
399   dm->enabled = 0;
400
401   // DET44 cleanup (order dependent)
402   // 1) remove interfaces (det44_interface_add_del) removes map ranges from fib
403   // 2) free sessions
404   // 3) free maps
405
406   interfaces = vec_dup (dm->interfaces);
407   vec_foreach (i, interfaces)
408   {
409     vnet_main_t *vnm = vnet_get_main ();
410
411     if (i->flags & DET44_INTERFACE_FLAG_IS_INSIDE)
412       {
413         rv = det44_interface_add_del (i->sw_if_index, i->flags, 1);
414         if (rv)
415           {
416             det44_log_err ("inside interface %U del failed",
417                            unformat_vnet_sw_interface, vnm, i->sw_if_index);
418           }
419       }
420
421     if (i->flags & DET44_INTERFACE_FLAG_IS_OUTSIDE)
422       {
423         rv = det44_interface_add_del (i->sw_if_index, i->flags, 1);
424         if (rv)
425           {
426             det44_log_err ("outside interface %U del failed",
427                            unformat_vnet_sw_interface, vnm, i->sw_if_index);
428           }
429
430       }
431   }
432   vec_free (interfaces);
433
434   pool_foreach (mp, dm->det_maps)
435    {
436     vec_free (mp->sessions);
437   }
438
439   det44_reset_timeouts ();
440
441   pool_free (dm->interfaces);
442   pool_free (dm->det_maps);
443
444   return rv;
445 }
446
447 static void
448 det44_update_outside_fib (ip4_main_t * im,
449                           uword opaque,
450                           u32 sw_if_index, u32 new_fib_index,
451                           u32 old_fib_index)
452 {
453   det44_main_t *dm = &det44_main;
454
455   det44_fib_t *outside_fib;
456   det44_interface_t *i;
457
458   u8 is_add = 1;
459   u8 match = 0;
460
461   if (plugin_enabled () == 0)
462     return;
463
464   if (new_fib_index == old_fib_index)
465     return;
466
467   if (!vec_len (dm->outside_fibs))
468     return;
469
470   pool_foreach (i, dm->interfaces)
471      {
472       if (i->sw_if_index == sw_if_index)
473         {
474           if (!(det44_interface_is_outside (i)))
475             return;
476           match = 1;
477         }
478     }
479
480   if (!match)
481     return;
482
483   vec_foreach (outside_fib, dm->outside_fibs)
484   {
485     if (outside_fib->fib_index == old_fib_index)
486       {
487         outside_fib->refcount--;
488         if (!outside_fib->refcount)
489           vec_del1 (dm->outside_fibs, outside_fib - dm->outside_fibs);
490         break;
491       }
492   }
493
494   vec_foreach (outside_fib, dm->outside_fibs)
495   {
496     if (outside_fib->fib_index == new_fib_index)
497       {
498         outside_fib->refcount++;
499         is_add = 0;
500         break;
501       }
502   }
503
504   if (is_add)
505     {
506       vec_add2 (dm->outside_fibs, outside_fib, 1);
507       outside_fib->refcount = 1;
508       outside_fib->fib_index = new_fib_index;
509     }
510 }
511
512 static clib_error_t *
513 det44_init (vlib_main_t * vm)
514 {
515   det44_main_t *dm = &det44_main;
516   ip4_table_bind_callback_t cb;
517   vlib_node_t *node;
518
519   clib_memset (dm, 0, sizeof (*dm));
520
521   dm->ip4_main = &ip4_main;
522   dm->log_class = vlib_log_register_class ("det44", 0);
523
524   node = vlib_get_node_by_name (vm, (u8 *) "det44-in2out");
525   dm->in2out_node_index = node->index;
526   node = vlib_get_node_by_name (vm, (u8 *) "det44-out2in");
527   dm->out2in_node_index = node->index;
528
529   dm->fib_src_hi = fib_source_allocate ("det44-hi",
530                                         FIB_SOURCE_PRIORITY_HI,
531                                         FIB_SOURCE_BH_SIMPLE);
532   dm->fib_src_low = fib_source_allocate ("det44-low",
533                                          FIB_SOURCE_PRIORITY_LOW,
534                                          FIB_SOURCE_BH_SIMPLE);
535
536   cb.function = det44_update_outside_fib;
537   cb.function_opaque = 0;
538   vec_add1 (dm->ip4_main->table_bind_callbacks, cb);
539
540   det44_reset_timeouts ();
541   return det44_api_hookup (vm);
542 }
543
544 VLIB_INIT_FUNCTION (det44_init);
545
546 u8 *
547 format_det44_session_state (u8 * s, va_list * args)
548 {
549   u32 i = va_arg (*args, u32);
550   u8 *t = 0;
551
552   switch (i)
553     {
554 #define _(v, N, str) case DET44_SESSION_##N: t = (u8 *) str; break;
555       foreach_det44_session_state
556 #undef _
557     default:
558       t = format (t, "unknown");
559     }
560   s = format (s, "%s", t);
561   return s;
562 }
563
564 u8 *
565 format_det_map_ses (u8 * s, va_list * args)
566 {
567   snat_det_map_t *det_map = va_arg (*args, snat_det_map_t *);
568   ip4_address_t in_addr, out_addr;
569   u32 in_offset, out_offset;
570   snat_det_session_t *ses = va_arg (*args, snat_det_session_t *);
571   u32 *i = va_arg (*args, u32 *);
572
573   u32 user_index = *i / DET44_SES_PER_USER;
574   in_addr.as_u32 =
575     clib_host_to_net_u32 (clib_net_to_host_u32 (det_map->in_addr.as_u32) +
576                           user_index);
577   in_offset =
578     clib_net_to_host_u32 (in_addr.as_u32) -
579     clib_net_to_host_u32 (det_map->in_addr.as_u32);
580   out_offset = in_offset / det_map->sharing_ratio;
581   out_addr.as_u32 =
582     clib_host_to_net_u32 (clib_net_to_host_u32 (det_map->out_addr.as_u32) +
583                           out_offset);
584   s =
585     format (s,
586             "in %U:%d out %U:%d external host %U:%d state: %U expire: %d\n",
587             format_ip4_address, &in_addr, clib_net_to_host_u16 (ses->in_port),
588             format_ip4_address, &out_addr,
589             clib_net_to_host_u16 (ses->out.out_port), format_ip4_address,
590             &ses->out.ext_host_addr,
591             clib_net_to_host_u16 (ses->out.ext_host_port),
592             format_det44_session_state, ses->state, ses->expire);
593
594   return s;
595 }
596
597 /*
598  * fd.io coding-style-patch-verification: ON
599  *
600  * Local Variables:
601  * eval: (c-set-style "gnu")
602  * End:
603  */