Driver level time-based src mac filter
[vpp.git] / src / plugins / mactime / mactime.c
1 /*
2  * mactime.c - time-based src mac address filtration
3  *
4  * Copyright (c) 2018 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/plugin/plugin.h>
20 #include <mactime/mactime.h>
21
22 #include <vlibapi/api.h>
23 #include <vlibmemory/api.h>
24 #include <vpp/app/version.h>
25
26 /* define message IDs */
27 #include <mactime/mactime_msg_enum.h>
28
29 /* define message structures */
30 #define vl_typedefs
31 #include <mactime/mactime_all_api_h.h>
32 #undef vl_typedefs
33
34 /* define generated endian-swappers */
35 #define vl_endianfun
36 #include <mactime/mactime_all_api_h.h>
37 #undef vl_endianfun
38
39 /* instantiate all the print functions we know about */
40 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
41 #define vl_printfun
42 #include <mactime/mactime_all_api_h.h>
43 #undef vl_printfun
44
45 /* Get the API version number */
46 #define vl_api_version(n,v) static u32 api_version=(v);
47 #include <mactime/mactime_all_api_h.h>
48 #undef vl_api_version
49
50 #define REPLY_MSG_ID_BASE mm->msg_id_base
51 #include <vlibapi/api_helper_macros.h>
52
53 mactime_main_t mactime_main;
54
55 /** \file time-base src-mac filter device-input feature arc implementation
56  */
57
58 /* List of message types that this plugin understands */
59
60 #define foreach_mactime_plugin_api_msg                  \
61 _(MACTIME_ENABLE_DISABLE, mactime_enable_disable)       \
62 _(MACTIME_ADD_DEL_RANGE, mactime_add_del_range)
63
64 static void
65 feature_init (mactime_main_t * mm)
66 {
67   if (mm->feature_initialized == 0)
68     {
69       /* Create the lookup table */
70       clib_bihash_init_8_8 (&mm->lookup_table, "mactime lookup table",
71                             mm->lookup_table_num_buckets,
72                             mm->lookup_table_memory_size);
73       clib_timebase_init (&mm->timebase, mm->timezone_offset,
74                           CLIB_TIMEBASE_DAYLIGHT_USA);
75       mm->allow_counters.name = "allow";
76       mm->allow_counters.stat_segment_name = "/mactime/allow";
77       mm->drop_counters.name = "drop";
78       mm->drop_counters.stat_segment_name = "/mactime/drop";
79       mm->feature_initialized = 1;
80     }
81 }
82
83 /** Action function shared between message handler and debug CLI
84 */
85 int
86 mactime_enable_disable (mactime_main_t * mm, u32 sw_if_index,
87                         int enable_disable)
88 {
89   vnet_sw_interface_t *sw;
90   int rv = 0;
91
92   feature_init (mm);
93
94   /* Utterly wrong? */
95   if (pool_is_free_index (mm->vnet_main->interface_main.sw_interfaces,
96                           sw_if_index))
97     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
98
99   /* Not a physical port? */
100   sw = vnet_get_sw_interface (mm->vnet_main, sw_if_index);
101   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
102     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
103
104   vnet_feature_enable_disable ("device-input", "mactime",
105                                sw_if_index, enable_disable, 0, 0);
106   return rv;
107 }
108
109 static clib_error_t *
110 mactime_enable_disable_command_fn (vlib_main_t * vm,
111                                    unformat_input_t * input,
112                                    vlib_cli_command_t * cmd)
113 {
114   mactime_main_t *mm = &mactime_main;
115   u32 sw_if_index = ~0;
116   int enable_disable = 1;
117
118   int rv;
119
120   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
121     {
122       if (unformat (input, "disable"))
123         enable_disable = 0;
124       else if (unformat (input, "%U", unformat_vnet_sw_interface,
125                          mm->vnet_main, &sw_if_index))
126         ;
127       else
128         break;
129     }
130
131   if (sw_if_index == ~0)
132     return clib_error_return (0, "Please specify an interface...");
133
134   rv = mactime_enable_disable (mm, sw_if_index, enable_disable);
135
136   switch (rv)
137     {
138     case 0:
139       break;
140
141     case VNET_API_ERROR_INVALID_SW_IF_INDEX:
142       return clib_error_return
143         (0, "Invalid interface, only works on physical ports");
144       break;
145
146     case VNET_API_ERROR_UNIMPLEMENTED:
147       return clib_error_return (0,
148                                 "Device driver doesn't support redirection");
149       break;
150
151     default:
152       return clib_error_return (0, "mactime_enable_disable returned %d", rv);
153     }
154   return 0;
155 }
156
157 /* *INDENT-OFF* */
158 VLIB_CLI_COMMAND (mactime_enable_disable_command, static) =
159 {
160   .path = "mactime enable-disable",
161   .short_help =
162   "mactime enable-disable <interface-name> [disable]",
163   .function = mactime_enable_disable_command_fn,
164 };
165 /* *INDENT-ON* */
166
167
168 /** Enable / disable time-base src mac filtration on an interface
169  */
170
171 static void vl_api_mactime_enable_disable_t_handler
172   (vl_api_mactime_enable_disable_t * mp)
173 {
174   vl_api_mactime_enable_disable_reply_t *rmp;
175   mactime_main_t *mm = &mactime_main;
176   int rv;
177
178   rv = mactime_enable_disable (mm, ntohl (mp->sw_if_index),
179                                (int) (mp->enable_disable));
180
181   REPLY_MACRO (VL_API_MACTIME_ENABLE_DISABLE_REPLY);
182 }
183
184 /** Add or delete static / dynamic accept/drop configuration for a src mac
185  */
186
187 static void vl_api_mactime_add_del_range_t_handler
188   (vl_api_mactime_add_del_range_t * mp)
189 {
190   mactime_main_t *mm = &mactime_main;
191   vl_api_mactime_add_del_range_reply_t *rmp;
192   mactime_device_t *dp;
193   clib_bihash_kv_8_8_t kv;
194   int found = 1;
195   clib_bihash_8_8_t *lut = &mm->lookup_table;
196   int i, rv = 0;
197
198   feature_init (mm);
199
200   memset (&kv, 0, sizeof (kv));
201   memcpy (&kv.key, mp->mac_address, sizeof (mp->mac_address));
202
203   /* See if we have a lookup table entry for this src mac address */
204   if (clib_bihash_search_8_8 (lut, &kv, &kv) < 0)
205     found = 0;
206
207   /* Add an entry? */
208   if (mp->is_add)
209     {
210       /* Create the device entry? */
211       if (found == 0)
212         {
213           pool_get (mm->devices, dp);
214           memset (dp, 0, sizeof (*dp));
215           vlib_validate_simple_counter (&mm->allow_counters,
216                                         dp - mm->devices);
217           vlib_zero_simple_counter (&mm->allow_counters, dp - mm->devices);
218           vlib_validate_simple_counter (&mm->drop_counters, dp - mm->devices);
219           vlib_zero_simple_counter (&mm->drop_counters, dp - mm->devices);
220           mp->device_name[ARRAY_LEN (mp->device_name) - 1] = 0;
221           dp->device_name = format (0, "%s", mp->device_name);
222           memcpy (dp->mac_address, mp->mac_address, sizeof (mp->mac_address));
223           for (i = 0; i < clib_net_to_host_u32 (mp->count); i++)
224             {
225               clib_timebase_range_t _r, *r = &_r;
226               r->start = mp->ranges[i].start;
227               r->end = mp->ranges[i].end;
228               vec_add1 (dp->ranges, r[0]);
229             }
230           /* If we found some time ranges */
231           if (i)
232             {
233               /* Set allow/drop based on msg flags */
234               if (mp->drop)
235                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_DROP;
236               if (mp->allow)
237                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW;
238             }
239           else
240             {
241               /* no ranges, it's a static allow/drop */
242               if (mp->drop)
243                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_DROP;
244               if (mp->allow)
245                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_ALLOW;
246             }
247
248           /* Add the hash table entry */
249           kv.value = dp - mm->devices;
250           clib_bihash_add_del_8_8 (lut, &kv, 1 /* is_add */ );
251         }
252       else                      /* add more ranges */
253         {
254           dp = pool_elt_at_index (mm->devices, kv.value);
255           for (i = 0; i < clib_net_to_host_u32 (mp->count); i++)
256             {
257               clib_timebase_range_t _r, *r = &_r;
258               r->start = mp->ranges[i].start;
259               r->end = mp->ranges[i].end;
260               vec_add1 (dp->ranges, r[0]);
261             }
262         }
263     }
264   else                          /* delete case */
265     {
266       if (found == 0)
267         {
268           rv = VNET_API_ERROR_NO_SUCH_ENTRY;
269           goto reply;
270         }
271
272       /* find the device entry */
273       dp = pool_elt_at_index (mm->devices, kv.value);
274
275       /* Remove it from the lookup table */
276       clib_bihash_add_del_8_8 (lut, &kv, 0 /* is_add */ );
277       vec_free (dp->ranges);
278       pool_put (mm->devices, dp);
279     }
280
281 reply:
282   REPLY_MACRO (VL_API_MACTIME_ADD_DEL_RANGE_REPLY);
283 }
284
285 /* Set up the API message handling tables */
286 static clib_error_t *
287 mactime_plugin_api_hookup (vlib_main_t * vm)
288 {
289   mactime_main_t *mm = &mactime_main;
290 #define _(N,n)                                                  \
291     vl_msg_api_set_handlers((VL_API_##N + mm->msg_id_base),     \
292                            #n,                                  \
293                            vl_api_##n##_t_handler,              \
294                            vl_noop_handler,                     \
295                            vl_api_##n##_t_endian,               \
296                            vl_api_##n##_t_print,                \
297                            sizeof(vl_api_##n##_t), 1);
298   foreach_mactime_plugin_api_msg;
299 #undef _
300
301   return 0;
302 }
303
304 #define vl_msg_name_crc_list
305 #include <mactime/mactime_all_api_h.h>
306 #undef vl_msg_name_crc_list
307
308 static void
309 setup_message_id_table (mactime_main_t * mm, api_main_t * am)
310 {
311 #define _(id,n,crc)   vl_msg_api_add_msg_name_crc (am, #n  #crc, id + mm->msg_id_base);
312   foreach_vl_msg_name_crc_mactime;
313 #undef _
314 }
315
316 static clib_error_t *
317 mactime_init (vlib_main_t * vm)
318 {
319   mactime_main_t *mm = &mactime_main;
320   clib_error_t *error = 0;
321   u8 *name;
322
323   mm->vlib_main = vm;
324   mm->vnet_main = vnet_get_main ();
325
326   name = format (0, "mactime_%08x%c", api_version, 0);
327
328   /* Ask for a correctly-sized block of API message decode slots */
329   mm->msg_id_base = vl_msg_api_get_msg_ids
330     ((char *) name, VL_MSG_FIRST_AVAILABLE);
331
332   error = mactime_plugin_api_hookup (vm);
333
334   /* Add our API messages to the global name_crc hash table */
335   setup_message_id_table (mm, &api_main);
336
337   vec_free (name);
338
339   mm->lookup_table_num_buckets = MACTIME_NUM_BUCKETS;
340   mm->lookup_table_memory_size = MACTIME_MEMORY_SIZE;
341   mm->timezone_offset = -5;     /* US EST / EDT */
342   return error;
343 }
344
345 VLIB_INIT_FUNCTION (mactime_init);
346
347 static clib_error_t *
348 mactime_config (vlib_main_t * vm, unformat_input_t * input)
349 {
350   mactime_main_t *mm = &mactime_main;
351
352   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
353     {
354       if (unformat (input, "lookup-table-buckets %u",
355                     &mm->lookup_table_num_buckets))
356         ;
357       else if (unformat (input, "lookup-table-memory %U",
358                          unformat_memory_size, &mm->lookup_table_memory_size))
359         ;
360       else if (unformat (input, "timezone_offset %d", &mm->timezone_offset))
361         ;
362       else
363         {
364           return clib_error_return (0, "unknown input '%U'",
365                                     format_unformat_error, input);
366         }
367     }
368   return 0;
369 }
370
371 VLIB_CONFIG_FUNCTION (mactime_config, "mactime");
372
373 /* *INDENT-OFF* */
374 VNET_FEATURE_INIT (mactime, static) =
375 {
376   .arc_name = "device-input",
377   .node_name = "mactime",
378   .runs_before = VNET_FEATURES ("ethernet-input"),
379 };
380 /* *INDENT-ON */
381
382 /* *INDENT-OFF* */
383 VLIB_PLUGIN_REGISTER () =
384 {
385   .version = VPP_BUILD_VER,
386   .description = "Time-based MAC source-address filter",
387 };
388 /* *INDENT-ON* */
389
390 static u8 *
391 format_mac_address (u8 * s, va_list * args)
392 {
393   u8 *a = va_arg (*args, u8 *);
394   return format (s, "%02x:%02x:%02x:%02x:%02x:%02x",
395                  a[0], a[1], a[2], a[3], a[4], a[5]);
396 }
397
398 static clib_error_t *
399 show_mactime_command_fn (vlib_main_t * vm,
400                          unformat_input_t * input, vlib_cli_command_t * cmd)
401 {
402   mactime_main_t *mm = &mactime_main;
403   mactime_device_t *dp;
404   u8 *macstring = 0;
405   char *status_string;
406   u32 *pool_indices = 0;
407   int verbose = 0;
408   int current_status = 99;
409   int i;
410   f64 now;
411   u64 allow, drop;
412
413   now = clib_timebase_now (&mm->timebase);
414
415   if (PREDICT_FALSE ((now - mm->sunday_midnight) > 86400.0 * 7.0))
416     mm->sunday_midnight = clib_timebase_find_sunday_midnight (now);
417
418   if (unformat (input, "verbose %d", &verbose))
419     ;
420
421   if (unformat (input, "verbose"))
422     verbose = 1;
423
424   if (verbose)
425     vlib_cli_output (vm, "Time now: %U", format_clib_timebase_time, now);
426
427   /* *INDENT-OFF* */
428   pool_foreach (dp, mm->devices,
429   ({
430     vec_add1 (pool_indices, dp - mm->devices);
431   }));
432   /* *INDENT-ON* */
433
434   vlib_cli_output (vm, "%-15s %20s %16s %10s %10s",
435                    "Device Name", "MAC address", "Current Status", "Allow",
436                    "Drop");
437
438   for (i = 0; i < vec_len (pool_indices); i++)
439     {
440       dp = pool_elt_at_index (mm->devices, pool_indices[i]);
441
442       /* Check dynamic ranges */
443       for (i = 0; i < vec_len (dp->ranges); i++)
444         {
445           clib_timebase_range_t *r = dp->ranges + i;
446           f64 start0, end0;
447
448           start0 = r->start + mm->sunday_midnight;
449           end0 = r->end + mm->sunday_midnight;
450           if (verbose > 1)
451             vlib_cli_output (vm, "  Range %d: %U - %U", i,
452                              format_clib_timebase_time, start0,
453                              format_clib_timebase_time, end0);
454
455           if (now >= start0 && now <= end0)
456             {
457               if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW)
458                 current_status = 3;
459               else
460                 current_status = 2;
461               if (verbose)
462                 {
463                   vlib_cli_output (vm, "  Time in range %d:", i);
464                   vlib_cli_output (vm, "     %U - %U",
465                                    format_clib_timebase_time, start0,
466                                    format_clib_timebase_time, end0);
467                 }
468               goto print;
469             }
470         }
471       if (verbose && i)
472         vlib_cli_output (vm, "  No range match.");
473       if (dp->flags & MACTIME_DEVICE_FLAG_STATIC_DROP)
474         current_status = 0;
475       if (dp->flags & MACTIME_DEVICE_FLAG_STATIC_ALLOW)
476         current_status = 1;
477       if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW)
478         current_status = 2;
479       if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_DROP)
480         current_status = 3;
481
482     print:
483       vec_reset_length (macstring);
484       macstring = format (0, "%U", format_mac_address, dp->mac_address);
485       switch (current_status)
486         {
487         case 0:
488           status_string = "static drop";
489           break;
490         case 1:
491           status_string = "static allow";
492           break;
493         case 2:
494           status_string = "dynamic drop";
495           break;
496         case 3:
497           status_string = "dynamic allow";
498           break;
499         default:
500           status_string = "code bug!";
501           break;
502         }
503       allow = vlib_get_simple_counter (&mm->allow_counters, dp - mm->devices);
504       drop = vlib_get_simple_counter (&mm->drop_counters, dp - mm->devices);
505       vlib_cli_output (vm, "%-15s %20s %16s %10lld %10lld",
506                        dp->device_name, macstring, status_string,
507                        allow, drop);
508     }
509
510   vec_free (macstring);
511   vec_free (pool_indices);
512
513   return 0;
514 }
515
516 /* *INDENT-OFF* */
517 VLIB_CLI_COMMAND (show_mactime_command, static) =
518 {
519   .path = "show mactime",
520   .short_help = "show mactime [verbose]",
521   .function = show_mactime_command_fn,
522 };
523 /* *INDENT-ON* */
524
525
526
527 /*
528  * fd.io coding-style-patch-verification: ON
529  *
530  * Local Variables:
531  * eval: (c-set-style "gnu")
532  * End:
533  */