ipsec: Allow SAs with NULL auth &crypto on IPSec interface
[vpp.git] / src / vnet / ipsec / ipsec_tun.c
1 /*
2  * ipsec_tun.h : IPSEC tunnel protection
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/ipsec/ipsec_tun.h>
19 #include <vnet/ipsec/ipsec_itf.h>
20 #include <vnet/ipsec/esp.h>
21 #include <vnet/udp/udp.h>
22 #include <vnet/adj/adj_delegate.h>
23 #include <vnet/adj/adj_midchain.h>
24 #include <vnet/teib/teib.h>
25
26 #define IPSEC_TUN_DEFAULT_HASH_NUM_BUCKETS (64 * 1024)
27 #define IPSEC_TUN_DEFAULT_HASH_MEMORY_SIZE 512 << 20
28
29 /**
30  * The logger
31  */
32 vlib_log_class_t ipsec_tun_protect_logger;
33
34 /**
35  * Pool of tunnel protection objects
36  */
37 ipsec_tun_protect_t *ipsec_tun_protect_pool;
38
39 /**
40  * Adj delegate registered type
41  */
42 static adj_delegate_type_t ipsec_tun_adj_delegate_type;
43
44 /**
45  * Adj index to TX SA mapping
46  */
47 index_t *ipsec_tun_protect_sa_by_adj_index;
48
49 const ip_address_t IP_ADDR_ALL_0 = IP_ADDRESS_V4_ALL_0S;
50
51 /**
52  * The DB of all added per-nh tunnel protectiond
53  */
54 typedef struct ipsec_tun_protect_itf_db_t_
55 {
56   /** A hash table key'd on IP (4 or 6) address */
57   uword *id_hash;
58   /** If the interface is P2P then there is only one protect
59    * object associated with the auto-adj for each NH proto */
60   index_t id_itp;
61 } ipsec_tun_protect_itf_db_t;
62
63 typedef struct ipsec_tun_protect_db_t_
64 {
65   /** Per-interface vector */
66   ipsec_tun_protect_itf_db_t *id_itf;
67 } ipsec_tun_protect_db_t;
68
69 static ipsec_tun_protect_db_t itp_db;
70
71 const static ipsec_tun_protect_itf_db_t IPSEC_TUN_PROTECT_DEFAULT_DB_ENTRY = {
72   .id_itp = INDEX_INVALID,
73 };
74
75 #define ITP_DBG(_itp, _fmt, _args...)                   \
76 {                                                       \
77   vlib_log_debug(ipsec_tun_protect_logger,              \
78                  "[%U]: " _fmt,                         \
79                  format_ipsec_tun_protect,              \
80                  _itp, ##_args);                        \
81 }
82
83 #define ITP_DBG2(_fmt, _args...)                        \
84 {                                                       \
85   vlib_log_debug(ipsec_tun_protect_logger,              \
86                  _fmt, ##_args);                        \
87 }
88
89 static u32 ipsec_tun_node_regs[N_AF];
90
91 void
92 ipsec_tun_register_nodes (ip_address_family_t af)
93 {
94   if (0 == ipsec_tun_node_regs[af]++)
95     {
96       if (AF_IP4 == af)
97         {
98           ipsec_register_udp_port (UDP_DST_PORT_ipsec);
99           ip4_register_protocol (IP_PROTOCOL_IPSEC_ESP,
100                                  ipsec4_tun_input_node.index);
101         }
102       else
103         ip6_register_protocol (IP_PROTOCOL_IPSEC_ESP,
104                                ipsec6_tun_input_node.index);
105     }
106 }
107
108 void
109 ipsec_tun_unregister_nodes (ip_address_family_t af)
110 {
111   ASSERT (0 != ipsec_tun_node_regs[af]);
112   if (0 == --ipsec_tun_node_regs[af])
113     {
114       if (AF_IP4 == af)
115         {
116           ipsec_unregister_udp_port (UDP_DST_PORT_ipsec);
117           ip4_unregister_protocol (IP_PROTOCOL_IPSEC_ESP);
118         }
119       else
120         ip6_unregister_protocol (IP_PROTOCOL_IPSEC_ESP);
121     }
122 }
123
124 static inline const ipsec_tun_protect_t *
125 ipsec_tun_protect_from_const_base (const adj_delegate_t * ad)
126 {
127   if (ad == NULL)
128     return (NULL);
129   return (pool_elt_at_index (ipsec_tun_protect_pool, ad->ad_index));
130 }
131
132 static u32
133 ipsec_tun_protect_get_adj_next (vnet_link_t linkt,
134                                 const ipsec_tun_protect_t * itp)
135 {
136   ipsec_main_t *im;
137   ipsec_sa_t *sa;
138   bool is_ip4;
139   u32 next;
140
141
142   if (itp->itp_flags & IPSEC_PROTECT_ITF)
143     is_ip4 = linkt == VNET_LINK_IP4;
144   else
145     is_ip4 = ip46_address_is_ip4 (&itp->itp_tun.src);
146
147   sa = ipsec_sa_get (itp->itp_out_sa);
148   im = &ipsec_main;
149
150   if ((sa->crypto_alg == IPSEC_CRYPTO_ALG_NONE &&
151        sa->integ_alg == IPSEC_INTEG_ALG_NONE) &&
152       !(itp->itp_flags & IPSEC_PROTECT_ITF))
153     next = (is_ip4 ?
154             im->esp4_no_crypto_tun_node_index :
155             im->esp6_no_crypto_tun_node_index);
156   else if (itp->itp_flags & IPSEC_PROTECT_L2)
157     next = (is_ip4 ?
158             im->esp4_encrypt_l2_tun_node_index :
159             im->esp6_encrypt_l2_tun_node_index);
160   else
161     next = (is_ip4 ?
162             im->esp4_encrypt_tun_node_index :
163             im->esp6_encrypt_tun_node_index);
164
165   return (next);
166 }
167
168 static void
169 ipsec_tun_protect_add_adj (adj_index_t ai, const ipsec_tun_protect_t * itp)
170 {
171   vec_validate_init_empty (ipsec_tun_protect_sa_by_adj_index, ai,
172                            INDEX_INVALID);
173
174   if (NULL == itp)
175     {
176       ipsec_tun_protect_sa_by_adj_index[ai] = INDEX_INVALID;
177       adj_nbr_midchain_reset_next_node (ai);
178     }
179   else
180     {
181       ipsec_tun_protect_sa_by_adj_index[ai] = itp->itp_out_sa;
182       adj_nbr_midchain_update_next_node
183         (ai, ipsec_tun_protect_get_adj_next (adj_get_link_type (ai), itp));
184     }
185 }
186
187 static index_t
188 ipsec_tun_protect_find (u32 sw_if_index, const ip_address_t * nh)
189 {
190   ipsec_tun_protect_itf_db_t *idi;
191   uword *p;
192
193   if (vec_len (itp_db.id_itf) <= sw_if_index)
194     return INDEX_INVALID;
195
196   if (vnet_sw_interface_is_p2p (vnet_get_main (), sw_if_index))
197     return (itp_db.id_itf[sw_if_index].id_itp);
198
199   idi = &itp_db.id_itf[sw_if_index];
200   p = hash_get_mem (idi->id_hash, nh);
201
202   if (NULL == p)
203     {
204       return INDEX_INVALID;
205     }
206   return (p[0]);
207 }
208
209 static void
210 ipsec_tun_protect_rx_db_add (ipsec_main_t * im,
211                              const ipsec_tun_protect_t * itp)
212 {
213   const ipsec_sa_t *sa;
214   u32 sai;
215
216   if (ip46_address_is_zero (&itp->itp_crypto.dst))
217     return;
218
219   /* *INDENT-OFF* */
220   FOR_EACH_IPSEC_PROTECT_INPUT_SAI(itp, sai,
221   ({
222       sa = ipsec_sa_get (sai);
223
224       ipsec_tun_lkup_result_t res = {
225         .tun_index = itp - ipsec_tun_protect_pool,
226         .sa_index = sai,
227       };
228
229       /*
230        * The key is formed from the tunnel's destination
231        * as the packet lookup is done from the packet's source
232        */
233       if (ip46_address_is_ip4 (&itp->itp_crypto.dst))
234         {
235           ipsec4_tunnel_kv_t key = {
236             .value = res,
237           };
238           clib_bihash_kv_8_8_t *bkey = (clib_bihash_kv_8_8_t*)&key;
239
240           ipsec4_tunnel_mk_key(&key, &itp->itp_crypto.dst.ip4,
241                                clib_host_to_net_u32 (sa->spi));
242
243           if (!im->tun4_protect_by_key.nbuckets)
244               clib_bihash_init_8_8 (&im->tun4_protect_by_key,
245                         "IPSec IPv4 tunnels",
246                         IPSEC_TUN_DEFAULT_HASH_NUM_BUCKETS,
247                         IPSEC_TUN_DEFAULT_HASH_MEMORY_SIZE);
248
249           clib_bihash_add_del_8_8 (&im->tun4_protect_by_key, bkey, 1);
250           ipsec_tun_register_nodes(AF_IP4);
251         }
252       else
253         {
254           ipsec6_tunnel_kv_t key = {
255             .key = {
256               .remote_ip = itp->itp_crypto.dst.ip6,
257               .spi = clib_host_to_net_u32 (sa->spi),
258             },
259             .value = res,
260           };
261           clib_bihash_kv_24_8_t *bkey = (clib_bihash_kv_24_8_t*)&key;
262
263           if (!im->tun4_protect_by_key.nbuckets)
264             clib_bihash_init_24_8 (&im->tun6_protect_by_key,
265                                    "IPSec IPv6 tunnels",
266                                    IPSEC_TUN_DEFAULT_HASH_NUM_BUCKETS,
267                                    IPSEC_TUN_DEFAULT_HASH_MEMORY_SIZE);
268           clib_bihash_add_del_24_8 (&im->tun6_protect_by_key, bkey, 1);
269           ipsec_tun_register_nodes(AF_IP6);
270         }
271   }))
272   /* *INDENT-ON* */
273 }
274
275 static adj_walk_rc_t
276 ipsec_tun_protect_adj_add (adj_index_t ai, void *arg)
277 {
278   ipsec_tun_protect_t *itp = arg;
279   adj_delegate_add (adj_get (ai), ipsec_tun_adj_delegate_type,
280                     itp - ipsec_tun_protect_pool);
281   ipsec_tun_protect_add_adj (ai, itp);
282
283   if (itp->itp_flags & IPSEC_PROTECT_ITF)
284     ipsec_itf_adj_stack (ai, itp->itp_out_sa);
285
286   return (ADJ_WALK_RC_CONTINUE);
287 }
288
289 static void
290 ipsec_tun_protect_tx_db_add (ipsec_tun_protect_t * itp)
291 {
292   /*
293    * add the delegate to the adj
294    */
295   ipsec_tun_protect_itf_db_t *idi;
296   fib_protocol_t nh_proto;
297   ip46_address_t nh;
298
299   vec_validate_init_empty (itp_db.id_itf,
300                            itp->itp_sw_if_index,
301                            IPSEC_TUN_PROTECT_DEFAULT_DB_ENTRY);
302
303   idi = &itp_db.id_itf[itp->itp_sw_if_index];
304
305   if (vnet_sw_interface_is_p2p (vnet_get_main (), itp->itp_sw_if_index))
306     {
307       if (INDEX_INVALID == idi->id_itp)
308         {
309           // ipsec_tun_protect_feature_set (itp, 1);
310         }
311       idi->id_itp = itp - ipsec_tun_protect_pool;
312
313       FOR_EACH_FIB_IP_PROTOCOL (nh_proto)
314         adj_nbr_walk (itp->itp_sw_if_index,
315                       nh_proto, ipsec_tun_protect_adj_add, itp);
316     }
317   else
318     {
319       if (NULL == idi->id_hash)
320         {
321           idi->id_hash =
322             hash_create_mem (0, sizeof (ip_address_t), sizeof (uword));
323           /*
324            * enable the encrypt feature for egress if this is the first addition
325            * on this interface
326            */
327           // ipsec_tun_protect_feature_set (itp, 1);
328         }
329
330       hash_set_mem (idi->id_hash, itp->itp_key, itp - ipsec_tun_protect_pool);
331
332       /*
333        * walk all the adjs with the same nh on this interface
334        * to associate them with this protection
335        */
336       nh_proto = ip_address_to_46 (itp->itp_key, &nh);
337
338       adj_nbr_walk_nh (itp->itp_sw_if_index,
339                        nh_proto, &nh, ipsec_tun_protect_adj_add, itp);
340
341       ipsec_tun_register_nodes (FIB_PROTOCOL_IP6 == nh_proto ?
342                                 AF_IP6 : AF_IP4);
343     }
344 }
345
346 static void
347 ipsec_tun_protect_rx_db_remove (ipsec_main_t * im,
348                                 const ipsec_tun_protect_t * itp)
349 {
350   const ipsec_sa_t *sa;
351
352   /* *INDENT-OFF* */
353   FOR_EACH_IPSEC_PROTECT_INPUT_SA(itp, sa,
354   ({
355     if (ip46_address_is_ip4 (&itp->itp_crypto.dst))
356       {
357           ipsec4_tunnel_kv_t key;
358           clib_bihash_kv_8_8_t res, *bkey = (clib_bihash_kv_8_8_t*)&key;
359
360           ipsec4_tunnel_mk_key(&key, &itp->itp_crypto.dst.ip4,
361                                clib_host_to_net_u32 (sa->spi));
362
363           if (!clib_bihash_search_8_8 (&im->tun4_protect_by_key, bkey, &res))
364             {
365               clib_bihash_add_del_8_8 (&im->tun4_protect_by_key, bkey, 0);
366               ipsec_tun_unregister_nodes(AF_IP4);
367             }
368       }
369     else
370       {
371         ipsec6_tunnel_kv_t key = {
372           .key = {
373             .remote_ip = itp->itp_crypto.dst.ip6,
374             .spi = clib_host_to_net_u32 (sa->spi),
375           },
376         };
377         clib_bihash_kv_24_8_t res, *bkey = (clib_bihash_kv_24_8_t*)&key;
378
379         if (!clib_bihash_search_24_8 (&im->tun6_protect_by_key, bkey, &res))
380           {
381             clib_bihash_add_del_24_8 (&im->tun6_protect_by_key, bkey, 0);
382             ipsec_tun_unregister_nodes(AF_IP6);
383           }
384       }
385   }));
386   /* *INDENT-ON* */
387 }
388
389 static adj_walk_rc_t
390 ipsec_tun_protect_adj_remove (adj_index_t ai, void *arg)
391 {
392   ipsec_tun_protect_t *itp = arg;
393
394   adj_delegate_remove (ai, ipsec_tun_adj_delegate_type);
395   ipsec_tun_protect_add_adj (ai, NULL);
396
397   if (itp->itp_flags & IPSEC_PROTECT_ITF)
398     ipsec_itf_adj_unstack (ai);
399
400   return (ADJ_WALK_RC_CONTINUE);
401 }
402
403 static void
404 ipsec_tun_protect_tx_db_remove (ipsec_tun_protect_t * itp)
405 {
406   ipsec_tun_protect_itf_db_t *idi;
407   fib_protocol_t nh_proto;
408   ip46_address_t nh;
409
410   nh_proto = ip_address_to_46 (itp->itp_key, &nh);
411   idi = &itp_db.id_itf[itp->itp_sw_if_index];
412
413   if (vnet_sw_interface_is_p2p (vnet_get_main (), itp->itp_sw_if_index))
414     {
415       // ipsec_tun_protect_feature_set (itp, 0);
416       idi->id_itp = INDEX_INVALID;
417
418       FOR_EACH_FIB_IP_PROTOCOL (nh_proto)
419         adj_nbr_walk (itp->itp_sw_if_index,
420                       nh_proto, ipsec_tun_protect_adj_remove, itp);
421     }
422   else
423     {
424       adj_nbr_walk_nh (itp->itp_sw_if_index,
425                        nh_proto, &nh, ipsec_tun_protect_adj_remove, itp);
426
427       hash_unset_mem (idi->id_hash, itp->itp_key);
428
429       if (0 == hash_elts (idi->id_hash))
430         {
431           // ipsec_tun_protect_feature_set (itp, 0);
432           hash_free (idi->id_hash);
433           idi->id_hash = NULL;
434         }
435       ipsec_tun_unregister_nodes (FIB_PROTOCOL_IP6 == nh_proto ?
436                                   AF_IP6 : AF_IP4);
437     }
438 }
439
440 static void
441 ipsec_tun_protect_set_crypto_addr (ipsec_tun_protect_t * itp)
442 {
443   ipsec_sa_t *sa;
444
445   /* *INDENT-OFF* */
446   FOR_EACH_IPSEC_PROTECT_INPUT_SA(itp, sa,
447   ({
448     if (ipsec_sa_is_set_IS_TUNNEL (sa))
449       {
450         itp->itp_crypto.src = sa->tunnel_dst_addr;
451         itp->itp_crypto.dst = sa->tunnel_src_addr;
452         if (!(itp->itp_flags & IPSEC_PROTECT_ITF))
453           {
454             ipsec_sa_set_IS_PROTECT (sa);
455             itp->itp_flags |= IPSEC_PROTECT_ENCAPED;
456           }
457       }
458     else
459       {
460         itp->itp_crypto.src = itp->itp_tun.src;
461         itp->itp_crypto.dst = itp->itp_tun.dst;
462         itp->itp_flags &= ~IPSEC_PROTECT_ENCAPED;
463       }
464   }));
465   /* *INDENT-ON* */
466 }
467
468 static void
469 ipsec_tun_protect_config (ipsec_main_t * im,
470                           ipsec_tun_protect_t * itp, u32 sa_out, u32 * sas_in)
471 {
472   index_t sai;
473   u32 ii;
474
475   itp->itp_n_sa_in = vec_len (sas_in);
476   for (ii = 0; ii < itp->itp_n_sa_in; ii++)
477     itp->itp_in_sas[ii] = sas_in[ii];
478   itp->itp_out_sa = sa_out;
479
480   ipsec_sa_lock (itp->itp_out_sa);
481
482   /* *INDENT-OFF* */
483   FOR_EACH_IPSEC_PROTECT_INPUT_SAI(itp, sai,
484   ({
485     ipsec_sa_lock(sai);
486   }));
487   ipsec_tun_protect_set_crypto_addr(itp);
488   /* *INDENT-ON* */
489
490   /*
491    * add to the DB against each SA
492    */
493   ipsec_tun_protect_rx_db_add (im, itp);
494   ipsec_tun_protect_tx_db_add (itp);
495
496   ITP_DBG (itp, "configured");
497 }
498
499 static void
500 ipsec_tun_protect_unconfig (ipsec_main_t * im, ipsec_tun_protect_t * itp)
501 {
502   ipsec_sa_t *sa;
503   index_t sai;
504
505   /* *INDENT-OFF* */
506   FOR_EACH_IPSEC_PROTECT_INPUT_SA(itp, sa,
507   ({
508     ipsec_sa_unset_IS_PROTECT (sa);
509   }));
510
511   ipsec_tun_protect_rx_db_remove (im, itp);
512   ipsec_tun_protect_tx_db_remove (itp);
513
514   ipsec_sa_unlock(itp->itp_out_sa);
515
516   FOR_EACH_IPSEC_PROTECT_INPUT_SAI(itp, sai,
517   ({
518     ipsec_sa_unlock(sai);
519   }));
520   /* *INDENT-ON* */
521   ITP_DBG (itp, "unconfigured");
522 }
523
524 int
525 ipsec_tun_protect_update_one (u32 sw_if_index,
526                               const ip_address_t * nh, u32 sa_out, u32 sa_in)
527 {
528   u32 *sas_in = NULL;
529   int rv;
530
531   vec_add1 (sas_in, sa_in);
532   rv = ipsec_tun_protect_update (sw_if_index, nh, sa_out, sas_in);
533
534   return (rv);
535 }
536
537 int
538 ipsec_tun_protect_update_out (u32 sw_if_index,
539                               const ip_address_t * nh, u32 sa_out)
540 {
541   u32 itpi, *sas_in, sai, *saip;
542   ipsec_tun_protect_t *itp;
543   ipsec_main_t *im;
544   int rv;
545
546   sas_in = NULL;
547   rv = 0;
548   im = &ipsec_main;
549
550   itpi = ipsec_tun_protect_find (sw_if_index, nh);
551
552   if (INDEX_INVALID == itpi)
553     {
554       return (VNET_API_ERROR_INVALID_INTERFACE);
555     }
556
557   itp = pool_elt_at_index (ipsec_tun_protect_pool, itpi);
558
559   /* *INDENT-OFF* */
560   FOR_EACH_IPSEC_PROTECT_INPUT_SAI (itp, sai,
561   ({
562     ipsec_sa_lock (sai);
563     vec_add1 (sas_in, sai);
564   }));
565   /* *INDENT-ON* */
566
567   sa_out = ipsec_sa_find_and_lock (sa_out);
568
569   if (~0 == sa_out)
570     {
571       rv = VNET_API_ERROR_INVALID_VALUE;
572       goto out;
573     }
574
575   ipsec_tun_protect_unconfig (im, itp);
576   ipsec_tun_protect_config (im, itp, sa_out, sas_in);
577
578   ipsec_sa_unlock (sa_out);
579   vec_foreach (saip, sas_in) ipsec_sa_unlock (*saip);
580
581 out:
582   vec_free (sas_in);
583   return (rv);
584 }
585
586 int
587 ipsec_tun_protect_update_in (u32 sw_if_index,
588                              const ip_address_t * nh, u32 sa_in)
589 {
590   u32 itpi, *sas_in, sa_out;
591   ipsec_tun_protect_t *itp;
592   ipsec_main_t *im;
593   int rv;
594
595   sas_in = NULL;
596   rv = 0;
597   im = &ipsec_main;
598   itpi = ipsec_tun_protect_find (sw_if_index, nh);
599
600   if (INDEX_INVALID == itpi)
601     {
602       return (VNET_API_ERROR_INVALID_INTERFACE);
603     }
604
605   sa_in = ipsec_sa_find_and_lock (sa_in);
606
607   if (~0 == sa_in)
608     {
609       rv = VNET_API_ERROR_INVALID_VALUE;
610       goto out;
611     }
612   vec_add1 (sas_in, sa_in);
613
614   itp = pool_elt_at_index (ipsec_tun_protect_pool, itpi);
615   sa_out = itp->itp_out_sa;
616
617   ipsec_sa_lock (sa_out);
618
619   ipsec_tun_protect_unconfig (im, itp);
620   ipsec_tun_protect_config (im, itp, sa_out, sas_in);
621
622   ipsec_sa_unlock (sa_out);
623   ipsec_sa_unlock (sa_in);
624 out:
625   vec_free (sas_in);
626   return (rv);
627 }
628
629 static void
630 ipsec_tun_protect_update_from_teib (ipsec_tun_protect_t * itp,
631                                     const teib_entry_t * ne)
632 {
633   if (NULL != ne)
634     {
635       const fib_prefix_t *pfx;
636
637       pfx = teib_entry_get_nh (ne);
638
639       ip46_address_copy (&itp->itp_tun.dst, &pfx->fp_addr);
640     }
641   else
642     ip46_address_reset (&itp->itp_tun.dst);
643 }
644
645 int
646 ipsec_tun_protect_update (u32 sw_if_index,
647                           const ip_address_t * nh, u32 sa_out, u32 * sas_in)
648 {
649   ipsec_tun_protect_t *itp;
650   u32 itpi, ii, *saip;
651   ipsec_main_t *im;
652   int rv;
653
654   ITP_DBG2 ("update: %U/%U",
655             format_vnet_sw_if_index_name, vnet_get_main (), sw_if_index,
656             format_ip_address, nh);
657
658   if (vec_len (sas_in) > ITP_MAX_N_SA_IN)
659     {
660       rv = VNET_API_ERROR_LIMIT_EXCEEDED;
661       goto out;
662     }
663
664   rv = 0;
665   im = &ipsec_main;
666   if (NULL == nh)
667     nh = &IP_ADDR_ALL_0;
668   itpi = ipsec_tun_protect_find (sw_if_index, nh);
669
670   vec_foreach_index (ii, sas_in)
671   {
672     sas_in[ii] = ipsec_sa_find_and_lock (sas_in[ii]);
673     if (~0 == sas_in[ii])
674       {
675         rv = VNET_API_ERROR_INVALID_VALUE;
676         goto out;
677       }
678   }
679
680   sa_out = ipsec_sa_find_and_lock (sa_out);
681
682   if (~0 == sa_out)
683     {
684       rv = VNET_API_ERROR_INVALID_VALUE;
685       goto out;
686     }
687
688   if (INDEX_INVALID == itpi)
689     {
690       vnet_device_class_t *dev_class;
691       vnet_hw_interface_t *hi;
692       vnet_main_t *vnm;
693       u8 is_l2;
694
695       vnm = vnet_get_main ();
696       hi = vnet_get_sup_hw_interface (vnm, sw_if_index);
697       dev_class = vnet_get_device_class (vnm, hi->dev_class_index);
698
699       if (NULL == dev_class->ip_tun_desc)
700         {
701           rv = VNET_API_ERROR_INVALID_SW_IF_INDEX;
702           goto out;
703         }
704
705       pool_get_zero (ipsec_tun_protect_pool, itp);
706
707       itp->itp_sw_if_index = sw_if_index;
708       itp->itp_ai = ADJ_INDEX_INVALID;
709
710       itp->itp_n_sa_in = vec_len (sas_in);
711       for (ii = 0; ii < itp->itp_n_sa_in; ii++)
712         itp->itp_in_sas[ii] = sas_in[ii];
713       itp->itp_out_sa = sa_out;
714
715       itp->itp_key = clib_mem_alloc (sizeof (*itp->itp_key));
716       ip_address_copy (itp->itp_key, nh);
717
718       rv = dev_class->ip_tun_desc (sw_if_index,
719                                    &itp->itp_tun.src,
720                                    &itp->itp_tun.dst, &is_l2);
721
722       if (rv)
723         goto out;
724
725       if (ip46_address_is_zero (&itp->itp_tun.src))
726         {
727           /* must be one of thos pesky ipsec interfaces that has no encap.
728            * the encap then MUST comefrom the tunnel mode SA.
729            */
730           ipsec_sa_t *sa;
731
732           sa = ipsec_sa_get (itp->itp_out_sa);
733
734           if (!ipsec_sa_is_set_IS_TUNNEL (sa))
735             {
736               rv = VNET_API_ERROR_INVALID_DST_ADDRESS;
737               goto out;
738             }
739
740           itp->itp_flags |= IPSEC_PROTECT_ITF;
741         }
742       else if (ip46_address_is_zero (&itp->itp_tun.dst))
743         {
744           /* tunnel has no destination address, presumably because it's p2mp
745              in which case we use the nh that this is protection for */
746           ipsec_tun_protect_update_from_teib
747             (itp, teib_entry_find (sw_if_index, nh));
748         }
749
750       if (is_l2)
751         itp->itp_flags |= IPSEC_PROTECT_L2;
752
753       /*
754        * add to the tunnel DB for ingress
755        *  - if the SA is in trasnport mode, then the packates will arrive
756        *    with the IP src,dst of the protected tunnel, in which case we can
757        *    simply strip the IP header and hand the payload to the protocol
758        *    appropriate input handler
759        *  - if the SA is in tunnel mode then there are two IP headers present
760        *    one for the crytpo tunnel endpoints (described in the SA) and one
761        *    for the tunnel endpoints. The outer IP headers in the srriving
762        *    packets will have the crypto endpoints. So the DB needs to contain
763        *    the crpto endpoint. Once the crypto header is stripped, revealing,
764        *    the tunnel-IP we have 2 choices:
765        *     1) do a tunnel lookup based on the revealed header
766        *     2) skip the tunnel lookup and assume that the packet matches the
767        *        one that is protected here.
768        *    If we did 1) then we would allow our peer to use the SA for tunnel
769        *    X to inject traffic onto tunnel Y, this is not good. If we do 2)
770        *    then we don't verify that the peer is indeed using SA for tunnel
771        *    X and addressing tunnel X. So we take a compromise, once the SA
772        *    matches to tunnel X we veriy that the inner IP matches the value
773        *    of the tunnel we are protecting, else it's dropped.
774        */
775       ipsec_tun_protect_config (im, itp, sa_out, sas_in);
776     }
777   else
778     {
779       /* updating SAs only */
780       itp = pool_elt_at_index (ipsec_tun_protect_pool, itpi);
781
782       ipsec_tun_protect_unconfig (im, itp);
783       ipsec_tun_protect_config (im, itp, sa_out, sas_in);
784     }
785
786   ipsec_sa_unlock (sa_out);
787   vec_foreach (saip, sas_in) ipsec_sa_unlock (*saip);
788   vec_free (sas_in);
789
790 out:
791   return (rv);
792 }
793
794 int
795 ipsec_tun_protect_del (u32 sw_if_index, const ip_address_t * nh)
796 {
797   ipsec_tun_protect_t *itp;
798   ipsec_main_t *im;
799   index_t itpi;
800
801   ITP_DBG2 ("delete: %U/%U",
802             format_vnet_sw_if_index_name, vnet_get_main (), sw_if_index,
803             format_ip_address, nh);
804
805   im = &ipsec_main;
806   if (NULL == nh)
807     nh = &IP_ADDR_ALL_0;
808
809   itpi = ipsec_tun_protect_find (sw_if_index, nh);
810
811   if (INDEX_INVALID == itpi)
812     return (VNET_API_ERROR_NO_SUCH_ENTRY);
813
814   itp = ipsec_tun_protect_get (itpi);
815   ipsec_tun_protect_unconfig (im, itp);
816
817   if (ADJ_INDEX_INVALID != itp->itp_ai)
818     adj_unlock (itp->itp_ai);
819
820   clib_mem_free (itp->itp_key);
821   pool_put (ipsec_tun_protect_pool, itp);
822
823   return (0);
824 }
825
826 void
827 ipsec_tun_protect_walk (ipsec_tun_protect_walk_cb_t fn, void *ctx)
828 {
829   index_t itpi;
830
831   /* *INDENT-OFF* */
832   pool_foreach_index(itpi, ipsec_tun_protect_pool,
833   ({
834     fn (itpi, ctx);
835   }));
836   /* *INDENT-ON* */
837 }
838
839 void
840 ipsec_tun_protect_walk_itf (u32 sw_if_index,
841                             ipsec_tun_protect_walk_cb_t fn, void *ctx)
842 {
843   ipsec_tun_protect_itf_db_t *idi;
844   ip_address_t *key;
845   index_t itpi;
846
847   if (vec_len (itp_db.id_itf) <= sw_if_index)
848     return;
849
850   idi = &itp_db.id_itf[sw_if_index];
851
852   /* *INDENT-OFF* */
853   hash_foreach(key, itpi, idi->id_hash,
854   ({
855     fn (itpi, ctx);
856   }));
857   /* *INDENT-ON* */
858   if (INDEX_INVALID != idi->id_itp)
859     fn (idi->id_itp, ctx);
860 }
861
862 static void
863 ipsec_tun_protect_adj_delegate_adj_deleted (adj_delegate_t * ad)
864 {
865   /* remove our delegate */
866   ipsec_tun_protect_add_adj (ad->ad_adj_index, NULL);
867   adj_delegate_remove (ad->ad_adj_index, ipsec_tun_adj_delegate_type);
868 }
869
870 static void
871 ipsec_tun_protect_adj_delegate_adj_modified (adj_delegate_t * ad)
872 {
873   ipsec_tun_protect_add_adj (ad->ad_adj_index,
874                              ipsec_tun_protect_get (ad->ad_index));
875 }
876
877 static void
878 ipsec_tun_protect_adj_delegate_adj_created (adj_index_t ai)
879 {
880   /* add our delegate if there is protection for this neighbour */
881   ip_address_t ip = IP_ADDRESS_V4_ALL_0S;
882   ip_adjacency_t *adj;
883   index_t itpi;
884
885   if (!adj_is_midchain (ai))
886     return;
887
888   adj = adj_get (ai);
889
890   ip_address_from_46 (&adj->sub_type.midchain.next_hop,
891                       adj->ia_nh_proto, &ip);
892
893   itpi = ipsec_tun_protect_find (adj->rewrite_header.sw_if_index, &ip);
894
895   if (INDEX_INVALID != itpi)
896     ipsec_tun_protect_adj_add (ai, ipsec_tun_protect_get (itpi));
897 }
898
899 static u8 *
900 ipsec_tun_protect_adj_delegate_format (const adj_delegate_t * aed, u8 * s)
901 {
902   const ipsec_tun_protect_t *itp;
903
904   itp = ipsec_tun_protect_from_const_base (aed);
905   s = format (s, "ipsec-tun-protect:\n%U", format_ipsec_tun_protect, itp);
906
907   return (s);
908 }
909
910 static void
911 ipsec_tun_teib_entry_added (const teib_entry_t * ne)
912 {
913   ipsec_tun_protect_t *itp;
914   index_t itpi;
915
916   itpi = ipsec_tun_protect_find (teib_entry_get_sw_if_index (ne),
917                                  teib_entry_get_peer (ne));
918
919   if (INDEX_INVALID == itpi)
920     return;
921
922   itp = ipsec_tun_protect_get (itpi);
923   ipsec_tun_protect_rx_db_remove (&ipsec_main, itp);
924   ipsec_tun_protect_update_from_teib (itp, ne);
925   ipsec_tun_protect_set_crypto_addr (itp);
926   ipsec_tun_protect_rx_db_add (&ipsec_main, itp);
927
928   ITP_DBG (itp, "teib-added");
929 }
930
931 static void
932 ipsec_tun_teib_entry_deleted (const teib_entry_t * ne)
933 {
934   ipsec_tun_protect_t *itp;
935   index_t itpi;
936
937   itpi = ipsec_tun_protect_find (teib_entry_get_sw_if_index (ne),
938                                  teib_entry_get_peer (ne));
939
940   if (INDEX_INVALID == itpi)
941     return;
942
943   itp = ipsec_tun_protect_get (itpi);
944   ipsec_tun_protect_rx_db_remove (&ipsec_main, itp);
945   ipsec_tun_protect_update_from_teib (itp, NULL);
946   ipsec_tun_protect_set_crypto_addr (itp);
947
948   ITP_DBG (itp, "teib-removed");
949 }
950
951 /**
952  * VFT registered with the adjacency delegate
953  */
954 const static adj_delegate_vft_t ipsec_tun_adj_delegate_vft = {
955   .adv_adj_deleted = ipsec_tun_protect_adj_delegate_adj_deleted,
956   .adv_adj_created = ipsec_tun_protect_adj_delegate_adj_created,
957   .adv_adj_modified = ipsec_tun_protect_adj_delegate_adj_modified,
958   .adv_format = ipsec_tun_protect_adj_delegate_format,
959 };
960
961 const static teib_vft_t ipsec_tun_teib_vft = {
962   .nv_added = ipsec_tun_teib_entry_added,
963   .nv_deleted = ipsec_tun_teib_entry_deleted,
964 };
965
966 void
967 ipsec_tun_table_init (ip_address_family_t af, uword table_size, u32 n_buckets)
968 {
969   ipsec_main_t *im;
970
971   im = &ipsec_main;
972
973   if (AF_IP4 == af)
974     clib_bihash_init_8_8 (&im->tun4_protect_by_key,
975                           "IPSec IPv4 tunnels", n_buckets, table_size);
976   else
977     clib_bihash_init_24_8 (&im->tun6_protect_by_key,
978                            "IPSec IPv6 tunnels", n_buckets, table_size);
979 }
980
981 clib_error_t *
982 ipsec_tunnel_protect_init (vlib_main_t * vm)
983 {
984   ipsec_main_t *im;
985
986   im = &ipsec_main;
987   clib_bihash_init_24_8 (&im->tun6_protect_by_key,
988                          "IPSec IPv6 tunnels",
989                          IPSEC_TUN_DEFAULT_HASH_NUM_BUCKETS,
990                          IPSEC_TUN_DEFAULT_HASH_MEMORY_SIZE);
991   clib_bihash_init_8_8 (&im->tun4_protect_by_key,
992                         "IPSec IPv4 tunnels",
993                         IPSEC_TUN_DEFAULT_HASH_NUM_BUCKETS,
994                         IPSEC_TUN_DEFAULT_HASH_MEMORY_SIZE);
995
996   /* set up feature nodes to drop outbound packets with no crypto alg set */
997   im->esp4_no_crypto_tun_node_index =
998     vlib_get_node_by_name (vm, (u8 *) "esp4-no-crypto")->index;
999   im->esp6_no_crypto_tun_node_index =
1000     vlib_get_node_by_name (vm, (u8 *) "esp6-no-crypto")->index;
1001   im->esp6_encrypt_l2_tun_node_index =
1002     vlib_get_node_by_name (vm, (u8 *) "esp6-encrypt-tun")->index;
1003   im->esp4_encrypt_l2_tun_node_index =
1004     vlib_get_node_by_name (vm, (u8 *) "esp4-encrypt-tun")->index;
1005
1006   ipsec_tun_adj_delegate_type =
1007     adj_delegate_register_new_type (&ipsec_tun_adj_delegate_vft);
1008
1009   ipsec_tun_protect_logger = vlib_log_register_class ("ipsec", "tun");
1010
1011   teib_register (&ipsec_tun_teib_vft);
1012
1013   return 0;
1014 }
1015
1016 VLIB_INIT_FUNCTION (ipsec_tunnel_protect_init);
1017
1018 static clib_error_t *
1019 ipsec_config (vlib_main_t * vm, unformat_input_t * input)
1020 {
1021   unformat_input_t sub_input;
1022
1023   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1024     {
1025       if (unformat (input, "ip4 %U", unformat_vlib_cli_sub_input, &sub_input))
1026         {
1027           uword table_size = ~0;
1028           u32 n_buckets = ~0;
1029
1030           while (unformat_check_input (&sub_input) != UNFORMAT_END_OF_INPUT)
1031             {
1032               if (unformat (&sub_input, "num-buckets %u", &n_buckets))
1033                 ;
1034               else
1035                 return clib_error_return (0, "unknown input `%U'",
1036                                           format_unformat_error, &sub_input);
1037             }
1038
1039           ipsec_tun_table_init (AF_IP4, table_size, n_buckets);
1040         }
1041       else if (unformat (input, "ip6 %U", unformat_vlib_cli_sub_input,
1042                          &sub_input))
1043         {
1044           uword table_size = ~0;
1045           u32 n_buckets = ~0;
1046
1047           while (unformat_check_input (&sub_input) != UNFORMAT_END_OF_INPUT)
1048             {
1049               if (unformat (&sub_input, "num-buckets %u", &n_buckets))
1050                 ;
1051               else
1052                 return clib_error_return (0, "unknown input `%U'",
1053                                           format_unformat_error, &sub_input);
1054             }
1055
1056           ipsec_tun_table_init (AF_IP6, table_size, n_buckets);
1057         }
1058       else
1059         return clib_error_return (0, "unknown input `%U'",
1060                                   format_unformat_error, input);
1061     }
1062
1063   return 0;
1064 }
1065
1066 VLIB_CONFIG_FUNCTION (ipsec_config, "ipsec");
1067
1068 /*
1069  * fd.io coding-style-patch-verification: ON
1070  *
1071  * Local Variables:
1072  * eval: (c-set-style "gnu")
1073  * End:
1074  */