ea99e375ea01afde72441038a2a0a7630012be8b
[vpp.git] / src / plugins / ikev2 / ikev2.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <vlib/vlib.h>
17 #include <vlib/unix/plugin.h>
18 #include <vlibmemory/api.h>
19 #include <vpp/app/version.h>
20 #include <vnet/vnet.h>
21 #include <vnet/pg/pg.h>
22 #include <vppinfra/error.h>
23 #include <vppinfra/random.h>
24 #include <vnet/udp/udp.h>
25 #include <vnet/ipsec/ipsec.h>
26 #include <vnet/ipsec/ipsec_tun.h>
27 #include <vnet/ipip/ipip.h>
28 #include <plugins/ikev2/ikev2.h>
29 #include <plugins/ikev2/ikev2_priv.h>
30 #include <openssl/sha.h>
31
32 ikev2_main_t ikev2_main;
33
34 static int ikev2_delete_tunnel_interface (vnet_main_t * vnm,
35                                           ikev2_sa_t * sa,
36                                           ikev2_child_sa_t * child);
37
38 #define ikev2_set_state(sa, v) do { \
39     (sa)->state = v; \
40     ikev2_elog_sa_state("ispi %lx SA state changed to " #v, sa->ispi); \
41   } while(0);
42
43 typedef struct
44 {
45   u32 next_index;
46   u32 sw_if_index;
47 } ikev2_trace_t;
48
49 static u8 *
50 format_ikev2_trace (u8 * s, va_list * args)
51 {
52   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
53   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
54   ikev2_trace_t *t = va_arg (*args, ikev2_trace_t *);
55
56   s = format (s, "ikev2: sw_if_index %d, next index %d",
57               t->sw_if_index, t->next_index);
58   return s;
59 }
60
61 static vlib_node_registration_t ikev2_node;
62
63 #define foreach_ikev2_error \
64 _(PROCESSED, "IKEv2 packets processed") \
65 _(IKE_SA_INIT_RETRANSMIT, "IKE_SA_INIT retransmit ") \
66 _(IKE_SA_INIT_IGNORE, "IKE_SA_INIT ignore (IKE SA already auth)") \
67 _(IKE_REQ_RETRANSMIT, "IKE request retransmit") \
68 _(IKE_REQ_IGNORE, "IKE request ignore (old msgid)") \
69 _(NOT_IKEV2, "Non IKEv2 packets received")
70
71 typedef enum
72 {
73 #define _(sym,str) IKEV2_ERROR_##sym,
74   foreach_ikev2_error
75 #undef _
76     IKEV2_N_ERROR,
77 } ikev2_error_t;
78
79 static char *ikev2_error_strings[] = {
80 #define _(sym,string) string,
81   foreach_ikev2_error
82 #undef _
83 };
84
85 typedef enum
86 {
87   IKEV2_NEXT_IP4_LOOKUP,
88   IKEV2_NEXT_ERROR_DROP,
89   IKEV2_N_NEXT,
90 } ikev2_next_t;
91
92 static ikev2_sa_transform_t *
93 ikev2_find_transform_data (ikev2_sa_transform_t * t)
94 {
95   ikev2_main_t *km = &ikev2_main;
96   ikev2_sa_transform_t *td;
97
98   vec_foreach (td, km->supported_transforms)
99   {
100     if (td->type != t->type)
101       continue;
102
103     if (td->transform_id != t->transform_id)
104       continue;
105
106     if (td->type == IKEV2_TRANSFORM_TYPE_ENCR)
107       {
108         if (vec_len (t->attrs) != 4 || t->attrs[0] != 0x80
109             || t->attrs[1] != 14)
110           continue;
111
112         if (((t->attrs[2] << 8 | t->attrs[3]) / 8) != td->key_len)
113           continue;
114       }
115     return td;
116   }
117   return 0;
118 }
119
120 static ikev2_sa_proposal_t *
121 ikev2_select_proposal (ikev2_sa_proposal_t * proposals,
122                        ikev2_protocol_id_t prot_id)
123 {
124   ikev2_sa_proposal_t *rv = 0;
125   ikev2_sa_proposal_t *proposal;
126   ikev2_sa_transform_t *transform, *new_t;
127   u8 mandatory_bitmap, optional_bitmap;
128
129   if (prot_id == IKEV2_PROTOCOL_IKE)
130     {
131       mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_ENCR) |
132         (1 << IKEV2_TRANSFORM_TYPE_PRF) |
133         (1 << IKEV2_TRANSFORM_TYPE_INTEG) | (1 << IKEV2_TRANSFORM_TYPE_DH);
134       optional_bitmap = mandatory_bitmap;
135     }
136   else if (prot_id == IKEV2_PROTOCOL_ESP)
137     {
138       mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_ENCR) |
139         (1 << IKEV2_TRANSFORM_TYPE_ESN);
140       optional_bitmap = mandatory_bitmap |
141         (1 << IKEV2_TRANSFORM_TYPE_INTEG) | (1 << IKEV2_TRANSFORM_TYPE_DH);
142     }
143   else if (prot_id == IKEV2_PROTOCOL_AH)
144     {
145       mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_INTEG) |
146         (1 << IKEV2_TRANSFORM_TYPE_ESN);
147       optional_bitmap = mandatory_bitmap | (1 << IKEV2_TRANSFORM_TYPE_DH);
148     }
149   else
150     return 0;
151
152   vec_add2 (rv, proposal, 1);
153
154   vec_foreach (proposal, proposals)
155   {
156     u8 bitmap = 0;
157     if (proposal->protocol_id != prot_id)
158       continue;
159
160     vec_foreach (transform, proposal->transforms)
161     {
162       if ((1 << transform->type) & bitmap)
163         continue;
164
165       if (ikev2_find_transform_data (transform))
166         {
167           bitmap |= 1 << transform->type;
168           vec_add2 (rv->transforms, new_t, 1);
169           clib_memcpy_fast (new_t, transform, sizeof (*new_t));
170           new_t->attrs = vec_dup (transform->attrs);
171         }
172     }
173
174     if ((bitmap & mandatory_bitmap) == mandatory_bitmap &&
175         (bitmap & ~optional_bitmap) == 0)
176       {
177         rv->proposal_num = proposal->proposal_num;
178         rv->protocol_id = proposal->protocol_id;
179         RAND_bytes ((u8 *) & rv->spi, sizeof (rv->spi));
180         goto done;
181       }
182     else
183       {
184         vec_free (rv->transforms);
185       }
186   }
187
188   vec_free (rv);
189 done:
190   return rv;
191 }
192
193 ikev2_sa_transform_t *
194 ikev2_sa_get_td_for_type (ikev2_sa_proposal_t * p,
195                           ikev2_transform_type_t type)
196 {
197   ikev2_sa_transform_t *t;
198
199   if (!p)
200     return 0;
201
202   vec_foreach (t, p->transforms)
203   {
204     if (t->type == type)
205       return ikev2_find_transform_data (t);
206   }
207   return 0;
208 }
209
210 ikev2_child_sa_t *
211 ikev2_sa_get_child (ikev2_sa_t * sa, u32 spi, ikev2_protocol_id_t prot_id,
212                     int by_initiator)
213 {
214   ikev2_child_sa_t *c;
215   vec_foreach (c, sa->childs)
216   {
217     ikev2_sa_proposal_t *proposal =
218       by_initiator ? &c->i_proposals[0] : &c->r_proposals[0];
219     if (proposal && proposal->spi == spi && proposal->protocol_id == prot_id)
220       return c;
221   }
222
223   return 0;
224 }
225
226 void
227 ikev2_sa_free_proposal_vector (ikev2_sa_proposal_t ** v)
228 {
229   ikev2_sa_proposal_t *p;
230   ikev2_sa_transform_t *t;
231
232   if (!*v)
233     return;
234
235   vec_foreach (p, *v)
236   {
237     vec_foreach (t, p->transforms)
238     {
239       vec_free (t->attrs);
240     }
241     vec_free (p->transforms);
242   }
243   vec_free (*v);
244 };
245
246 static void
247 ikev2_sa_free_child_sa (ikev2_child_sa_t * c)
248 {
249   ikev2_sa_free_proposal_vector (&c->r_proposals);
250   ikev2_sa_free_proposal_vector (&c->i_proposals);
251   vec_free (c->sk_ai);
252   vec_free (c->sk_ar);
253   vec_free (c->sk_ei);
254   vec_free (c->sk_er);
255   vec_free (c->tsi);
256   vec_free (c->tsr);
257 }
258
259 static void
260 ikev2_sa_free_all_child_sa (ikev2_child_sa_t ** childs)
261 {
262   ikev2_child_sa_t *c;
263   vec_foreach (c, *childs) ikev2_sa_free_child_sa (c);
264
265   vec_free (*childs);
266 }
267
268 static void
269 ikev2_sa_del_child_sa (ikev2_sa_t * sa, ikev2_child_sa_t * child)
270 {
271   ikev2_sa_free_child_sa (child);
272   vec_del1 (sa->childs, child - sa->childs);
273 }
274
275 static void
276 ikev2_sa_free_all_vec (ikev2_sa_t * sa)
277 {
278   vec_free (sa->i_nonce);
279   vec_free (sa->i_dh_data);
280   vec_free (sa->dh_shared_key);
281   vec_free (sa->dh_private_key);
282
283   ikev2_sa_free_proposal_vector (&sa->r_proposals);
284   ikev2_sa_free_proposal_vector (&sa->i_proposals);
285
286   vec_free (sa->sk_d);
287   vec_free (sa->sk_ai);
288   vec_free (sa->sk_ar);
289   vec_free (sa->sk_ei);
290   vec_free (sa->sk_er);
291   vec_free (sa->sk_pi);
292   vec_free (sa->sk_pr);
293
294   vec_free (sa->i_id.data);
295   vec_free (sa->i_auth.data);
296   vec_free (sa->r_id.data);
297   vec_free (sa->r_auth.data);
298   if (sa->r_auth.key)
299     EVP_PKEY_free (sa->r_auth.key);
300
301   vec_free (sa->del);
302
303   ikev2_sa_free_all_child_sa (&sa->childs);
304 }
305
306 static void
307 ikev2_delete_sa (ikev2_sa_t * sa)
308 {
309   ikev2_main_t *km = &ikev2_main;
310   u32 thread_index = vlib_get_thread_index ();
311   uword *p;
312
313   ikev2_sa_free_all_vec (sa);
314
315   p = hash_get (km->per_thread_data[thread_index].sa_by_rspi, sa->rspi);
316   if (p)
317     {
318       hash_unset (km->per_thread_data[thread_index].sa_by_rspi, sa->rspi);
319       pool_put (km->per_thread_data[thread_index].sas, sa);
320     }
321 }
322
323 static void
324 ikev2_generate_sa_init_data (ikev2_sa_t * sa)
325 {
326   ikev2_sa_transform_t *t = 0, *t2;
327   ikev2_main_t *km = &ikev2_main;
328
329   if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE)
330     {
331       return;
332     }
333
334   /* check if received DH group is on our list of supported groups */
335   vec_foreach (t2, km->supported_transforms)
336   {
337     if (t2->type == IKEV2_TRANSFORM_TYPE_DH && sa->dh_group == t2->dh_type)
338       {
339         t = t2;
340         break;
341       }
342   }
343
344   if (!t)
345     {
346       sa->dh_group = IKEV2_TRANSFORM_DH_TYPE_NONE;
347       return;
348     }
349
350   if (sa->is_initiator)
351     {
352       /* generate rspi */
353       RAND_bytes ((u8 *) & sa->ispi, 8);
354
355       /* generate nonce */
356       sa->i_nonce = vec_new (u8, IKEV2_NONCE_SIZE);
357       RAND_bytes ((u8 *) sa->i_nonce, IKEV2_NONCE_SIZE);
358     }
359   else
360     {
361       /* generate rspi */
362       RAND_bytes ((u8 *) & sa->rspi, 8);
363
364       /* generate nonce */
365       sa->r_nonce = vec_new (u8, IKEV2_NONCE_SIZE);
366       RAND_bytes ((u8 *) sa->r_nonce, IKEV2_NONCE_SIZE);
367     }
368
369   /* generate dh keys */
370   ikev2_generate_dh (sa, t);
371
372 }
373
374 static void
375 ikev2_complete_sa_data (ikev2_sa_t * sa, ikev2_sa_t * sai)
376 {
377   ikev2_sa_transform_t *t = 0, *t2;
378   ikev2_main_t *km = &ikev2_main;
379
380
381   /*move some data to the new SA */
382 #define _(A) ({void* __tmp__ = (A); (A) = 0; __tmp__;})
383   sa->i_nonce = _(sai->i_nonce);
384   sa->i_dh_data = _(sai->i_dh_data);
385   sa->dh_private_key = _(sai->dh_private_key);
386   sa->iaddr.as_u32 = sai->iaddr.as_u32;
387   sa->raddr.as_u32 = sai->raddr.as_u32;
388   sa->is_initiator = sai->is_initiator;
389   sa->i_id.type = sai->i_id.type;
390   sa->profile_index = sai->profile_index;
391   sa->is_profile_index_set = sai->is_profile_index_set;
392   sa->tun_itf = sai->tun_itf;
393   sa->is_tun_itf_set = sai->is_tun_itf_set;
394   sa->i_id.data = _(sai->i_id.data);
395   sa->i_auth.method = sai->i_auth.method;
396   sa->i_auth.hex = sai->i_auth.hex;
397   sa->i_auth.data = _(sai->i_auth.data);
398   sa->i_auth.key = _(sai->i_auth.key);
399   sa->last_sa_init_req_packet_data = _(sai->last_sa_init_req_packet_data);
400   sa->childs = _(sai->childs);
401   sa->udp_encap = sai->udp_encap;
402   sa->dst_port = sai->dst_port;
403 #undef _
404
405
406   if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE)
407     {
408       return;
409     }
410
411   /* check if received DH group is on our list of supported groups */
412   vec_foreach (t2, km->supported_transforms)
413   {
414     if (t2->type == IKEV2_TRANSFORM_TYPE_DH && sa->dh_group == t2->dh_type)
415       {
416         t = t2;
417         break;
418       }
419   }
420
421   if (!t)
422     {
423       sa->dh_group = IKEV2_TRANSFORM_DH_TYPE_NONE;
424       return;
425     }
426
427
428   /* generate dh keys */
429   ikev2_complete_dh (sa, t);
430
431 }
432
433 static void
434 ikev2_calc_keys (ikev2_sa_t * sa)
435 {
436   u8 *tmp;
437   /* calculate SKEYSEED = prf(Ni | Nr, g^ir) */
438   u8 *skeyseed = 0;
439   u8 *s = 0;
440   u16 integ_key_len = 0;
441   ikev2_sa_transform_t *tr_encr, *tr_prf, *tr_integ;
442   tr_encr =
443     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR);
444   tr_prf =
445     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF);
446   tr_integ =
447     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG);
448
449   if (tr_integ)
450     integ_key_len = tr_integ->key_len;
451
452   vec_append (s, sa->i_nonce);
453   vec_append (s, sa->r_nonce);
454   skeyseed = ikev2_calc_prf (tr_prf, s, sa->dh_shared_key);
455
456   /* Calculate S = Ni | Nr | SPIi | SPIr */
457   u64 *spi;
458   vec_add2 (s, tmp, 2 * sizeof (*spi));
459   spi = (u64 *) tmp;
460   spi[0] = clib_host_to_net_u64 (sa->ispi);
461   spi[1] = clib_host_to_net_u64 (sa->rspi);
462
463   /* calculate PRFplus */
464   u8 *keymat;
465   int len = tr_prf->key_trunc + /* SK_d */
466     integ_key_len * 2 +         /* SK_ai, SK_ar */
467     tr_encr->key_len * 2 +      /* SK_ei, SK_er */
468     tr_prf->key_len * 2;        /* SK_pi, SK_pr */
469
470   keymat = ikev2_calc_prfplus (tr_prf, skeyseed, s, len);
471   vec_free (skeyseed);
472   vec_free (s);
473
474   int pos = 0;
475
476   /* SK_d */
477   sa->sk_d = vec_new (u8, tr_prf->key_trunc);
478   clib_memcpy_fast (sa->sk_d, keymat + pos, tr_prf->key_trunc);
479   pos += tr_prf->key_trunc;
480
481   if (integ_key_len)
482     {
483       /* SK_ai */
484       sa->sk_ai = vec_new (u8, integ_key_len);
485       clib_memcpy_fast (sa->sk_ai, keymat + pos, integ_key_len);
486       pos += integ_key_len;
487
488       /* SK_ar */
489       sa->sk_ar = vec_new (u8, integ_key_len);
490       clib_memcpy_fast (sa->sk_ar, keymat + pos, integ_key_len);
491       pos += integ_key_len;
492     }
493
494   /* SK_ei */
495   sa->sk_ei = vec_new (u8, tr_encr->key_len);
496   clib_memcpy_fast (sa->sk_ei, keymat + pos, tr_encr->key_len);
497   pos += tr_encr->key_len;
498
499   /* SK_er */
500   sa->sk_er = vec_new (u8, tr_encr->key_len);
501   clib_memcpy_fast (sa->sk_er, keymat + pos, tr_encr->key_len);
502   pos += tr_encr->key_len;
503
504   /* SK_pi */
505   sa->sk_pi = vec_new (u8, tr_prf->key_len);
506   clib_memcpy_fast (sa->sk_pi, keymat + pos, tr_prf->key_len);
507   pos += tr_prf->key_len;
508
509   /* SK_pr */
510   sa->sk_pr = vec_new (u8, tr_prf->key_len);
511   clib_memcpy_fast (sa->sk_pr, keymat + pos, tr_prf->key_len);
512   pos += tr_prf->key_len;
513
514   vec_free (keymat);
515 }
516
517 static void
518 ikev2_calc_child_keys (ikev2_sa_t * sa, ikev2_child_sa_t * child)
519 {
520   u8 *s = 0;
521   u16 integ_key_len = 0;
522   u8 salt_len = 0;
523
524   ikev2_sa_transform_t *tr_prf, *ctr_encr, *ctr_integ;
525   tr_prf =
526     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF);
527   ctr_encr =
528     ikev2_sa_get_td_for_type (child->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR);
529   ctr_integ =
530     ikev2_sa_get_td_for_type (child->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG);
531
532   if (ctr_integ)
533     integ_key_len = ctr_integ->key_len;
534   else
535     salt_len = sizeof (u32);
536
537   vec_append (s, sa->i_nonce);
538   vec_append (s, sa->r_nonce);
539   /* calculate PRFplus */
540   u8 *keymat;
541   int len = ctr_encr->key_len * 2 + integ_key_len * 2 + salt_len * 2;
542
543   keymat = ikev2_calc_prfplus (tr_prf, sa->sk_d, s, len);
544
545   int pos = 0;
546
547   /* SK_ei */
548   child->sk_ei = vec_new (u8, ctr_encr->key_len);
549   clib_memcpy_fast (child->sk_ei, keymat + pos, ctr_encr->key_len);
550   pos += ctr_encr->key_len;
551
552   if (ctr_integ)
553     {
554       /* SK_ai */
555       child->sk_ai = vec_new (u8, ctr_integ->key_len);
556       clib_memcpy_fast (child->sk_ai, keymat + pos, ctr_integ->key_len);
557       pos += ctr_integ->key_len;
558     }
559   else
560     {
561       clib_memcpy (&child->salt_ei, keymat + pos, salt_len);
562       pos += salt_len;
563     }
564
565   /* SK_er */
566   child->sk_er = vec_new (u8, ctr_encr->key_len);
567   clib_memcpy_fast (child->sk_er, keymat + pos, ctr_encr->key_len);
568   pos += ctr_encr->key_len;
569
570   if (ctr_integ)
571     {
572       /* SK_ar */
573       child->sk_ar = vec_new (u8, integ_key_len);
574       clib_memcpy_fast (child->sk_ar, keymat + pos, integ_key_len);
575       pos += integ_key_len;
576     }
577   else
578     {
579       clib_memcpy (&child->salt_er, keymat + pos, salt_len);
580       pos += salt_len;
581     }
582
583   ASSERT (pos == len);
584
585   vec_free (keymat);
586 }
587
588 static void
589 ikev2_process_sa_init_req (vlib_main_t * vm, ikev2_sa_t * sa,
590                            ike_header_t * ike)
591 {
592   int p = 0;
593   u32 len = clib_net_to_host_u32 (ike->length);
594   u8 payload = ike->nextpayload;
595
596   ikev2_elog_exchange ("ispi %lx rspi %lx IKE_INIT request received "
597                        "from %d.%d.%d.%d",
598                        clib_net_to_host_u64 (ike->ispi),
599                        clib_net_to_host_u64 (ike->rspi), sa->iaddr.as_u32);
600
601   sa->ispi = clib_net_to_host_u64 (ike->ispi);
602
603   /* store whole IKE payload - needed for PSK auth */
604   vec_free (sa->last_sa_init_req_packet_data);
605   vec_add (sa->last_sa_init_req_packet_data, ike, len);
606
607   while (p < len && payload != IKEV2_PAYLOAD_NONE)
608     {
609       ike_payload_header_t *ikep = (ike_payload_header_t *) & ike->payload[p];
610       u32 plen = clib_net_to_host_u16 (ikep->length);
611
612       if (plen < sizeof (ike_payload_header_t))
613         return;
614
615       if (payload == IKEV2_PAYLOAD_SA)
616         {
617           ikev2_sa_free_proposal_vector (&sa->i_proposals);
618           sa->i_proposals = ikev2_parse_sa_payload (ikep);
619         }
620       else if (payload == IKEV2_PAYLOAD_KE)
621         {
622           ike_ke_payload_header_t *ke = (ike_ke_payload_header_t *) ikep;
623           sa->dh_group = clib_net_to_host_u16 (ke->dh_group);
624           vec_free (sa->i_dh_data);
625           vec_add (sa->i_dh_data, ke->payload, plen - sizeof (*ke));
626         }
627       else if (payload == IKEV2_PAYLOAD_NONCE)
628         {
629           vec_free (sa->i_nonce);
630           vec_add (sa->i_nonce, ikep->payload, plen - sizeof (*ikep));
631         }
632       else if (payload == IKEV2_PAYLOAD_NOTIFY)
633         {
634           ikev2_notify_t *n = ikev2_parse_notify_payload (ikep);
635           vec_free (n);
636         }
637       else if (payload == IKEV2_PAYLOAD_VENDOR)
638         {
639           ikev2_parse_vendor_payload (ikep);
640         }
641       else
642         {
643           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
644                            payload);
645           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
646             {
647               ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
648               sa->unsupported_cp = payload;
649               return;
650             }
651         }
652
653       payload = ikep->nextpayload;
654       p += plen;
655     }
656
657   ikev2_set_state (sa, IKEV2_STATE_SA_INIT);
658 }
659
660 static void
661 ikev2_process_sa_init_resp (vlib_main_t * vm, ikev2_sa_t * sa,
662                             ike_header_t * ike)
663 {
664   int p = 0;
665   u32 len = clib_net_to_host_u32 (ike->length);
666   u8 payload = ike->nextpayload;
667
668   sa->ispi = clib_net_to_host_u64 (ike->ispi);
669   sa->rspi = clib_net_to_host_u64 (ike->rspi);
670
671   ikev2_elog_exchange ("ispi %lx rspi %lx IKE_INIT response received "
672                        "from %d.%d.%d.%d", sa->ispi, sa->rspi,
673                        sa->raddr.as_u32);
674
675   /* store whole IKE payload - needed for PSK auth */
676   vec_free (sa->last_sa_init_res_packet_data);
677   vec_add (sa->last_sa_init_res_packet_data, ike, len);
678
679   while (p < len && payload != IKEV2_PAYLOAD_NONE)
680     {
681       ike_payload_header_t *ikep = (ike_payload_header_t *) & ike->payload[p];
682       u32 plen = clib_net_to_host_u16 (ikep->length);
683
684       if (plen < sizeof (ike_payload_header_t))
685         return;
686
687       if (payload == IKEV2_PAYLOAD_SA)
688         {
689           ikev2_sa_free_proposal_vector (&sa->r_proposals);
690           sa->r_proposals = ikev2_parse_sa_payload (ikep);
691           if (sa->r_proposals)
692             {
693               ikev2_set_state (sa, IKEV2_STATE_SA_INIT);
694               ike->msgid =
695                 clib_host_to_net_u32 (clib_net_to_host_u32 (ike->msgid) + 1);
696             }
697         }
698       else if (payload == IKEV2_PAYLOAD_KE)
699         {
700           ike_ke_payload_header_t *ke = (ike_ke_payload_header_t *) ikep;
701           sa->dh_group = clib_net_to_host_u16 (ke->dh_group);
702           vec_free (sa->r_dh_data);
703           vec_add (sa->r_dh_data, ke->payload, plen - sizeof (*ke));
704         }
705       else if (payload == IKEV2_PAYLOAD_NONCE)
706         {
707           vec_free (sa->r_nonce);
708           vec_add (sa->r_nonce, ikep->payload, plen - sizeof (*ikep));
709         }
710       else if (payload == IKEV2_PAYLOAD_NOTIFY)
711         {
712           ikev2_notify_t *n = ikev2_parse_notify_payload (ikep);
713           vec_free (n);
714         }
715       else if (payload == IKEV2_PAYLOAD_VENDOR)
716         {
717           ikev2_parse_vendor_payload (ikep);
718         }
719       else
720         {
721           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
722                            payload);
723           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
724             {
725               ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
726               sa->unsupported_cp = payload;
727               return;
728             }
729         }
730
731       payload = ikep->nextpayload;
732       p += plen;
733     }
734 }
735
736 static u8 *
737 ikev2_decrypt_sk_payload (ikev2_sa_t * sa, ike_header_t * ike, u8 * payload)
738 {
739   int p = 0;
740   u8 last_payload = 0;
741   u8 *hmac = 0;
742   u32 len = clib_net_to_host_u32 (ike->length);
743   ike_payload_header_t *ikep = 0;
744   u32 plen = 0;
745   ikev2_sa_transform_t *tr_integ;
746   tr_integ =
747     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG);
748
749   while (p < len &&
750          *payload != IKEV2_PAYLOAD_NONE && last_payload != IKEV2_PAYLOAD_SK)
751     {
752       ikep = (ike_payload_header_t *) & ike->payload[p];
753       plen = clib_net_to_host_u16 (ikep->length);
754
755       if (plen < sizeof (*ikep))
756         return 0;
757
758       if (*payload == IKEV2_PAYLOAD_SK)
759         {
760           last_payload = *payload;
761         }
762       else
763         {
764           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
765                            *payload);
766           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
767             {
768               sa->unsupported_cp = *payload;
769               return 0;
770             }
771         }
772
773       *payload = ikep->nextpayload;
774       p += plen;
775     }
776
777   if (last_payload != IKEV2_PAYLOAD_SK)
778     {
779       ikev2_elog_error ("Last payload must be SK");
780       return 0;
781     }
782
783   hmac =
784     ikev2_calc_integr (tr_integ, sa->is_initiator ? sa->sk_ar : sa->sk_ai,
785                        (u8 *) ike, len - tr_integ->key_trunc);
786
787   plen = plen - sizeof (*ikep) - tr_integ->key_trunc;
788
789   if (memcmp (hmac, &ikep->payload[plen], tr_integ->key_trunc))
790     {
791       ikev2_elog_error ("message integrity check failed");
792       vec_free (hmac);
793       return 0;
794     }
795   vec_free (hmac);
796
797   return ikev2_decrypt_data (sa, ikep->payload, plen);
798 }
799
800 static void
801 ikev2_initial_contact_cleanup (ikev2_sa_t * sa)
802 {
803   ikev2_main_t *km = &ikev2_main;
804   ikev2_sa_t *tmp;
805   u32 i, *delete = 0;
806   ikev2_child_sa_t *c;
807   u32 thread_index = vlib_get_thread_index ();
808
809   if (!sa->initial_contact)
810     return;
811
812   /* find old IKE SAs with the same authenticated identity */
813   /* *INDENT-OFF* */
814   pool_foreach (tmp, km->per_thread_data[thread_index].sas, ({
815         if (tmp->i_id.type != sa->i_id.type ||
816             vec_len(tmp->i_id.data) != vec_len(sa->i_id.data) ||
817             memcmp(sa->i_id.data, tmp->i_id.data, vec_len(sa->i_id.data)))
818           continue;
819
820         if (sa->rspi != tmp->rspi)
821           vec_add1(delete, tmp - km->per_thread_data[thread_index].sas);
822   }));
823   /* *INDENT-ON* */
824
825   for (i = 0; i < vec_len (delete); i++)
826     {
827       tmp =
828         pool_elt_at_index (km->per_thread_data[thread_index].sas, delete[i]);
829       vec_foreach (c,
830                    tmp->childs) ikev2_delete_tunnel_interface (km->vnet_main,
831                                                                tmp, c);
832       ikev2_delete_sa (tmp);
833     }
834
835   vec_free (delete);
836   sa->initial_contact = 0;
837 }
838
839 static void
840 ikev2_process_auth_req (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike)
841 {
842   ikev2_child_sa_t *first_child_sa;
843   int p = 0;
844   u8 payload = ike->nextpayload;
845   u8 *plaintext = 0;
846   ike_payload_header_t *ikep;
847   u32 plen;
848
849   ikev2_elog_exchange ("ispi %lx rspi %lx EXCHANGE_IKE_AUTH received "
850                        "from %d.%d.%d.%d", clib_host_to_net_u64 (ike->ispi),
851                        clib_host_to_net_u64 (ike->rspi),
852                        sa->is_initiator ? sa->raddr.as_u32 : sa->
853                        iaddr.as_u32);
854
855   ikev2_calc_keys (sa);
856
857   plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload);
858
859   if (!plaintext)
860     {
861       if (sa->unsupported_cp)
862         ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
863       goto cleanup_and_exit;
864     }
865
866   /* select or create 1st child SA */
867   if (sa->is_initiator)
868     {
869       first_child_sa = &sa->childs[0];
870     }
871   else
872     {
873       ikev2_sa_free_all_child_sa (&sa->childs);
874       vec_add2 (sa->childs, first_child_sa, 1);
875     }
876
877
878   /* process encrypted payload */
879   p = 0;
880   while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE)
881     {
882       ikep = (ike_payload_header_t *) & plaintext[p];
883       plen = clib_net_to_host_u16 (ikep->length);
884
885       if (plen < sizeof (ike_payload_header_t))
886         goto cleanup_and_exit;
887
888       if (payload == IKEV2_PAYLOAD_SA)  /* 33 */
889         {
890           if (sa->is_initiator)
891             {
892               ikev2_sa_free_proposal_vector (&first_child_sa->r_proposals);
893               first_child_sa->r_proposals = ikev2_parse_sa_payload (ikep);
894             }
895           else
896             {
897               ikev2_sa_free_proposal_vector (&first_child_sa->i_proposals);
898               first_child_sa->i_proposals = ikev2_parse_sa_payload (ikep);
899             }
900         }
901       else if (payload == IKEV2_PAYLOAD_IDI)    /* 35 */
902         {
903           ike_id_payload_header_t *id = (ike_id_payload_header_t *) ikep;
904
905           sa->i_id.type = id->id_type;
906           vec_free (sa->i_id.data);
907           vec_add (sa->i_id.data, id->payload, plen - sizeof (*id));
908         }
909       else if (payload == IKEV2_PAYLOAD_IDR)    /* 36 */
910         {
911           ike_id_payload_header_t *id = (ike_id_payload_header_t *) ikep;
912
913           sa->r_id.type = id->id_type;
914           vec_free (sa->r_id.data);
915           vec_add (sa->r_id.data, id->payload, plen - sizeof (*id));
916         }
917       else if (payload == IKEV2_PAYLOAD_AUTH)   /* 39 */
918         {
919           ike_auth_payload_header_t *a = (ike_auth_payload_header_t *) ikep;
920
921           if (sa->is_initiator)
922             {
923               sa->r_auth.method = a->auth_method;
924               vec_free (sa->r_auth.data);
925               vec_add (sa->r_auth.data, a->payload, plen - sizeof (*a));
926             }
927           else
928             {
929               sa->i_auth.method = a->auth_method;
930               vec_free (sa->i_auth.data);
931               vec_add (sa->i_auth.data, a->payload, plen - sizeof (*a));
932             }
933         }
934       else if (payload == IKEV2_PAYLOAD_NOTIFY) /* 41 */
935         {
936           ikev2_notify_t *n = ikev2_parse_notify_payload (ikep);
937           if (n->msg_type == IKEV2_NOTIFY_MSG_INITIAL_CONTACT)
938             {
939               sa->initial_contact = 1;
940             }
941           vec_free (n);
942         }
943       else if (payload == IKEV2_PAYLOAD_VENDOR) /* 43 */
944         {
945           ikev2_parse_vendor_payload (ikep);
946         }
947       else if (payload == IKEV2_PAYLOAD_TSI)    /* 44 */
948         {
949           vec_free (first_child_sa->tsi);
950           first_child_sa->tsi = ikev2_parse_ts_payload (ikep);
951         }
952       else if (payload == IKEV2_PAYLOAD_TSR)    /* 45 */
953         {
954           vec_free (first_child_sa->tsr);
955           first_child_sa->tsr = ikev2_parse_ts_payload (ikep);
956         }
957       else
958         {
959           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
960                            payload);
961
962           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
963             {
964               ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
965               sa->unsupported_cp = payload;
966               return;
967             }
968         }
969
970       payload = ikep->nextpayload;
971       p += plen;
972     }
973
974 cleanup_and_exit:
975   vec_free (plaintext);
976 }
977
978 static void
979 ikev2_process_informational_req (vlib_main_t * vm, ikev2_sa_t * sa,
980                                  ike_header_t * ike)
981 {
982   int p = 0;
983   u8 payload = ike->nextpayload;
984   u8 *plaintext = 0;
985   ike_payload_header_t *ikep;
986   u32 plen;
987
988   ikev2_elog_exchange ("ispi %lx rspi %lx INFORMATIONAL received "
989                        "from %d.%d.%d.%d", clib_host_to_net_u64 (ike->ispi),
990                        clib_host_to_net_u64 (ike->rspi), sa->iaddr.as_u32);
991
992   plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload);
993
994   if (!plaintext)
995     goto cleanup_and_exit;
996
997   /* process encrypted payload */
998   p = 0;
999   while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE)
1000     {
1001       ikep = (ike_payload_header_t *) & plaintext[p];
1002       plen = clib_net_to_host_u16 (ikep->length);
1003
1004       if (plen < sizeof (ike_payload_header_t))
1005         goto cleanup_and_exit;
1006
1007       if (payload == IKEV2_PAYLOAD_NOTIFY)      /* 41 */
1008         {
1009           ikev2_notify_t *n = ikev2_parse_notify_payload (ikep);
1010           if (n->msg_type == IKEV2_NOTIFY_MSG_AUTHENTICATION_FAILED)
1011             ikev2_set_state (sa, IKEV2_STATE_AUTH_FAILED);
1012           vec_free (n);
1013         }
1014       else if (payload == IKEV2_PAYLOAD_DELETE) /* 42 */
1015         {
1016           sa->del = ikev2_parse_delete_payload (ikep);
1017         }
1018       else if (payload == IKEV2_PAYLOAD_VENDOR) /* 43 */
1019         {
1020           ikev2_parse_vendor_payload (ikep);
1021         }
1022       else
1023         {
1024           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
1025                            payload);
1026           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
1027             {
1028               sa->unsupported_cp = payload;
1029               return;
1030             }
1031         }
1032
1033       payload = ikep->nextpayload;
1034       p += plen;
1035     }
1036
1037 cleanup_and_exit:
1038   vec_free (plaintext);
1039 }
1040
1041 static void
1042 ikev2_process_create_child_sa_req (vlib_main_t * vm, ikev2_sa_t * sa,
1043                                    ike_header_t * ike)
1044 {
1045   int p = 0;
1046   u8 payload = ike->nextpayload;
1047   u8 *plaintext = 0;
1048   u8 rekeying = 0;
1049   u8 nonce[IKEV2_NONCE_SIZE];
1050
1051   ike_payload_header_t *ikep;
1052   u32 plen;
1053   ikev2_notify_t *n = 0;
1054   ikev2_ts_t *tsi = 0;
1055   ikev2_ts_t *tsr = 0;
1056   ikev2_sa_proposal_t *proposal = 0;
1057   ikev2_child_sa_t *child_sa;
1058
1059   ikev2_elog_exchange ("ispi %lx rspi %lx CREATE_CHILD_SA received "
1060                        "from %d.%d.%d.%d", clib_host_to_net_u64 (ike->ispi),
1061                        clib_host_to_net_u64 (ike->rspi), sa->raddr.as_u32);
1062
1063   plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload);
1064
1065   if (!plaintext)
1066     goto cleanup_and_exit;
1067
1068   /* process encrypted payload */
1069   p = 0;
1070   while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE)
1071     {
1072       ikep = (ike_payload_header_t *) & plaintext[p];
1073       plen = clib_net_to_host_u16 (ikep->length);
1074
1075       if (plen < sizeof (ike_payload_header_t))
1076         goto cleanup_and_exit;
1077
1078       else if (payload == IKEV2_PAYLOAD_SA)
1079         {
1080           proposal = ikev2_parse_sa_payload (ikep);
1081         }
1082       else if (payload == IKEV2_PAYLOAD_NOTIFY)
1083         {
1084           n = ikev2_parse_notify_payload (ikep);
1085           if (n->msg_type == IKEV2_NOTIFY_MSG_REKEY_SA)
1086             {
1087               rekeying = 1;
1088             }
1089         }
1090       else if (payload == IKEV2_PAYLOAD_DELETE)
1091         {
1092           sa->del = ikev2_parse_delete_payload (ikep);
1093         }
1094       else if (payload == IKEV2_PAYLOAD_VENDOR)
1095         {
1096           ikev2_parse_vendor_payload (ikep);
1097         }
1098       else if (payload == IKEV2_PAYLOAD_NONCE)
1099         {
1100           clib_memcpy_fast (nonce, ikep->payload, plen - sizeof (*ikep));
1101         }
1102       else if (payload == IKEV2_PAYLOAD_TSI)
1103         {
1104           tsi = ikev2_parse_ts_payload (ikep);
1105         }
1106       else if (payload == IKEV2_PAYLOAD_TSR)
1107         {
1108           tsr = ikev2_parse_ts_payload (ikep);
1109         }
1110       else
1111         {
1112           ikev2_elog_uint (IKEV2_LOG_ERROR, "Unknown payload! type=%d",
1113                            payload);
1114           if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL)
1115             {
1116               sa->unsupported_cp = payload;
1117               return;
1118             }
1119         }
1120
1121       payload = ikep->nextpayload;
1122       p += plen;
1123     }
1124
1125   if (sa->is_initiator && proposal->protocol_id == IKEV2_PROTOCOL_ESP)
1126     {
1127       ikev2_rekey_t *rekey = &sa->rekey[0];
1128       rekey->protocol_id = proposal->protocol_id;
1129       rekey->i_proposal =
1130         ikev2_select_proposal (proposal, IKEV2_PROTOCOL_ESP);
1131       rekey->i_proposal->spi = rekey->spi;
1132       rekey->r_proposal = proposal;
1133       rekey->tsi = tsi;
1134       rekey->tsr = tsr;
1135       /* update Nr */
1136       vec_free (sa->r_nonce);
1137       vec_add (sa->r_nonce, nonce, IKEV2_NONCE_SIZE);
1138       child_sa = ikev2_sa_get_child (sa, rekey->ispi, IKEV2_PROTOCOL_ESP, 1);
1139       if (child_sa)
1140         {
1141           child_sa->rekey_retries = 0;
1142         }
1143     }
1144   else if (rekeying)
1145     {
1146       ikev2_rekey_t *rekey;
1147       child_sa = ikev2_sa_get_child (sa, n->spi, n->protocol_id, 1);
1148       if (!child_sa)
1149         {
1150           ikev2_elog_uint (IKEV2_LOG_ERROR, "child SA spi %lx not found",
1151                            n->spi);
1152           goto cleanup_and_exit;
1153         }
1154       vec_add2 (sa->rekey, rekey, 1);
1155       rekey->protocol_id = n->protocol_id;
1156       rekey->spi = n->spi;
1157       rekey->i_proposal = proposal;
1158       rekey->r_proposal =
1159         ikev2_select_proposal (proposal, IKEV2_PROTOCOL_ESP);
1160       rekey->tsi = tsi;
1161       rekey->tsr = tsr;
1162       /* update Ni */
1163       vec_free (sa->i_nonce);
1164       vec_add (sa->i_nonce, nonce, IKEV2_NONCE_SIZE);
1165       /* generate new Nr */
1166       vec_free (sa->r_nonce);
1167       sa->r_nonce = vec_new (u8, IKEV2_NONCE_SIZE);
1168       RAND_bytes ((u8 *) sa->r_nonce, IKEV2_NONCE_SIZE);
1169     }
1170
1171 cleanup_and_exit:
1172   vec_free (plaintext);
1173   vec_free (n);
1174 }
1175
1176 static u8 *
1177 ikev2_sa_generate_authmsg (ikev2_sa_t * sa, int is_responder)
1178 {
1179   u8 *authmsg = 0;
1180   u8 *data;
1181   u8 *nonce;
1182   ikev2_id_t *id;
1183   u8 *key;
1184   u8 *packet_data;
1185   ikev2_sa_transform_t *tr_prf;
1186
1187   tr_prf =
1188     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF);
1189
1190   if (is_responder)
1191     {
1192       id = &sa->r_id;
1193       key = sa->sk_pr;
1194       nonce = sa->i_nonce;
1195       packet_data = sa->last_sa_init_res_packet_data;
1196     }
1197   else
1198     {
1199       id = &sa->i_id;
1200       key = sa->sk_pi;
1201       nonce = sa->r_nonce;
1202       packet_data = sa->last_sa_init_req_packet_data;
1203     }
1204
1205   data = vec_new (u8, 4);
1206   data[0] = id->type;
1207   vec_append (data, id->data);
1208
1209   u8 *id_hash = ikev2_calc_prf (tr_prf, key, data);
1210   vec_append (authmsg, packet_data);
1211   vec_append (authmsg, nonce);
1212   vec_append (authmsg, id_hash);
1213   vec_free (id_hash);
1214   vec_free (data);
1215
1216   return authmsg;
1217 }
1218
1219 static int
1220 ikev2_ts_cmp (ikev2_ts_t * ts1, ikev2_ts_t * ts2)
1221 {
1222   if (ts1->ts_type == ts2->ts_type && ts1->protocol_id == ts2->protocol_id &&
1223       ts1->start_port == ts2->start_port && ts1->end_port == ts2->end_port &&
1224       ts1->start_addr.as_u32 == ts2->start_addr.as_u32 &&
1225       ts1->end_addr.as_u32 == ts2->end_addr.as_u32)
1226     return 1;
1227
1228   return 0;
1229 }
1230
1231 static void
1232 ikev2_sa_match_ts (ikev2_sa_t * sa)
1233 {
1234   ikev2_main_t *km = &ikev2_main;
1235   ikev2_profile_t *p;
1236   ikev2_ts_t *ts, *p_tsi, *p_tsr, *tsi = 0, *tsr = 0;
1237   ikev2_id_t *id;
1238
1239   /* *INDENT-OFF* */
1240   pool_foreach (p, km->profiles, ({
1241
1242     if (sa->is_initiator)
1243       {
1244         p_tsi = &p->loc_ts;
1245         p_tsr = &p->rem_ts;
1246         id = &sa->r_id;
1247       }
1248     else
1249       {
1250         p_tsi = &p->rem_ts;
1251         p_tsr = &p->loc_ts;
1252         id = &sa->i_id;
1253       }
1254
1255     /* check id */
1256     if (p->rem_id.type != id->type ||
1257         vec_len(p->rem_id.data) != vec_len(id->data) ||
1258         memcmp(p->rem_id.data, id->data, vec_len(p->rem_id.data)))
1259       continue;
1260
1261     vec_foreach(ts, sa->childs[0].tsi)
1262       {
1263         if (ikev2_ts_cmp(p_tsi, ts))
1264           {
1265             vec_add1 (tsi, ts[0]);
1266             break;
1267           }
1268       }
1269
1270     vec_foreach(ts, sa->childs[0].tsr)
1271       {
1272         if (ikev2_ts_cmp(p_tsr, ts))
1273           {
1274             vec_add1 (tsr, ts[0]);
1275             break;
1276           }
1277       }
1278
1279     break;
1280   }));
1281   /* *INDENT-ON* */
1282
1283   if (tsi && tsr)
1284     {
1285       vec_free (sa->childs[0].tsi);
1286       vec_free (sa->childs[0].tsr);
1287       sa->childs[0].tsi = tsi;
1288       sa->childs[0].tsr = tsr;
1289     }
1290   else
1291     {
1292       vec_free (tsi);
1293       vec_free (tsr);
1294       ikev2_set_state (sa, IKEV2_STATE_TS_UNACCEPTABLE);
1295     }
1296 }
1297
1298 static void
1299 ikev2_sa_auth (ikev2_sa_t * sa)
1300 {
1301   ikev2_main_t *km = &ikev2_main;
1302   ikev2_profile_t *p, *sel_p = 0;
1303   u8 *authmsg, *key_pad, *psk = 0, *auth = 0;
1304   ikev2_sa_transform_t *tr_prf;
1305
1306   tr_prf =
1307     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF);
1308
1309   /* only shared key and rsa signature */
1310   if (!(sa->i_auth.method == IKEV2_AUTH_METHOD_SHARED_KEY_MIC ||
1311         sa->i_auth.method == IKEV2_AUTH_METHOD_RSA_SIG))
1312     {
1313       ikev2_elog_uint (IKEV2_LOG_ERROR,
1314                        "unsupported authentication method %u",
1315                        sa->i_auth.method);
1316       ikev2_set_state (sa, IKEV2_STATE_AUTH_FAILED);
1317       return;
1318     }
1319
1320   key_pad = format (0, "%s", IKEV2_KEY_PAD);
1321   authmsg = ikev2_sa_generate_authmsg (sa, sa->is_initiator);
1322
1323   ikev2_id_t *sa_id;
1324   ikev2_auth_t *sa_auth;
1325
1326   if (sa->is_initiator)
1327     {
1328       sa_id = &sa->r_id;
1329       sa_auth = &sa->r_auth;
1330     }
1331   else
1332     {
1333       sa_id = &sa->i_id;
1334       sa_auth = &sa->i_auth;
1335     }
1336
1337   /* *INDENT-OFF* */
1338   pool_foreach (p, km->profiles, ({
1339
1340     /* check id */
1341     if (p->rem_id.type != sa_id->type ||
1342         vec_len(p->rem_id.data) != vec_len(sa_id->data) ||
1343         memcmp(p->rem_id.data, sa_id->data, vec_len(p->rem_id.data)))
1344       continue;
1345
1346     if (sa_auth->method == IKEV2_AUTH_METHOD_SHARED_KEY_MIC)
1347       {
1348         if (!p->auth.data ||
1349              p->auth.method != IKEV2_AUTH_METHOD_SHARED_KEY_MIC)
1350           continue;
1351
1352         psk = ikev2_calc_prf(tr_prf, p->auth.data, key_pad);
1353         auth = ikev2_calc_prf(tr_prf, psk, authmsg);
1354
1355         if (!memcmp(auth, sa_auth->data, vec_len(sa_auth->data)))
1356           {
1357             ikev2_set_state(sa, IKEV2_STATE_AUTHENTICATED);
1358             vec_free(auth);
1359             sel_p = p;
1360             break;
1361           }
1362
1363       }
1364     else if (sa_auth->method == IKEV2_AUTH_METHOD_RSA_SIG)
1365       {
1366         if (p->auth.method != IKEV2_AUTH_METHOD_RSA_SIG)
1367           continue;
1368
1369         if (ikev2_verify_sign(p->auth.key, sa_auth->data, authmsg) == 1)
1370           {
1371             ikev2_set_state(sa, IKEV2_STATE_AUTHENTICATED);
1372             sel_p = p;
1373             break;
1374           }
1375       }
1376
1377     vec_free(auth);
1378     vec_free(psk);
1379   }));
1380   /* *INDENT-ON* */
1381
1382   if (sel_p)
1383     {
1384       sa->udp_encap = sel_p->udp_encap;
1385       sa->dst_port = sel_p->dst_port;
1386     }
1387   vec_free (authmsg);
1388
1389   if (sa->state == IKEV2_STATE_AUTHENTICATED)
1390     {
1391       if (!sa->is_initiator)
1392         {
1393           vec_free (sa->r_id.data);
1394           sa->r_id.data = vec_dup (sel_p->loc_id.data);
1395           sa->r_id.type = sel_p->loc_id.type;
1396
1397           /* generate our auth data */
1398           authmsg = ikev2_sa_generate_authmsg (sa, 1);
1399           if (sel_p->auth.method == IKEV2_AUTH_METHOD_SHARED_KEY_MIC)
1400             {
1401               sa->r_auth.data = ikev2_calc_prf (tr_prf, psk, authmsg);
1402               sa->r_auth.method = IKEV2_AUTH_METHOD_SHARED_KEY_MIC;
1403             }
1404           else if (sel_p->auth.method == IKEV2_AUTH_METHOD_RSA_SIG)
1405             {
1406               sa->r_auth.data = ikev2_calc_sign (km->pkey, authmsg);
1407               sa->r_auth.method = IKEV2_AUTH_METHOD_RSA_SIG;
1408             }
1409           vec_free (authmsg);
1410
1411           /* select transforms for 1st child sa */
1412           ikev2_sa_free_proposal_vector (&sa->childs[0].r_proposals);
1413           sa->childs[0].r_proposals =
1414             ikev2_select_proposal (sa->childs[0].i_proposals,
1415                                    IKEV2_PROTOCOL_ESP);
1416
1417           if (~0 != sel_p->tun_itf)
1418             {
1419               sa->is_tun_itf_set = 1;
1420               sa->tun_itf = sel_p->tun_itf;
1421             }
1422         }
1423     }
1424   else
1425     {
1426       ikev2_elog_uint (IKEV2_LOG_ERROR, "authentication failed, no matching "
1427                        "profile found! ispi %lx", sa->ispi);
1428       ikev2_set_state (sa, IKEV2_STATE_AUTH_FAILED);
1429     }
1430   vec_free (psk);
1431   vec_free (key_pad);
1432 }
1433
1434
1435 static void
1436 ikev2_sa_auth_init (ikev2_sa_t * sa)
1437 {
1438   ikev2_main_t *km = &ikev2_main;
1439   u8 *authmsg, *key_pad, *psk = 0, *auth = 0;
1440   ikev2_sa_transform_t *tr_prf;
1441
1442   tr_prf =
1443     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF);
1444
1445   /* only shared key and rsa signature */
1446   if (!(sa->i_auth.method == IKEV2_AUTH_METHOD_SHARED_KEY_MIC ||
1447         sa->i_auth.method == IKEV2_AUTH_METHOD_RSA_SIG))
1448     {
1449       ikev2_elog_uint (IKEV2_LOG_ERROR,
1450                        "unsupported authentication method %u",
1451                        sa->i_auth.method);
1452       ikev2_set_state (sa, IKEV2_STATE_AUTH_FAILED);
1453       return;
1454     }
1455
1456   key_pad = format (0, "%s", IKEV2_KEY_PAD);
1457   authmsg = ikev2_sa_generate_authmsg (sa, 0);
1458   psk = ikev2_calc_prf (tr_prf, sa->i_auth.data, key_pad);
1459   auth = ikev2_calc_prf (tr_prf, psk, authmsg);
1460
1461
1462   if (sa->i_auth.method == IKEV2_AUTH_METHOD_SHARED_KEY_MIC)
1463     {
1464       sa->i_auth.data = ikev2_calc_prf (tr_prf, psk, authmsg);
1465       sa->i_auth.method = IKEV2_AUTH_METHOD_SHARED_KEY_MIC;
1466     }
1467   else if (sa->i_auth.method == IKEV2_AUTH_METHOD_RSA_SIG)
1468     {
1469       sa->i_auth.data = ikev2_calc_sign (km->pkey, authmsg);
1470       sa->i_auth.method = IKEV2_AUTH_METHOD_RSA_SIG;
1471     }
1472
1473   vec_free (psk);
1474   vec_free (key_pad);
1475   vec_free (auth);
1476   vec_free (authmsg);
1477 }
1478
1479 static u32
1480 ikev2_mk_local_sa_id (u32 sai, u32 ci, u32 ti)
1481 {
1482   return (0x80000000 | (ti << 24) | (sai << 12) | ci);
1483 }
1484
1485 static u32
1486 ikev2_mk_remote_sa_id (u32 sai, u32 ci, u32 ti)
1487 {
1488   return (0xc0000000 | (ti << 24) | (sai << 12) | ci);
1489 }
1490
1491 typedef struct
1492 {
1493   u32 sw_if_index;
1494   u32 salt_local;
1495   u32 salt_remote;
1496   u32 local_sa_id;
1497   u32 remote_sa_id;
1498   ipsec_sa_flags_t flags;
1499   u32 local_spi;
1500   u32 remote_spi;
1501   ipsec_crypto_alg_t encr_type;
1502   ipsec_integ_alg_t integ_type;
1503   ip46_address_t local_ip;
1504   ip46_address_t remote_ip;
1505   ipsec_key_t loc_ckey, rem_ckey, loc_ikey, rem_ikey;
1506   u8 is_rekey;
1507   u32 old_remote_sa_id;
1508   u16 dst_port;
1509 } ikev2_add_ipsec_tunnel_args_t;
1510
1511 static void
1512 ikev2_add_tunnel_from_main (ikev2_add_ipsec_tunnel_args_t * a)
1513 {
1514   ikev2_main_t *km = &ikev2_main;
1515   u32 sw_if_index;
1516   int rv = 0;
1517
1518   if (~0 == a->sw_if_index)
1519     {
1520       /* no tunnel associated with the SA/profile - create a new one */
1521       rv = ipip_add_tunnel (IPIP_TRANSPORT_IP4, ~0,
1522                             &a->local_ip, &a->remote_ip, 0,
1523                             TUNNEL_ENCAP_DECAP_FLAG_NONE, IP_DSCP_CS0,
1524                             TUNNEL_MODE_P2P, &sw_if_index);
1525
1526       if (rv == VNET_API_ERROR_IF_ALREADY_EXISTS)
1527         {
1528           if (hash_get (km->sw_if_indices, sw_if_index))
1529             /* interface is managed by IKE; proceed with updating SAs */
1530             rv = 0;
1531         }
1532       hash_set1 (km->sw_if_indices, sw_if_index);
1533     }
1534   else
1535     {
1536       sw_if_index = a->sw_if_index;
1537       vnet_sw_interface_admin_up (vnet_get_main (), sw_if_index);
1538     }
1539
1540   if (rv)
1541     {
1542       ikev2_elog_peers (IKEV2_LOG_ERROR, "installing ipip tunnel failed! "
1543                         "loc:%d.%d.%d.%d rem:%d.%d.%d.%d",
1544                         a->local_ip.ip4.as_u32, a->remote_ip.ip4.as_u32);
1545       return;
1546     }
1547
1548   u32 *sas_in = NULL;
1549   vec_add1 (sas_in, a->remote_sa_id);
1550   if (a->is_rekey)
1551     {
1552       ipsec_tun_protect_del (sw_if_index, NULL);
1553
1554       /* replace local SA immediately */
1555       ipsec_sa_unlock_id (a->local_sa_id);
1556
1557       /* keep the old sa */
1558       vec_add1 (sas_in, a->old_remote_sa_id);
1559     }
1560
1561   rv |= ipsec_sa_add_and_lock (a->local_sa_id,
1562                                a->local_spi,
1563                                IPSEC_PROTOCOL_ESP, a->encr_type,
1564                                &a->loc_ckey, a->integ_type, &a->loc_ikey,
1565                                a->flags, 0, a->salt_local, &a->local_ip,
1566                                &a->remote_ip, NULL, a->dst_port);
1567   rv |= ipsec_sa_add_and_lock (a->remote_sa_id, a->remote_spi,
1568                                IPSEC_PROTOCOL_ESP, a->encr_type, &a->rem_ckey,
1569                                a->integ_type, &a->rem_ikey,
1570                                (a->flags | IPSEC_SA_FLAG_IS_INBOUND), 0,
1571                                a->salt_remote, &a->remote_ip,
1572                                &a->local_ip, NULL, a->dst_port);
1573
1574   rv |= ipsec_tun_protect_update (sw_if_index, NULL, a->local_sa_id, sas_in);
1575 }
1576
1577 static int
1578 ikev2_create_tunnel_interface (vnet_main_t * vnm,
1579                                u32 thread_index,
1580                                ikev2_sa_t * sa,
1581                                ikev2_child_sa_t * child, u32 sa_index,
1582                                u32 child_index, u8 is_rekey)
1583 {
1584   ikev2_main_t *km = &ikev2_main;
1585   ipsec_crypto_alg_t encr_type;
1586   ipsec_integ_alg_t integ_type;
1587   ikev2_profile_t *p = 0;
1588   ikev2_sa_transform_t *tr;
1589   ikev2_sa_proposal_t *proposals;
1590   u8 is_aead = 0;
1591   ikev2_add_ipsec_tunnel_args_t a;
1592
1593   clib_memset (&a, 0, sizeof (a));
1594
1595   if (!child->r_proposals)
1596     {
1597       ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1598       return 1;
1599     }
1600
1601   if (sa->is_initiator)
1602     {
1603       ip46_address_set_ip4 (&a.local_ip, &sa->iaddr);
1604       ip46_address_set_ip4 (&a.remote_ip, &sa->raddr);
1605       proposals = child->i_proposals;
1606       a.local_spi = child->r_proposals[0].spi;
1607       a.remote_spi = child->i_proposals[0].spi;
1608     }
1609   else
1610     {
1611       ip46_address_set_ip4 (&a.local_ip, &sa->raddr);
1612       ip46_address_set_ip4 (&a.remote_ip, &sa->iaddr);
1613       proposals = child->r_proposals;
1614       a.local_spi = child->i_proposals[0].spi;
1615       a.remote_spi = child->r_proposals[0].spi;
1616     }
1617
1618   a.flags = IPSEC_SA_FLAG_USE_ANTI_REPLAY;
1619   a.flags |= IPSEC_SA_FLAG_IS_TUNNEL;
1620   if (sa->udp_encap)
1621     a.flags |= IPSEC_SA_FLAG_UDP_ENCAP;
1622   a.is_rekey = is_rekey;
1623
1624   tr = ikev2_sa_get_td_for_type (proposals, IKEV2_TRANSFORM_TYPE_ESN);
1625   if (tr && tr->esn_type)
1626     a.flags |= IPSEC_SA_FLAG_USE_ESN;
1627
1628   tr = ikev2_sa_get_td_for_type (proposals, IKEV2_TRANSFORM_TYPE_ENCR);
1629   if (tr)
1630     {
1631       if (tr->encr_type == IKEV2_TRANSFORM_ENCR_TYPE_AES_CBC && tr->key_len)
1632         {
1633           switch (tr->key_len)
1634             {
1635             case 16:
1636               encr_type = IPSEC_CRYPTO_ALG_AES_CBC_128;
1637               break;
1638             case 24:
1639               encr_type = IPSEC_CRYPTO_ALG_AES_CBC_192;
1640               break;
1641             case 32:
1642               encr_type = IPSEC_CRYPTO_ALG_AES_CBC_256;
1643               break;
1644             default:
1645               ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1646               return 1;
1647               break;
1648             }
1649         }
1650       else if (tr->encr_type == IKEV2_TRANSFORM_ENCR_TYPE_AES_GCM_16
1651                && tr->key_len)
1652         {
1653           switch (tr->key_len)
1654             {
1655             case 16:
1656               encr_type = IPSEC_CRYPTO_ALG_AES_GCM_128;
1657               break;
1658             case 24:
1659               encr_type = IPSEC_CRYPTO_ALG_AES_GCM_192;
1660               break;
1661             case 32:
1662               encr_type = IPSEC_CRYPTO_ALG_AES_GCM_256;
1663               break;
1664             default:
1665               ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1666               return 1;
1667               break;
1668             }
1669           is_aead = 1;
1670         }
1671       else
1672         {
1673           ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1674           return 1;
1675         }
1676     }
1677   else
1678     {
1679       ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1680       return 1;
1681     }
1682   a.encr_type = encr_type;
1683
1684   if (!is_aead)
1685     {
1686       tr = ikev2_sa_get_td_for_type (proposals, IKEV2_TRANSFORM_TYPE_INTEG);
1687       if (tr)
1688         {
1689           switch (tr->integ_type)
1690             {
1691             case IKEV2_TRANSFORM_INTEG_TYPE_AUTH_HMAC_SHA2_256_128:
1692               integ_type = IPSEC_INTEG_ALG_SHA_256_128;
1693               break;
1694             case IKEV2_TRANSFORM_INTEG_TYPE_AUTH_HMAC_SHA2_384_192:
1695               integ_type = IPSEC_INTEG_ALG_SHA_384_192;
1696               break;
1697             case IKEV2_TRANSFORM_INTEG_TYPE_AUTH_HMAC_SHA2_512_256:
1698               integ_type = IPSEC_INTEG_ALG_SHA_512_256;
1699               break;
1700             case IKEV2_TRANSFORM_INTEG_TYPE_AUTH_HMAC_SHA1_96:
1701               integ_type = IPSEC_INTEG_ALG_SHA1_96;
1702               break;
1703             default:
1704               ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1705               return 1;
1706             }
1707         }
1708       else
1709         {
1710           ikev2_set_state (sa, IKEV2_STATE_NO_PROPOSAL_CHOSEN);
1711           return 1;
1712         }
1713     }
1714   else
1715     {
1716       integ_type = IPSEC_INTEG_ALG_NONE;
1717     }
1718
1719   a.integ_type = integ_type;
1720   ikev2_calc_child_keys (sa, child);
1721
1722   if (sa->is_initiator)
1723     {
1724       ipsec_mk_key (&a.loc_ikey, child->sk_ai, vec_len (child->sk_ai));
1725       ipsec_mk_key (&a.rem_ikey, child->sk_ar, vec_len (child->sk_ar));
1726       ipsec_mk_key (&a.loc_ckey, child->sk_ei, vec_len (child->sk_ei));
1727       ipsec_mk_key (&a.rem_ckey, child->sk_er, vec_len (child->sk_er));
1728       if (is_aead)
1729         {
1730           a.salt_remote = child->salt_er;
1731           a.salt_local = child->salt_ei;
1732         }
1733     }
1734   else
1735     {
1736       ipsec_mk_key (&a.loc_ikey, child->sk_ar, vec_len (child->sk_ar));
1737       ipsec_mk_key (&a.rem_ikey, child->sk_ai, vec_len (child->sk_ai));
1738       ipsec_mk_key (&a.loc_ckey, child->sk_er, vec_len (child->sk_er));
1739       ipsec_mk_key (&a.rem_ckey, child->sk_ei, vec_len (child->sk_ei));
1740       if (is_aead)
1741         {
1742           a.salt_remote = child->salt_ei;
1743           a.salt_local = child->salt_er;
1744         }
1745     }
1746
1747   if (sa->is_profile_index_set)
1748     p = pool_elt_at_index (km->profiles, sa->profile_index);
1749
1750   if (p && p->lifetime)
1751     {
1752       child->time_to_expiration =
1753         vlib_time_now (vnm->vlib_main) + p->lifetime;
1754       if (p->lifetime_jitter)
1755         {
1756           // This is not much better than rand(3), which Coverity warns
1757           // is unsuitable for security applications; random_u32 is
1758           // however fast. If this perturbance to the expiration time
1759           // needs to use a better RNG then we may need to use something
1760           // like /dev/urandom which has significant overhead.
1761           u32 rnd = (u32) (vlib_time_now (vnm->vlib_main) * 1e6);
1762           rnd = random_u32 (&rnd);
1763
1764           child->time_to_expiration += 1 + (rnd % p->lifetime_jitter);
1765         }
1766     }
1767
1768   if (thread_index & 0xffffffc0)
1769     ikev2_elog_error ("error: thread index exceeds max range 0x3f!");
1770
1771   if (child_index & 0xfffff000 || sa_index & 0xfffff000)
1772     ikev2_elog_error ("error: sa/child index exceeds max range 0xfff!");
1773
1774   child->local_sa_id =
1775     a.local_sa_id =
1776     ikev2_mk_local_sa_id (sa_index, child_index, thread_index);
1777
1778   u32 remote_sa_id = ikev2_mk_remote_sa_id (sa_index, child_index,
1779                                             thread_index);
1780
1781   if (is_rekey)
1782     {
1783       /* create a new remote SA ID to keep the old SA for a bit longer
1784        * so the peer has some time to swap their SAs */
1785
1786       /* use most significat bit of child index part in id */
1787       u32 mask = 0x800;
1788       if (sa->current_remote_id_mask)
1789         {
1790           sa->old_remote_id = a.old_remote_sa_id = remote_sa_id | mask;
1791           sa->current_remote_id_mask = 0;
1792         }
1793       else
1794         {
1795           sa->old_remote_id = a.old_remote_sa_id = remote_sa_id;
1796           sa->current_remote_id_mask = mask;
1797           remote_sa_id |= mask;
1798         }
1799       sa->old_id_expiration = 3.0;
1800       sa->old_remote_id_present = 1;
1801     }
1802
1803   child->remote_sa_id = a.remote_sa_id = remote_sa_id;
1804
1805   a.sw_if_index = (sa->is_tun_itf_set ? sa->tun_itf : ~0);
1806   a.dst_port = sa->dst_port;
1807
1808   vl_api_rpc_call_main_thread (ikev2_add_tunnel_from_main,
1809                                (u8 *) & a, sizeof (a));
1810   return 0;
1811 }
1812
1813 typedef struct
1814 {
1815   ip46_address_t local_ip;
1816   ip46_address_t remote_ip;
1817   u32 remote_sa_id;
1818   u32 local_sa_id;
1819   u32 sw_if_index;
1820 } ikev2_del_ipsec_tunnel_args_t;
1821
1822 static_always_inline u32
1823 ikev2_flip_alternate_sa_bit (u32 id)
1824 {
1825   u32 mask = 0x800;
1826   if (mask & id)
1827     return id & ~mask;
1828   return id | mask;
1829 }
1830
1831 static void
1832 ikev2_del_tunnel_from_main (ikev2_del_ipsec_tunnel_args_t * a)
1833 {
1834   ikev2_main_t *km = &ikev2_main;
1835   ipip_tunnel_t *ipip = NULL;
1836   u32 sw_if_index;
1837
1838   if (~0 == a->sw_if_index)
1839     {
1840     /* *INDENT-OFF* */
1841     ipip_tunnel_key_t key = {
1842       .src = a->local_ip,
1843       .dst = a->remote_ip,
1844       .transport = IPIP_TRANSPORT_IP4,
1845       .fib_index = 0,
1846     };
1847     /* *INDENT-ON* */
1848
1849       ipip = ipip_tunnel_db_find (&key);
1850
1851       if (ipip)
1852         {
1853           sw_if_index = ipip->sw_if_index;
1854           hash_unset (km->sw_if_indices, ipip->sw_if_index);
1855         }
1856       else
1857         sw_if_index = ~0;
1858     }
1859   else
1860     {
1861       sw_if_index = a->sw_if_index;
1862       vnet_sw_interface_admin_down (vnet_get_main (), sw_if_index);
1863     }
1864
1865   if (~0 != sw_if_index)
1866     ipsec_tun_protect_del (sw_if_index, NULL);
1867
1868   ipsec_sa_unlock_id (a->remote_sa_id);
1869   ipsec_sa_unlock_id (a->local_sa_id);
1870   ipsec_sa_unlock_id (ikev2_flip_alternate_sa_bit (a->remote_sa_id));
1871
1872   if (ipip)
1873     ipip_del_tunnel (ipip->sw_if_index);
1874 }
1875
1876 static int
1877 ikev2_delete_tunnel_interface (vnet_main_t * vnm, ikev2_sa_t * sa,
1878                                ikev2_child_sa_t * child)
1879 {
1880   ikev2_del_ipsec_tunnel_args_t a;
1881
1882   clib_memset (&a, 0, sizeof (a));
1883
1884   if (sa->is_initiator)
1885     {
1886       ip46_address_set_ip4 (&a.local_ip, &sa->iaddr);
1887       ip46_address_set_ip4 (&a.remote_ip, &sa->raddr);
1888     }
1889   else
1890     {
1891       ip46_address_set_ip4 (&a.local_ip, &sa->raddr);
1892       ip46_address_set_ip4 (&a.remote_ip, &sa->iaddr);
1893     }
1894
1895   a.remote_sa_id = child->remote_sa_id;
1896   a.local_sa_id = child->local_sa_id;
1897   a.sw_if_index = (sa->is_tun_itf_set ? sa->tun_itf : ~0);
1898
1899   vl_api_rpc_call_main_thread (ikev2_del_tunnel_from_main, (u8 *) & a,
1900                                sizeof (a));
1901   return 0;
1902 }
1903
1904 static u32
1905 ikev2_generate_message (ikev2_sa_t * sa, ike_header_t * ike, void *user)
1906 {
1907   v8 *integ = 0;
1908   ike_payload_header_t *ph;
1909   u16 plen;
1910   u32 tlen = 0;
1911
1912   ikev2_sa_transform_t *tr_encr, *tr_integ;
1913   tr_encr =
1914     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR);
1915   tr_integ =
1916     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG);
1917
1918   ikev2_payload_chain_t *chain = 0;
1919   ikev2_payload_new_chain (chain);
1920
1921   if (ike->exchange == IKEV2_EXCHANGE_SA_INIT)
1922     {
1923       if (sa->r_proposals == 0)
1924         {
1925           ikev2_payload_add_notify (chain,
1926                                     IKEV2_NOTIFY_MSG_NO_PROPOSAL_CHOSEN, 0);
1927           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1928         }
1929       else if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE)
1930         {
1931           u8 *data = vec_new (u8, 2);
1932           ikev2_sa_transform_t *tr_dh;
1933           tr_dh =
1934             ikev2_sa_get_td_for_type (sa->r_proposals,
1935                                       IKEV2_TRANSFORM_TYPE_DH);
1936           ASSERT (tr_dh && tr_dh->dh_type);
1937
1938           data[0] = (tr_dh->dh_type >> 8) & 0xff;
1939           data[1] = (tr_dh->dh_type) & 0xff;
1940
1941           ikev2_payload_add_notify (chain,
1942                                     IKEV2_NOTIFY_MSG_INVALID_KE_PAYLOAD,
1943                                     data);
1944           vec_free (data);
1945           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1946         }
1947       else if (sa->state == IKEV2_STATE_NOTIFY_AND_DELETE)
1948         {
1949           u8 *data = vec_new (u8, 1);
1950
1951           data[0] = sa->unsupported_cp;
1952           ikev2_payload_add_notify (chain,
1953                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
1954                                     data);
1955           vec_free (data);
1956         }
1957       else
1958         {
1959           ike->rspi = clib_host_to_net_u64 (sa->rspi);
1960           ikev2_payload_add_sa (chain, sa->r_proposals);
1961           ikev2_payload_add_ke (chain, sa->dh_group, sa->r_dh_data);
1962           ikev2_payload_add_nonce (chain, sa->r_nonce);
1963         }
1964     }
1965   else if (ike->exchange == IKEV2_EXCHANGE_IKE_AUTH)
1966     {
1967       if (sa->state == IKEV2_STATE_AUTHENTICATED)
1968         {
1969           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
1970           ikev2_payload_add_auth (chain, &sa->r_auth);
1971           ikev2_payload_add_sa (chain, sa->childs[0].r_proposals);
1972           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
1973           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
1974         }
1975       else if (sa->state == IKEV2_STATE_AUTH_FAILED)
1976         {
1977           ikev2_payload_add_notify (chain,
1978                                     IKEV2_NOTIFY_MSG_AUTHENTICATION_FAILED,
1979                                     0);
1980           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1981         }
1982       else if (sa->state == IKEV2_STATE_TS_UNACCEPTABLE)
1983         {
1984           ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_TS_UNACCEPTABLE,
1985                                     0);
1986           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
1987           ikev2_payload_add_auth (chain, &sa->r_auth);
1988         }
1989       else if (sa->state == IKEV2_STATE_NO_PROPOSAL_CHOSEN)
1990         {
1991           ikev2_payload_add_notify (chain,
1992                                     IKEV2_NOTIFY_MSG_NO_PROPOSAL_CHOSEN, 0);
1993           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
1994           ikev2_payload_add_auth (chain, &sa->r_auth);
1995           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
1996           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
1997         }
1998       else if (sa->state == IKEV2_STATE_NOTIFY_AND_DELETE)
1999         {
2000           u8 *data = vec_new (u8, 1);
2001
2002           data[0] = sa->unsupported_cp;
2003           ikev2_payload_add_notify (chain,
2004                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2005                                     data);
2006           vec_free (data);
2007         }
2008       else if (sa->state == IKEV2_STATE_SA_INIT)
2009         {
2010           ikev2_payload_add_id (chain, &sa->i_id, IKEV2_PAYLOAD_IDI);
2011           ikev2_payload_add_auth (chain, &sa->i_auth);
2012           ikev2_payload_add_sa (chain, sa->childs[0].i_proposals);
2013           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
2014           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
2015           ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_INITIAL_CONTACT,
2016                                     0);
2017         }
2018       else
2019         {
2020           ikev2_set_state (sa, IKEV2_STATE_DELETED);
2021           goto done;
2022         }
2023     }
2024   else if (ike->exchange == IKEV2_EXCHANGE_INFORMATIONAL)
2025     {
2026       /* if pending delete */
2027       if (sa->del)
2028         {
2029           if (sa->del[0].protocol_id == IKEV2_PROTOCOL_IKE)
2030             {
2031               if (sa->is_initiator)
2032                 ikev2_payload_add_delete (chain, sa->del);
2033
2034               /* The response to a request that deletes the IKE SA is an empty
2035                  INFORMATIONAL response. */
2036               ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
2037             }
2038           /* The response to a request that deletes ESP or AH SAs will contain
2039              delete payloads for the paired SAs going in the other direction. */
2040           else
2041             {
2042               ikev2_payload_add_delete (chain, sa->del);
2043             }
2044           vec_free (sa->del);
2045           sa->del = 0;
2046         }
2047       /* received N(AUTHENTICATION_FAILED) */
2048       else if (sa->state == IKEV2_STATE_AUTH_FAILED)
2049         {
2050           ikev2_set_state (sa, IKEV2_STATE_DELETED);
2051           goto done;
2052         }
2053       /* received unsupported critical payload */
2054       else if (sa->unsupported_cp)
2055         {
2056           u8 *data = vec_new (u8, 1);
2057
2058           data[0] = sa->unsupported_cp;
2059           ikev2_payload_add_notify (chain,
2060                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2061                                     data);
2062           vec_free (data);
2063           sa->unsupported_cp = 0;
2064         }
2065       /* else send empty response */
2066     }
2067   else if (ike->exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
2068     {
2069       if (sa->is_initiator)
2070         {
2071
2072           ikev2_sa_proposal_t *proposals = (ikev2_sa_proposal_t *) user;
2073           ikev2_notify_t notify;
2074           u8 *data = vec_new (u8, 4);
2075           clib_memset (&notify, 0, sizeof (notify));
2076           notify.protocol_id = IKEV2_PROTOCOL_ESP;
2077           notify.spi = sa->childs[0].i_proposals->spi;
2078           *(u32 *) data = clib_host_to_net_u32 (notify.spi);
2079
2080           ikev2_payload_add_sa (chain, proposals);
2081           ikev2_payload_add_nonce (chain, sa->i_nonce);
2082           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
2083           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
2084           ikev2_payload_add_notify_2 (chain, IKEV2_NOTIFY_MSG_REKEY_SA, data,
2085                                       &notify);
2086
2087           vec_free (data);
2088         }
2089       else
2090         {
2091           if (sa->rekey)
2092             {
2093               ikev2_payload_add_sa (chain, sa->rekey[0].r_proposal);
2094               ikev2_payload_add_nonce (chain, sa->r_nonce);
2095               ikev2_payload_add_ts (chain, sa->rekey[0].tsi,
2096                                     IKEV2_PAYLOAD_TSI);
2097               ikev2_payload_add_ts (chain, sa->rekey[0].tsr,
2098                                     IKEV2_PAYLOAD_TSR);
2099               vec_del1 (sa->rekey, 0);
2100             }
2101           else if (sa->unsupported_cp)
2102             {
2103               u8 *data = vec_new (u8, 1);
2104
2105               data[0] = sa->unsupported_cp;
2106               ikev2_payload_add_notify (chain,
2107                                         IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2108                                         data);
2109               vec_free (data);
2110               sa->unsupported_cp = 0;
2111             }
2112           else
2113             {
2114               ikev2_payload_add_notify (chain,
2115                                         IKEV2_NOTIFY_MSG_NO_ADDITIONAL_SAS,
2116                                         0);
2117             }
2118         }
2119     }
2120
2121   /* IKEv2 header */
2122   ike->version = IKE_VERSION_2;
2123   ike->nextpayload = IKEV2_PAYLOAD_SK;
2124   tlen = sizeof (*ike);
2125   if (sa->is_initiator)
2126     {
2127       ike->flags = IKEV2_HDR_FLAG_INITIATOR;
2128       sa->last_init_msg_id = clib_net_to_host_u32 (ike->msgid);
2129     }
2130   else
2131     {
2132       ike->flags = IKEV2_HDR_FLAG_RESPONSE;
2133     }
2134
2135
2136   if (ike->exchange == IKEV2_EXCHANGE_SA_INIT)
2137     {
2138       tlen += vec_len (chain->data);
2139       ike->nextpayload = chain->first_payload_type;
2140       ike->length = clib_host_to_net_u32 (tlen);
2141       clib_memcpy_fast (ike->payload, chain->data, vec_len (chain->data));
2142
2143       /* store whole IKE payload - needed for PSK auth */
2144       vec_free (sa->last_sa_init_res_packet_data);
2145       vec_add (sa->last_sa_init_res_packet_data, ike, tlen);
2146     }
2147   else
2148     {
2149
2150       ikev2_payload_chain_add_padding (chain, tr_encr->block_size);
2151
2152       /* SK payload */
2153       plen = sizeof (*ph);
2154       ph = (ike_payload_header_t *) & ike->payload[0];
2155       ph->nextpayload = chain->first_payload_type;
2156       ph->flags = 0;
2157       int enc_len = ikev2_encrypt_data (sa, chain->data, ph->payload);
2158       plen += enc_len;
2159
2160       /* add space for hmac */
2161       plen += tr_integ->key_trunc;
2162       tlen += plen;
2163
2164       /* payload and total length */
2165       ph->length = clib_host_to_net_u16 (plen);
2166       ike->length = clib_host_to_net_u32 (tlen);
2167
2168       /* calc integrity data for whole packet except hash itself */
2169       integ =
2170         ikev2_calc_integr (tr_integ, sa->is_initiator ? sa->sk_ai : sa->sk_ar,
2171                            (u8 *) ike, tlen - tr_integ->key_trunc);
2172
2173       clib_memcpy_fast (ike->payload + tlen - tr_integ->key_trunc -
2174                         sizeof (*ike), integ, tr_integ->key_trunc);
2175
2176       /* store whole IKE payload - needed for retransmit */
2177       vec_free (sa->last_res_packet_data);
2178       vec_add (sa->last_res_packet_data, ike, tlen);
2179     }
2180
2181 done:
2182   ikev2_payload_destroy_chain (chain);
2183   vec_free (integ);
2184   return tlen;
2185 }
2186
2187 static int
2188 ikev2_retransmit_sa_init (ike_header_t * ike,
2189                           ip4_address_t iaddr, ip4_address_t raddr)
2190 {
2191   ikev2_main_t *km = &ikev2_main;
2192   ikev2_sa_t *sa;
2193   u32 thread_index = vlib_get_thread_index ();
2194
2195   /* *INDENT-OFF* */
2196   pool_foreach (sa, km->per_thread_data[thread_index].sas, ({
2197     if (sa->ispi == clib_net_to_host_u64(ike->ispi) &&
2198         sa->iaddr.as_u32 == iaddr.as_u32 &&
2199         sa->raddr.as_u32 == raddr.as_u32)
2200       {
2201         int p = 0;
2202         u32 len = clib_net_to_host_u32(ike->length);
2203         u8 payload = ike->nextpayload;
2204
2205         while (p < len && payload!= IKEV2_PAYLOAD_NONE) {
2206           ike_payload_header_t * ikep = (ike_payload_header_t *) &ike->payload[p];
2207           u32 plen = clib_net_to_host_u16(ikep->length);
2208
2209           if (plen < sizeof(ike_payload_header_t))
2210             return -1;
2211
2212           if (payload == IKEV2_PAYLOAD_NONCE)
2213             {
2214               if (!memcmp(sa->i_nonce, ikep->payload, plen - sizeof(*ikep)))
2215                 {
2216                   /* req is retransmit */
2217                   if (sa->state == IKEV2_STATE_SA_INIT)
2218                     {
2219                       ike_header_t * tmp;
2220                       tmp = (ike_header_t*)sa->last_sa_init_res_packet_data;
2221                       ike->ispi = tmp->ispi;
2222                       ike->rspi = tmp->rspi;
2223                       ike->nextpayload = tmp->nextpayload;
2224                       ike->version = tmp->version;
2225                       ike->exchange = tmp->exchange;
2226                       ike->flags = tmp->flags;
2227                       ike->msgid = tmp->msgid;
2228                       ike->length = tmp->length;
2229                       clib_memcpy_fast(ike->payload, tmp->payload,
2230                              clib_net_to_host_u32(tmp->length) - sizeof(*ike));
2231                       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG,
2232                                              "ispi %lx IKE_SA_INIT retransmit "
2233                                              "from %d.%d.%d.%d to %d.%d.%d.%d",
2234                                              ike->ispi,
2235                                              raddr.as_u32, iaddr.as_u32);
2236                       return 1;
2237                     }
2238                   /* else ignore req */
2239                   else
2240                     {
2241                       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG,
2242                                              "ispi %lx IKE_SA_INIT ignore "
2243                                              "from %d.%d.%d.%d to %d.%d.%d.%d",
2244                                              ike->ispi,
2245                                              raddr.as_u32, iaddr.as_u32);
2246                       return -1;
2247                     }
2248                 }
2249             }
2250           payload = ikep->nextpayload;
2251           p+=plen;
2252         }
2253       }
2254   }));
2255   /* *INDENT-ON* */
2256
2257   /* req is not retransmit */
2258   return 0;
2259 }
2260
2261 static int
2262 ikev2_retransmit_resp (ikev2_sa_t * sa, ike_header_t * ike)
2263 {
2264   u32 msg_id = clib_net_to_host_u32 (ike->msgid);
2265
2266   /* new req */
2267   if (msg_id > sa->last_msg_id)
2268     {
2269       sa->last_msg_id = msg_id;
2270       return 0;
2271     }
2272   /* retransmitted req */
2273   else if (msg_id == sa->last_msg_id)
2274     {
2275       ike_header_t *tmp;
2276       tmp = (ike_header_t *) sa->last_res_packet_data;
2277       ike->ispi = tmp->ispi;
2278       ike->rspi = tmp->rspi;
2279       ike->nextpayload = tmp->nextpayload;
2280       ike->version = tmp->version;
2281       ike->exchange = tmp->exchange;
2282       ike->flags = tmp->flags;
2283       ike->msgid = tmp->msgid;
2284       ike->length = tmp->length;
2285       clib_memcpy_fast (ike->payload, tmp->payload,
2286                         clib_net_to_host_u32 (tmp->length) - sizeof (*ike));
2287       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG, "IKE retransmit msgid %d",
2288                              msg_id, sa->raddr.as_u32, sa->iaddr.as_u32);
2289       return 1;
2290     }
2291   /* old req ignore */
2292   else
2293     {
2294       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG, "IKE req ignore msgid %d",
2295                              msg_id, sa->raddr.as_u32, sa->iaddr.as_u32);
2296     }
2297   return -1;
2298 }
2299
2300
2301 static uword
2302 ikev2_node_fn (vlib_main_t * vm,
2303                vlib_node_runtime_t * node, vlib_frame_t * frame)
2304 {
2305   u32 n_left_from, *from, *to_next;
2306   ikev2_next_t next_index;
2307   ikev2_main_t *km = &ikev2_main;
2308   u32 thread_index = vlib_get_thread_index ();
2309
2310   from = vlib_frame_vector_args (frame);
2311   n_left_from = frame->n_vectors;
2312   next_index = node->cached_next_index;
2313
2314   while (n_left_from > 0)
2315     {
2316       u32 n_left_to_next;
2317
2318       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2319
2320       while (n_left_from > 0 && n_left_to_next > 0)
2321         {
2322           u32 bi0;
2323           vlib_buffer_t *b0;
2324           u32 next0 = IKEV2_NEXT_ERROR_DROP;
2325           u32 sw_if_index0;
2326           ip4_header_t *ip40;
2327           udp_header_t *udp0;
2328           ike_header_t *ike0;
2329           ikev2_sa_t *sa0 = 0;
2330           ikev2_sa_t sa;        /* temporary store for SA */
2331           int len = 0;
2332           int r;
2333
2334           /* speculatively enqueue b0 to the current next frame */
2335           bi0 = from[0];
2336           to_next[0] = bi0;
2337           from += 1;
2338           to_next += 1;
2339           n_left_from -= 1;
2340           n_left_to_next -= 1;
2341
2342           b0 = vlib_get_buffer (vm, bi0);
2343           ike0 = vlib_buffer_get_current (b0);
2344           vlib_buffer_advance (b0, -sizeof (*udp0));
2345           udp0 = vlib_buffer_get_current (b0);
2346           vlib_buffer_advance (b0, -sizeof (*ip40));
2347           ip40 = vlib_buffer_get_current (b0);
2348
2349           if (ike0->version != IKE_VERSION_2)
2350             {
2351               vlib_node_increment_counter (vm, ikev2_node.index,
2352                                            IKEV2_ERROR_NOT_IKEV2, 1);
2353               goto dispatch0;
2354             }
2355
2356           if (ike0->exchange == IKEV2_EXCHANGE_SA_INIT)
2357             {
2358               sa0 = &sa;
2359               clib_memset (sa0, 0, sizeof (*sa0));
2360
2361               if (ike0->flags & IKEV2_HDR_FLAG_INITIATOR)
2362                 {
2363                   if (ike0->rspi == 0)
2364                     {
2365                       sa0->raddr.as_u32 = ip40->dst_address.as_u32;
2366                       sa0->iaddr.as_u32 = ip40->src_address.as_u32;
2367
2368                       r = ikev2_retransmit_sa_init (ike0, sa0->iaddr,
2369                                                     sa0->raddr);
2370                       if (r == 1)
2371                         {
2372                           vlib_node_increment_counter (vm, ikev2_node.index,
2373                                                        IKEV2_ERROR_IKE_SA_INIT_RETRANSMIT,
2374                                                        1);
2375                           len = clib_net_to_host_u32 (ike0->length);
2376                           goto dispatch0;
2377                         }
2378                       else if (r == -1)
2379                         {
2380                           vlib_node_increment_counter (vm, ikev2_node.index,
2381                                                        IKEV2_ERROR_IKE_SA_INIT_IGNORE,
2382                                                        1);
2383                           goto dispatch0;
2384                         }
2385
2386                       ikev2_process_sa_init_req (vm, sa0, ike0);
2387
2388                       if (sa0->state == IKEV2_STATE_SA_INIT)
2389                         {
2390                           ikev2_sa_free_proposal_vector (&sa0->r_proposals);
2391                           sa0->r_proposals =
2392                             ikev2_select_proposal (sa0->i_proposals,
2393                                                    IKEV2_PROTOCOL_IKE);
2394                           ikev2_generate_sa_init_data (sa0);
2395                         }
2396
2397                       if (sa0->state == IKEV2_STATE_SA_INIT
2398                           || sa0->state == IKEV2_STATE_NOTIFY_AND_DELETE)
2399                         {
2400                           len = ikev2_generate_message (sa0, ike0, 0);
2401                         }
2402
2403                       if (sa0->state == IKEV2_STATE_SA_INIT)
2404                         {
2405                           /* add SA to the pool */
2406                           pool_get (km->per_thread_data[thread_index].sas,
2407                                     sa0);
2408                           clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
2409                           hash_set (km->
2410                                     per_thread_data[thread_index].sa_by_rspi,
2411                                     sa0->rspi,
2412                                     sa0 -
2413                                     km->per_thread_data[thread_index].sas);
2414                         }
2415                       else
2416                         {
2417                           ikev2_sa_free_all_vec (sa0);
2418                         }
2419                     }
2420                 }
2421               else              //received sa_init without initiator flag
2422                 {
2423                   ikev2_process_sa_init_resp (vm, sa0, ike0);
2424
2425                   if (sa0->state == IKEV2_STATE_SA_INIT)
2426                     {
2427                       ike0->exchange = IKEV2_EXCHANGE_IKE_AUTH;
2428                       uword *p = hash_get (km->sa_by_ispi, ike0->ispi);
2429                       if (p)
2430                         {
2431                           ikev2_sa_t *sai =
2432                             pool_elt_at_index (km->sais, p[0]);
2433
2434                           ikev2_complete_sa_data (sa0, sai);
2435                           ikev2_calc_keys (sa0);
2436                           ikev2_sa_auth_init (sa0);
2437                           len = ikev2_generate_message (sa0, ike0, 0);
2438                         }
2439                     }
2440
2441                   if (sa0->state == IKEV2_STATE_SA_INIT)
2442                     {
2443                       /* add SA to the pool */
2444                       pool_get (km->per_thread_data[thread_index].sas, sa0);
2445                       clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
2446                       hash_set (km->per_thread_data[thread_index].sa_by_rspi,
2447                                 sa0->rspi,
2448                                 sa0 - km->per_thread_data[thread_index].sas);
2449                     }
2450                   else
2451                     {
2452                       ikev2_sa_free_all_vec (sa0);
2453                     }
2454                 }
2455             }
2456           else if (ike0->exchange == IKEV2_EXCHANGE_IKE_AUTH)
2457             {
2458               uword *p;
2459               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2460                             clib_net_to_host_u64 (ike0->rspi));
2461               if (p)
2462                 {
2463                   sa0 =
2464                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2465                                        p[0]);
2466
2467                   r = ikev2_retransmit_resp (sa0, ike0);
2468                   if (r == 1)
2469                     {
2470                       vlib_node_increment_counter (vm, ikev2_node.index,
2471                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2472                                                    1);
2473                       len = clib_net_to_host_u32 (ike0->length);
2474                       goto dispatch0;
2475                     }
2476                   else if (r == -1)
2477                     {
2478                       vlib_node_increment_counter (vm, ikev2_node.index,
2479                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2480                                                    1);
2481                       goto dispatch0;
2482                     }
2483
2484                   ikev2_process_auth_req (vm, sa0, ike0);
2485                   ikev2_sa_auth (sa0);
2486                   if (sa0->state == IKEV2_STATE_AUTHENTICATED)
2487                     {
2488                       ikev2_initial_contact_cleanup (sa0);
2489                       ikev2_sa_match_ts (sa0);
2490                       if (sa0->state != IKEV2_STATE_TS_UNACCEPTABLE)
2491                         ikev2_create_tunnel_interface (km->vnet_main,
2492                                                        thread_index, sa0,
2493                                                        &sa0->childs[0],
2494                                                        p[0], 0, 0);
2495                     }
2496
2497                   if (sa0->is_initiator)
2498                     {
2499                       uword *p = hash_get (km->sa_by_ispi, ike0->ispi);
2500                       if (p)
2501                         {
2502                           ikev2_sa_t *sai =
2503                             pool_elt_at_index (km->sais, p[0]);
2504                           hash_unset (km->sa_by_ispi, sai->ispi);
2505                           ikev2_sa_free_all_vec (sai);
2506                           pool_put (km->sais, sai);
2507                         }
2508                     }
2509                   else
2510                     {
2511                       len = ikev2_generate_message (sa0, ike0, 0);
2512                     }
2513                 }
2514             }
2515           else if (ike0->exchange == IKEV2_EXCHANGE_INFORMATIONAL)
2516             {
2517               uword *p;
2518               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2519                             clib_net_to_host_u64 (ike0->rspi));
2520               if (p)
2521                 {
2522                   sa0 =
2523                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2524                                        p[0]);
2525
2526                   r = ikev2_retransmit_resp (sa0, ike0);
2527                   if (r == 1)
2528                     {
2529                       vlib_node_increment_counter (vm, ikev2_node.index,
2530                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2531                                                    1);
2532                       len = clib_net_to_host_u32 (ike0->length);
2533                       goto dispatch0;
2534                     }
2535                   else if (r == -1)
2536                     {
2537                       vlib_node_increment_counter (vm, ikev2_node.index,
2538                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2539                                                    1);
2540                       goto dispatch0;
2541                     }
2542
2543                   ikev2_process_informational_req (vm, sa0, ike0);
2544                   if (sa0->del)
2545                     {
2546                       if (sa0->del[0].protocol_id != IKEV2_PROTOCOL_IKE)
2547                         {
2548                           ikev2_delete_t *d, *tmp, *resp = 0;
2549                           vec_foreach (d, sa0->del)
2550                           {
2551                             ikev2_child_sa_t *ch_sa;
2552                             ch_sa = ikev2_sa_get_child (sa0, d->spi,
2553                                                         d->protocol_id,
2554                                                         !sa0->is_initiator);
2555                             if (ch_sa)
2556                               {
2557                                 ikev2_delete_tunnel_interface (km->vnet_main,
2558                                                                sa0, ch_sa);
2559                                 if (!sa0->is_initiator)
2560                                   {
2561                                     vec_add2 (resp, tmp, 1);
2562                                     tmp->protocol_id = d->protocol_id;
2563                                     tmp->spi = ch_sa->r_proposals[0].spi;
2564                                   }
2565                                 ikev2_sa_del_child_sa (sa0, ch_sa);
2566                               }
2567                           }
2568                           if (!sa0->is_initiator)
2569                             {
2570                               vec_free (sa0->del);
2571                               sa0->del = resp;
2572                             }
2573                         }
2574                     }
2575                   if (!sa0->is_initiator)
2576                     {
2577                       len = ikev2_generate_message (sa0, ike0, 0);
2578                     }
2579                 }
2580             }
2581           else if (ike0->exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
2582             {
2583               uword *p;
2584               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2585                             clib_net_to_host_u64 (ike0->rspi));
2586               if (p)
2587                 {
2588                   sa0 =
2589                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2590                                        p[0]);
2591
2592                   r = ikev2_retransmit_resp (sa0, ike0);
2593                   if (r == 1)
2594                     {
2595                       vlib_node_increment_counter (vm, ikev2_node.index,
2596                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2597                                                    1);
2598                       len = clib_net_to_host_u32 (ike0->length);
2599                       goto dispatch0;
2600                     }
2601                   else if (r == -1)
2602                     {
2603                       vlib_node_increment_counter (vm, ikev2_node.index,
2604                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2605                                                    1);
2606                       goto dispatch0;
2607                     }
2608
2609                   ikev2_process_create_child_sa_req (vm, sa0, ike0);
2610                   if (sa0->rekey)
2611                     {
2612                       if (sa0->rekey[0].protocol_id != IKEV2_PROTOCOL_IKE)
2613                         {
2614                           if (sa0->childs)
2615                             vec_free (sa0->childs);
2616                           ikev2_child_sa_t *child;
2617                           vec_add2 (sa0->childs, child, 1);
2618                           child->r_proposals = sa0->rekey[0].r_proposal;
2619                           child->i_proposals = sa0->rekey[0].i_proposal;
2620                           child->tsi = sa0->rekey[0].tsi;
2621                           child->tsr = sa0->rekey[0].tsr;
2622                           ikev2_create_tunnel_interface (km->vnet_main,
2623                                                          thread_index, sa0,
2624                                                          child, p[0],
2625                                                          child - sa0->childs,
2626                                                          1);
2627                         }
2628                       if (sa0->is_initiator)
2629                         {
2630                           vec_del1 (sa0->rekey, 0);
2631                         }
2632                       else
2633                         {
2634                           len = ikev2_generate_message (sa0, ike0, 0);
2635                         }
2636                     }
2637                 }
2638             }
2639           else
2640             {
2641               ikev2_elog_uint_peers (IKEV2_LOG_WARNING, "IKEv2 exchange %d "
2642                                      "received from %d.%d.%d.%d to %d.%d.%d.%d",
2643                                      ike0->exchange,
2644                                      ip40->src_address.as_u32,
2645                                      ip40->dst_address.as_u32);
2646             }
2647
2648         dispatch0:
2649           /* if we are sending packet back, rewrite headers */
2650           if (len)
2651             {
2652               next0 = IKEV2_NEXT_IP4_LOOKUP;
2653               if (sa0->is_initiator)
2654                 {
2655                   ip40->dst_address.as_u32 = sa0->raddr.as_u32;
2656                   ip40->src_address.as_u32 = sa0->iaddr.as_u32;
2657                 }
2658               else
2659                 {
2660                   ip40->dst_address.as_u32 = sa0->iaddr.as_u32;
2661                   ip40->src_address.as_u32 = sa0->raddr.as_u32;
2662                 }
2663               udp0->length =
2664                 clib_host_to_net_u16 (len + sizeof (udp_header_t));
2665               udp0->checksum = 0;
2666               b0->current_length =
2667                 len + sizeof (ip4_header_t) + sizeof (udp_header_t);
2668               ip40->length = clib_host_to_net_u16 (b0->current_length);
2669               ip40->checksum = ip4_header_checksum (ip40);
2670             }
2671           /* delete sa */
2672           if (sa0 && (sa0->state == IKEV2_STATE_DELETED ||
2673                       sa0->state == IKEV2_STATE_NOTIFY_AND_DELETE))
2674             {
2675               ikev2_child_sa_t *c;
2676
2677               vec_foreach (c, sa0->childs)
2678                 ikev2_delete_tunnel_interface (km->vnet_main, sa0, c);
2679
2680               ikev2_delete_sa (sa0);
2681             }
2682           sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
2683
2684           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
2685                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
2686             {
2687               ikev2_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
2688               t->sw_if_index = sw_if_index0;
2689               t->next_index = next0;
2690             }
2691
2692           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2693                                            n_left_to_next, bi0, next0);
2694         }
2695
2696       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2697     }
2698
2699   vlib_node_increment_counter (vm, ikev2_node.index,
2700                                IKEV2_ERROR_PROCESSED, frame->n_vectors);
2701   return frame->n_vectors;
2702 }
2703
2704 /* *INDENT-OFF* */
2705 VLIB_REGISTER_NODE (ikev2_node,static) = {
2706   .function = ikev2_node_fn,
2707   .name = "ikev2",
2708   .vector_size = sizeof (u32),
2709   .format_trace = format_ikev2_trace,
2710   .type = VLIB_NODE_TYPE_INTERNAL,
2711
2712   .n_errors = ARRAY_LEN(ikev2_error_strings),
2713   .error_strings = ikev2_error_strings,
2714
2715   .n_next_nodes = IKEV2_N_NEXT,
2716
2717   .next_nodes = {
2718     [IKEV2_NEXT_IP4_LOOKUP] = "ip4-lookup",
2719         [IKEV2_NEXT_ERROR_DROP] = "error-drop",
2720   },
2721 };
2722 /* *INDENT-ON* */
2723
2724 // set ikev2 proposals when vpp is used as initiator
2725 static clib_error_t *
2726 ikev2_set_initiator_proposals (vlib_main_t * vm, ikev2_sa_t * sa,
2727                                ikev2_transforms_set * ts,
2728                                ikev2_sa_proposal_t ** proposals, int is_ike)
2729 {
2730   clib_error_t *r;
2731   ikev2_main_t *km = &ikev2_main;
2732   ikev2_sa_proposal_t *proposal;
2733   vec_add2 (*proposals, proposal, 1);
2734   ikev2_sa_transform_t *td;
2735   int error;
2736
2737   /* Encryption */
2738   error = 1;
2739   vec_foreach (td, km->supported_transforms)
2740   {
2741     if (td->type == IKEV2_TRANSFORM_TYPE_ENCR
2742         && td->encr_type == ts->crypto_alg
2743         && td->key_len == ts->crypto_key_size / 8)
2744       {
2745         u16 attr[2];
2746         attr[0] = clib_host_to_net_u16 (14 | (1 << 15));
2747         attr[1] = clib_host_to_net_u16 (td->key_len << 3);
2748         vec_add (td->attrs, (u8 *) attr, 4);
2749         vec_add1 (proposal->transforms, *td);
2750         td->attrs = 0;
2751
2752         error = 0;
2753         break;
2754       }
2755   }
2756   if (error)
2757     {
2758       r = clib_error_return (0, "Unsupported algorithm");
2759       return r;
2760     }
2761
2762   if (IKEV2_TRANSFORM_ENCR_TYPE_AES_GCM_16 != ts->crypto_alg)
2763     {
2764       /* Integrity */
2765       error = 1;
2766       vec_foreach (td, km->supported_transforms)
2767       {
2768         if (td->type == IKEV2_TRANSFORM_TYPE_INTEG
2769             && td->integ_type == ts->integ_alg)
2770           {
2771             vec_add1 (proposal->transforms, *td);
2772             error = 0;
2773             break;
2774           }
2775       }
2776       if (error)
2777         {
2778           ikev2_elog_error
2779             ("Didn't find any supported algorithm for IKEV2_TRANSFORM_TYPE_INTEG");
2780           r = clib_error_return (0, "Unsupported algorithm");
2781           return r;
2782         }
2783     }
2784
2785   /* PRF */
2786   if (is_ike)
2787     {
2788       error = 1;
2789       vec_foreach (td, km->supported_transforms)
2790       {
2791         if (td->type == IKEV2_TRANSFORM_TYPE_PRF
2792             && td->prf_type == IKEV2_TRANSFORM_PRF_TYPE_PRF_HMAC_SHA2_256)
2793           {
2794             vec_add1 (proposal->transforms, *td);
2795             error = 0;
2796             break;
2797           }
2798       }
2799       if (error)
2800         {
2801           r = clib_error_return (0, "Unsupported algorithm");
2802           return r;
2803         }
2804     }
2805
2806   /* DH */
2807   if (is_ike || ts->dh_type != IKEV2_TRANSFORM_DH_TYPE_NONE)
2808     {
2809       error = 1;
2810       vec_foreach (td, km->supported_transforms)
2811       {
2812         if (td->type == IKEV2_TRANSFORM_TYPE_DH && td->dh_type == ts->dh_type)
2813           {
2814             vec_add1 (proposal->transforms, *td);
2815             if (is_ike)
2816               {
2817                 sa->dh_group = td->dh_type;
2818               }
2819             error = 0;
2820             break;
2821           }
2822       }
2823       if (error)
2824         {
2825           r = clib_error_return (0, "Unsupported algorithm");
2826           return r;
2827         }
2828     }
2829
2830   if (!is_ike)
2831     {
2832       error = 1;
2833       vec_foreach (td, km->supported_transforms)
2834       {
2835         if (td->type == IKEV2_TRANSFORM_TYPE_ESN)
2836           {
2837             vec_add1 (proposal->transforms, *td);
2838             error = 0;
2839             break;
2840           }
2841       }
2842       if (error)
2843         {
2844           r = clib_error_return (0, "Unsupported algorithm");
2845           return r;
2846         }
2847     }
2848
2849
2850   return 0;
2851 }
2852
2853 static ikev2_profile_t *
2854 ikev2_profile_index_by_name (u8 * name)
2855 {
2856   ikev2_main_t *km = &ikev2_main;
2857   uword *p;
2858
2859   p = mhash_get (&km->profile_index_by_name, name);
2860   if (!p)
2861     return 0;
2862
2863   return pool_elt_at_index (km->profiles, p[0]);
2864 }
2865
2866
2867 static void
2868 ikev2_send_ike (vlib_main_t * vm, ip4_address_t * src, ip4_address_t * dst,
2869                 u32 bi0, u32 len)
2870 {
2871   ip4_header_t *ip40;
2872   udp_header_t *udp0;
2873   vlib_buffer_t *b0;
2874   vlib_frame_t *f;
2875   u32 *to_next;
2876
2877   b0 = vlib_get_buffer (vm, bi0);
2878   vlib_buffer_advance (b0, -sizeof (udp_header_t));
2879   udp0 = vlib_buffer_get_current (b0);
2880   vlib_buffer_advance (b0, -sizeof (ip4_header_t));
2881   ip40 = vlib_buffer_get_current (b0);
2882
2883
2884   ip40->ip_version_and_header_length = 0x45;
2885   ip40->tos = 0;
2886   ip40->fragment_id = 0;
2887   ip40->flags_and_fragment_offset = 0;
2888   ip40->ttl = 0xff;
2889   ip40->protocol = IP_PROTOCOL_UDP;
2890   ip40->dst_address.as_u32 = dst->as_u32;
2891   ip40->src_address.as_u32 = src->as_u32;
2892   udp0->dst_port = clib_host_to_net_u16 (500);
2893   udp0->src_port = clib_host_to_net_u16 (500);
2894   udp0->length = clib_host_to_net_u16 (len + sizeof (udp_header_t));
2895   udp0->checksum = 0;
2896   b0->current_length = len + sizeof (ip4_header_t) + sizeof (udp_header_t);
2897   ip40->length = clib_host_to_net_u16 (b0->current_length);
2898   ip40->checksum = ip4_header_checksum (ip40);
2899
2900
2901   /* send the request */
2902   f = vlib_get_frame_to_node (vm, ip4_lookup_node.index);
2903   to_next = vlib_frame_vector_args (f);
2904   to_next[0] = bi0;
2905   f->n_vectors = 1;
2906   vlib_put_frame_to_node (vm, ip4_lookup_node.index, f);
2907
2908 }
2909
2910 static u32
2911 ikev2_get_new_ike_header_buff (vlib_main_t * vm, ike_header_t ** ike)
2912 {
2913   u32 bi0;
2914   if (vlib_buffer_alloc (vm, &bi0, 1) != 1)
2915     {
2916       *ike = 0;
2917       return 0;
2918     }
2919   vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
2920   *ike = vlib_buffer_get_current (b0);
2921   return bi0;
2922 }
2923
2924 clib_error_t *
2925 ikev2_set_local_key (vlib_main_t * vm, u8 * file)
2926 {
2927   ikev2_main_t *km = &ikev2_main;
2928
2929   km->pkey = ikev2_load_key_file (file);
2930   if (km->pkey == NULL)
2931     return clib_error_return (0, "load key '%s' failed", file);
2932
2933   return 0;
2934 }
2935
2936 static_always_inline vnet_api_error_t
2937 ikev2_register_udp_port (ikev2_profile_t * p, u16 port)
2938 {
2939   ikev2_main_t *km = &ikev2_main;
2940   udp_dst_port_info_t *pi;
2941
2942   uword *v = hash_get (km->udp_ports, port);
2943   pi = udp_get_dst_port_info (&udp_main, port, UDP_IP4);
2944
2945   if (v)
2946     {
2947       /* IKE already uses this port, only increment reference counter */
2948       ASSERT (pi);
2949       v[0]++;
2950     }
2951   else
2952     {
2953       if (pi)
2954         return VNET_API_ERROR_UDP_PORT_TAKEN;
2955
2956       udp_register_dst_port (km->vlib_main, port,
2957                              ipsec4_tun_input_node.index, 1);
2958       hash_set (km->udp_ports, port, 1);
2959     }
2960   p->dst_port = port;
2961   return 0;
2962 }
2963
2964 static_always_inline void
2965 ikev2_unregister_udp_port (ikev2_profile_t * p)
2966 {
2967   ikev2_main_t *km = &ikev2_main;
2968   uword *v;
2969
2970   if (p->dst_port == IPSEC_UDP_PORT_NONE)
2971     return;
2972
2973   v = hash_get (km->udp_ports, p->dst_port);
2974   if (!v)
2975     return;
2976
2977   v[0]--;
2978
2979   if (v[0] == 0)
2980     {
2981       udp_unregister_dst_port (km->vlib_main, p->dst_port, 1);
2982       hash_unset (km->udp_ports, p->dst_port);
2983     }
2984
2985   p->dst_port = IPSEC_UDP_PORT_NONE;
2986 }
2987
2988 clib_error_t *
2989 ikev2_add_del_profile (vlib_main_t * vm, u8 * name, int is_add)
2990 {
2991   ikev2_main_t *km = &ikev2_main;
2992   ikev2_profile_t *p;
2993
2994   if (is_add)
2995     {
2996       if (ikev2_profile_index_by_name (name))
2997         return clib_error_return (0, "policy %v already exists", name);
2998
2999       pool_get (km->profiles, p);
3000       clib_memset (p, 0, sizeof (*p));
3001       p->name = vec_dup (name);
3002       p->dst_port = IPSEC_UDP_PORT_NONE;
3003       p->responder.sw_if_index = ~0;
3004       p->tun_itf = ~0;
3005       uword index = p - km->profiles;
3006       mhash_set_mem (&km->profile_index_by_name, name, &index, 0);
3007     }
3008   else
3009     {
3010       p = ikev2_profile_index_by_name (name);
3011       if (!p)
3012         return clib_error_return (0, "policy %v does not exists", name);
3013
3014       ikev2_unregister_udp_port (p);
3015
3016       vec_free (p->name);
3017       pool_put (km->profiles, p);
3018       mhash_unset (&km->profile_index_by_name, name, 0);
3019     }
3020   return 0;
3021 }
3022
3023 clib_error_t *
3024 ikev2_set_profile_auth (vlib_main_t * vm, u8 * name, u8 auth_method,
3025                         u8 * auth_data, u8 data_hex_format)
3026 {
3027   ikev2_profile_t *p;
3028   clib_error_t *r;
3029
3030   p = ikev2_profile_index_by_name (name);
3031
3032   if (!p)
3033     {
3034       r = clib_error_return (0, "unknown profile %v", name);
3035       return r;
3036     }
3037   vec_free (p->auth.data);
3038   p->auth.method = auth_method;
3039   p->auth.data = vec_dup (auth_data);
3040   p->auth.hex = data_hex_format;
3041
3042   if (auth_method == IKEV2_AUTH_METHOD_RSA_SIG)
3043     {
3044       vec_add1 (p->auth.data, 0);
3045       if (p->auth.key)
3046         EVP_PKEY_free (p->auth.key);
3047       p->auth.key = ikev2_load_cert_file (auth_data);
3048       if (p->auth.key == NULL)
3049         return clib_error_return (0, "load cert '%s' failed", auth_data);
3050     }
3051
3052   return 0;
3053 }
3054
3055 clib_error_t *
3056 ikev2_set_profile_id (vlib_main_t * vm, u8 * name, u8 id_type, u8 * data,
3057                       int is_local)
3058 {
3059   ikev2_profile_t *p;
3060   clib_error_t *r;
3061
3062   if (id_type > IKEV2_ID_TYPE_ID_RFC822_ADDR
3063       && id_type < IKEV2_ID_TYPE_ID_KEY_ID)
3064     {
3065       r = clib_error_return (0, "unsupported identity type %U",
3066                              format_ikev2_id_type, id_type);
3067       return r;
3068     }
3069
3070   p = ikev2_profile_index_by_name (name);
3071
3072   if (!p)
3073     {
3074       r = clib_error_return (0, "unknown profile %v", name);
3075       return r;
3076     }
3077
3078   if (is_local)
3079     {
3080       vec_free (p->loc_id.data);
3081       p->loc_id.type = id_type;
3082       p->loc_id.data = vec_dup (data);
3083     }
3084   else
3085     {
3086       vec_free (p->rem_id.data);
3087       p->rem_id.type = id_type;
3088       p->rem_id.data = vec_dup (data);
3089     }
3090
3091   return 0;
3092 }
3093
3094 clib_error_t *
3095 ikev2_set_profile_ts (vlib_main_t * vm, u8 * name, u8 protocol_id,
3096                       u16 start_port, u16 end_port, ip4_address_t start_addr,
3097                       ip4_address_t end_addr, int is_local)
3098 {
3099   ikev2_profile_t *p;
3100   clib_error_t *r;
3101
3102   p = ikev2_profile_index_by_name (name);
3103
3104   if (!p)
3105     {
3106       r = clib_error_return (0, "unknown profile %v", name);
3107       return r;
3108     }
3109
3110   if (is_local)
3111     {
3112       p->loc_ts.start_addr.as_u32 = start_addr.as_u32;
3113       p->loc_ts.end_addr.as_u32 = end_addr.as_u32;
3114       p->loc_ts.start_port = start_port;
3115       p->loc_ts.end_port = end_port;
3116       p->loc_ts.protocol_id = protocol_id;
3117       p->loc_ts.ts_type = 7;
3118     }
3119   else
3120     {
3121       p->rem_ts.start_addr.as_u32 = start_addr.as_u32;
3122       p->rem_ts.end_addr.as_u32 = end_addr.as_u32;
3123       p->rem_ts.start_port = start_port;
3124       p->rem_ts.end_port = end_port;
3125       p->rem_ts.protocol_id = protocol_id;
3126       p->rem_ts.ts_type = 7;
3127     }
3128
3129   return 0;
3130 }
3131
3132
3133 clib_error_t *
3134 ikev2_set_profile_responder (vlib_main_t * vm, u8 * name,
3135                              u32 sw_if_index, ip4_address_t ip4)
3136 {
3137   ikev2_profile_t *p;
3138   clib_error_t *r;
3139
3140   p = ikev2_profile_index_by_name (name);
3141
3142   if (!p)
3143     {
3144       r = clib_error_return (0, "unknown profile %v", name);
3145       return r;
3146     }
3147
3148   p->responder.sw_if_index = sw_if_index;
3149   p->responder.ip4 = ip4;
3150
3151   return 0;
3152 }
3153
3154 clib_error_t *
3155 ikev2_set_profile_ike_transforms (vlib_main_t * vm, u8 * name,
3156                                   ikev2_transform_encr_type_t crypto_alg,
3157                                   ikev2_transform_integ_type_t integ_alg,
3158                                   ikev2_transform_dh_type_t dh_type,
3159                                   u32 crypto_key_size)
3160 {
3161   ikev2_profile_t *p;
3162   clib_error_t *r;
3163
3164   p = ikev2_profile_index_by_name (name);
3165
3166   if (!p)
3167     {
3168       r = clib_error_return (0, "unknown profile %v", name);
3169       return r;
3170     }
3171
3172   p->ike_ts.crypto_alg = crypto_alg;
3173   p->ike_ts.integ_alg = integ_alg;
3174   p->ike_ts.dh_type = dh_type;
3175   p->ike_ts.crypto_key_size = crypto_key_size;
3176   return 0;
3177 }
3178
3179 clib_error_t *
3180 ikev2_set_profile_esp_transforms (vlib_main_t * vm, u8 * name,
3181                                   ikev2_transform_encr_type_t crypto_alg,
3182                                   ikev2_transform_integ_type_t integ_alg,
3183                                   ikev2_transform_dh_type_t dh_type,
3184                                   u32 crypto_key_size)
3185 {
3186   ikev2_profile_t *p;
3187   clib_error_t *r;
3188
3189   p = ikev2_profile_index_by_name (name);
3190
3191   if (!p)
3192     {
3193       r = clib_error_return (0, "unknown profile %v", name);
3194       return r;
3195     }
3196
3197   p->esp_ts.crypto_alg = crypto_alg;
3198   p->esp_ts.integ_alg = integ_alg;
3199   p->esp_ts.dh_type = dh_type;
3200   p->esp_ts.crypto_key_size = crypto_key_size;
3201   return 0;
3202 }
3203
3204 clib_error_t *
3205 ikev2_set_profile_tunnel_interface (vlib_main_t * vm,
3206                                     u8 * name, u32 sw_if_index)
3207 {
3208   ikev2_profile_t *p;
3209   clib_error_t *r;
3210
3211   p = ikev2_profile_index_by_name (name);
3212
3213   if (!p)
3214     {
3215       r = clib_error_return (0, "unknown profile %v", name);
3216       return r;
3217     }
3218
3219   p->tun_itf = sw_if_index;
3220
3221   return 0;
3222 }
3223
3224 vnet_api_error_t
3225 ikev2_set_profile_ipsec_udp_port (vlib_main_t * vm, u8 * name, u16 port,
3226                                   u8 is_set)
3227 {
3228   ikev2_profile_t *p = ikev2_profile_index_by_name (name);
3229   ikev2_main_t *km = &ikev2_main;
3230   vnet_api_error_t rv = 0;
3231   uword *v;
3232
3233   if (!p)
3234     return VNET_API_ERROR_INVALID_VALUE;
3235
3236   if (is_set)
3237     {
3238       if (p->dst_port != IPSEC_UDP_PORT_NONE)
3239         return VNET_API_ERROR_VALUE_EXIST;
3240
3241       rv = ikev2_register_udp_port (p, port);
3242     }
3243   else
3244     {
3245       v = hash_get (km->udp_ports, port);
3246       if (!v)
3247         return VNET_API_ERROR_IKE_NO_PORT;
3248
3249       if (p->dst_port == IPSEC_UDP_PORT_NONE)
3250         return VNET_API_ERROR_INVALID_VALUE;
3251
3252       ikev2_unregister_udp_port (p);
3253     }
3254   return rv;
3255 }
3256
3257 clib_error_t *
3258 ikev2_set_profile_udp_encap (vlib_main_t * vm, u8 * name)
3259 {
3260   ikev2_profile_t *p = ikev2_profile_index_by_name (name);
3261   clib_error_t *r;
3262
3263   if (!p)
3264     {
3265       r = clib_error_return (0, "unknown profile %v", name);
3266       return r;
3267     }
3268
3269   p->udp_encap = 1;
3270   return 0;
3271 }
3272
3273 clib_error_t *
3274 ikev2_set_profile_sa_lifetime (vlib_main_t * vm, u8 * name,
3275                                u64 lifetime, u32 jitter, u32 handover,
3276                                u64 maxdata)
3277 {
3278   ikev2_profile_t *p;
3279   clib_error_t *r;
3280
3281   p = ikev2_profile_index_by_name (name);
3282
3283   if (!p)
3284     {
3285       r = clib_error_return (0, "unknown profile %v", name);
3286       return r;
3287     }
3288
3289   p->lifetime = lifetime;
3290   p->lifetime_jitter = jitter;
3291   p->handover = handover;
3292   p->lifetime_maxdata = maxdata;
3293   return 0;
3294 }
3295
3296 clib_error_t *
3297 ikev2_initiate_sa_init (vlib_main_t * vm, u8 * name)
3298 {
3299   ikev2_profile_t *p;
3300   clib_error_t *r;
3301   ip4_main_t *im = &ip4_main;
3302   ikev2_main_t *km = &ikev2_main;
3303
3304   p = ikev2_profile_index_by_name (name);
3305
3306   if (!p)
3307     {
3308       r = clib_error_return (0, "unknown profile %v", name);
3309       return r;
3310     }
3311
3312   if (p->responder.sw_if_index == ~0 || p->responder.ip4.data_u32 == 0)
3313     {
3314       r = clib_error_return (0, "responder not set for profile %v", name);
3315       return r;
3316     }
3317
3318
3319   /* Create the Initiator Request */
3320   {
3321     ike_header_t *ike0;
3322     u32 bi0 = 0;
3323     ip_lookup_main_t *lm = &im->lookup_main;
3324     u32 if_add_index0;
3325     int len = sizeof (ike_header_t);
3326
3327     /* Get own iface IP */
3328     if_add_index0 =
3329       lm->if_address_pool_index_by_sw_if_index[p->responder.sw_if_index];
3330     ip_interface_address_t *if_add =
3331       pool_elt_at_index (lm->if_address_pool, if_add_index0);
3332     ip4_address_t *if_ip = ip_interface_address_get_address (lm, if_add);
3333
3334     bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3335
3336     /* Prepare the SA and the IKE payload */
3337     ikev2_sa_t sa;
3338     clib_memset (&sa, 0, sizeof (ikev2_sa_t));
3339     ikev2_payload_chain_t *chain = 0;
3340     ikev2_payload_new_chain (chain);
3341
3342     /* Build the IKE proposal payload */
3343     ikev2_sa_proposal_t *proposals = 0;
3344     ikev2_set_initiator_proposals (vm, &sa, &p->ike_ts, &proposals, 1);
3345     proposals[0].proposal_num = 1;
3346     proposals[0].protocol_id = IKEV2_PROTOCOL_IKE;
3347
3348     /* Add and then cleanup proposal data */
3349     ikev2_payload_add_sa (chain, proposals);
3350     ikev2_sa_free_proposal_vector (&proposals);
3351
3352     sa.is_initiator = 1;
3353     sa.profile_index = km->profiles - p;
3354     sa.is_profile_index_set = 1;
3355     sa.state = IKEV2_STATE_SA_INIT;
3356     sa.tun_itf = p->tun_itf;
3357     sa.udp_encap = p->udp_encap;
3358     sa.dst_port = p->dst_port;
3359     sa.is_tun_itf_set = 1;
3360     sa.initial_contact = 1;
3361     ikev2_generate_sa_init_data (&sa);
3362     ikev2_payload_add_ke (chain, sa.dh_group, sa.i_dh_data);
3363     ikev2_payload_add_nonce (chain, sa.i_nonce);
3364
3365     /* Build the child SA proposal */
3366     vec_resize (sa.childs, 1);
3367     ikev2_set_initiator_proposals (vm, &sa, &p->esp_ts,
3368                                    &sa.childs[0].i_proposals, 0);
3369     sa.childs[0].i_proposals[0].proposal_num = 1;
3370     sa.childs[0].i_proposals[0].protocol_id = IKEV2_PROTOCOL_ESP;
3371     RAND_bytes ((u8 *) & sa.childs[0].i_proposals[0].spi,
3372                 sizeof (sa.childs[0].i_proposals[0].spi));
3373
3374
3375
3376     /* Add NAT detection notification messages (mandatory) */
3377     u8 nat_detection_source[8 + 8 + 4 + 2];
3378     u8 *nat_detection_sha1 = vec_new (u8, 20);
3379
3380     u64 tmpspi = clib_host_to_net_u64 (sa.ispi);
3381     clib_memcpy_fast (&nat_detection_source[0], &tmpspi, sizeof (tmpspi));
3382     tmpspi = clib_host_to_net_u64 (sa.rspi);
3383     clib_memcpy_fast (&nat_detection_source[8], &tmpspi, sizeof (tmpspi));
3384     u16 tmpport = clib_host_to_net_u16 (500);
3385     clib_memcpy_fast (&nat_detection_source[8 + 8 + 4], &tmpport,
3386                       sizeof (tmpport));
3387     u32 tmpip = clib_host_to_net_u32 (if_ip->as_u32);
3388     clib_memcpy_fast (&nat_detection_source[8 + 8], &tmpip, sizeof (tmpip));
3389     SHA1 (nat_detection_source, sizeof (nat_detection_source),
3390           nat_detection_sha1);
3391     ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_NAT_DETECTION_SOURCE_IP,
3392                               nat_detection_sha1);
3393     tmpip = clib_host_to_net_u32 (p->responder.ip4.as_u32);
3394     clib_memcpy_fast (&nat_detection_source[8 + 8], &tmpip, sizeof (tmpip));
3395     SHA1 (nat_detection_source, sizeof (nat_detection_source),
3396           nat_detection_sha1);
3397     ikev2_payload_add_notify (chain,
3398                               IKEV2_NOTIFY_MSG_NAT_DETECTION_DESTINATION_IP,
3399                               nat_detection_sha1);
3400     vec_free (nat_detection_sha1);
3401
3402     u8 *sig_hash_algo = vec_new (u8, 8);
3403     u64 tmpsig = clib_host_to_net_u64 (0x0001000200030004);
3404     clib_memcpy_fast (sig_hash_algo, &tmpsig, sizeof (tmpsig));
3405     ikev2_payload_add_notify (chain,
3406                               IKEV2_NOTIFY_MSG_SIGNATURE_HASH_ALGORITHMS,
3407                               sig_hash_algo);
3408     vec_free (sig_hash_algo);
3409
3410
3411     /* Buffer update and boilerplate */
3412     len += vec_len (chain->data);
3413     ike0->nextpayload = chain->first_payload_type;
3414     ike0->length = clib_host_to_net_u32 (len);
3415     clib_memcpy_fast (ike0->payload, chain->data, vec_len (chain->data));
3416     ikev2_payload_destroy_chain (chain);
3417
3418     ike0->version = IKE_VERSION_2;
3419     ike0->flags = IKEV2_HDR_FLAG_INITIATOR;
3420     ike0->exchange = IKEV2_EXCHANGE_SA_INIT;
3421     ike0->ispi = sa.ispi;
3422     ike0->rspi = 0;
3423     ike0->msgid = 0;
3424
3425     /* store whole IKE payload - needed for PSK auth */
3426     vec_free (sa.last_sa_init_req_packet_data);
3427     vec_add (sa.last_sa_init_req_packet_data, ike0, len);
3428
3429     /* add data to the SA then add it to the pool */
3430     sa.iaddr.as_u32 = if_ip->as_u32;
3431     sa.raddr.as_u32 = p->responder.ip4.as_u32;
3432     sa.i_id.type = p->loc_id.type;
3433     sa.i_id.data = vec_dup (p->loc_id.data);
3434     sa.i_auth.method = p->auth.method;
3435     sa.i_auth.hex = p->auth.hex;
3436     sa.i_auth.data = vec_dup (p->auth.data);
3437     vec_add (sa.childs[0].tsi, &p->loc_ts, 1);
3438     vec_add (sa.childs[0].tsr, &p->rem_ts, 1);
3439
3440     ikev2_initial_contact_cleanup (&sa);
3441
3442     /* add SA to the pool */
3443     ikev2_sa_t *sa0 = 0;
3444     pool_get (km->sais, sa0);
3445     clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
3446     hash_set (km->sa_by_ispi, sa0->ispi, sa0 - km->sais);
3447
3448     ikev2_send_ike (vm, if_ip, &p->responder.ip4, bi0, len);
3449
3450     ikev2_elog_exchange ("ispi %lx rspi %lx IKEV2_EXCHANGE_SA_INIT sent to "
3451                          "%d.%d.%d.%d", clib_host_to_net_u64 (sa0->ispi), 0,
3452                          p->responder.ip4.as_u32);
3453   }
3454
3455   return 0;
3456 }
3457
3458 static void
3459 ikev2_delete_child_sa_internal (vlib_main_t * vm, ikev2_sa_t * sa,
3460                                 ikev2_child_sa_t * csa)
3461 {
3462   /* Create the Initiator notification for child SA removal */
3463   ikev2_main_t *km = &ikev2_main;
3464   ike_header_t *ike0;
3465   u32 bi0 = 0;
3466   int len;
3467
3468   bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3469
3470
3471   ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3472   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3473   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3474   vec_resize (sa->del, 1);
3475   sa->del->protocol_id = IKEV2_PROTOCOL_ESP;
3476   sa->del->spi = csa->i_proposals->spi;
3477   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3478   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3479   len = ikev2_generate_message (sa, ike0, 0);
3480
3481   ikev2_send_ike (vm, &sa->iaddr, &sa->raddr, bi0, len);
3482
3483   /* delete local child SA */
3484   ikev2_delete_tunnel_interface (km->vnet_main, sa, csa);
3485   ikev2_sa_del_child_sa (sa, csa);
3486 }
3487
3488 clib_error_t *
3489 ikev2_initiate_delete_child_sa (vlib_main_t * vm, u32 ispi)
3490 {
3491   clib_error_t *r;
3492   ikev2_main_t *km = &ikev2_main;
3493   ikev2_main_per_thread_data_t *tkm;
3494   ikev2_sa_t *fsa = 0;
3495   ikev2_child_sa_t *fchild = 0;
3496
3497   /* Search for the child SA */
3498   vec_foreach (tkm, km->per_thread_data)
3499   {
3500     ikev2_sa_t *sa;
3501     if (fchild)
3502       break;
3503     /* *INDENT-OFF* */
3504     pool_foreach (sa, tkm->sas, ({
3505       fchild = ikev2_sa_get_child(sa, ispi, IKEV2_PROTOCOL_ESP, 1);
3506       if (fchild)
3507         {
3508           fsa = sa;
3509           break;
3510         }
3511     }));
3512     /* *INDENT-ON* */
3513   }
3514
3515   if (!fchild || !fsa)
3516     {
3517       r = clib_error_return (0, "Child SA not found");
3518       return r;
3519     }
3520   else
3521     {
3522       ikev2_delete_child_sa_internal (vm, fsa, fchild);
3523     }
3524
3525   return 0;
3526 }
3527
3528 clib_error_t *
3529 ikev2_initiate_delete_ike_sa (vlib_main_t * vm, u64 ispi)
3530 {
3531   clib_error_t *r;
3532   ikev2_main_t *km = &ikev2_main;
3533   ikev2_main_per_thread_data_t *tkm;
3534   ikev2_sa_t *fsa = 0;
3535   ikev2_main_per_thread_data_t *ftkm = 0;
3536
3537   /* Search for the IKE SA */
3538   vec_foreach (tkm, km->per_thread_data)
3539   {
3540     ikev2_sa_t *sa;
3541     if (fsa)
3542       break;
3543     /* *INDENT-OFF* */
3544     pool_foreach (sa, tkm->sas, ({
3545       if (sa->ispi == ispi)
3546         {
3547           fsa = sa;
3548           ftkm = tkm;
3549           break;
3550         }
3551     }));
3552     /* *INDENT-ON* */
3553   }
3554
3555   if (!fsa)
3556     {
3557       r = clib_error_return (0, "IKE SA not found");
3558       return r;
3559     }
3560
3561
3562   /* Create the Initiator notification for IKE SA removal */
3563   {
3564     ike_header_t *ike0;
3565     u32 bi0 = 0;
3566     int len;
3567
3568     bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3569
3570
3571     ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3572     ike0->ispi = clib_host_to_net_u64 (fsa->ispi);
3573     ike0->rspi = clib_host_to_net_u64 (fsa->rspi);
3574     vec_resize (fsa->del, 1);
3575     fsa->del->protocol_id = IKEV2_PROTOCOL_IKE;
3576     fsa->del->spi = ispi;
3577     ike0->msgid = clib_host_to_net_u32 (fsa->last_init_msg_id + 1);
3578     fsa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3579     len = ikev2_generate_message (fsa, ike0, 0);
3580
3581     ikev2_send_ike (vm, &fsa->iaddr, &fsa->raddr, bi0, len);
3582   }
3583
3584
3585   /* delete local SA */
3586   ikev2_child_sa_t *c;
3587   vec_foreach (c, fsa->childs)
3588   {
3589     ikev2_delete_tunnel_interface (km->vnet_main, fsa, c);
3590     ikev2_sa_del_child_sa (fsa, c);
3591   }
3592   ikev2_sa_free_all_vec (fsa);
3593   uword *p = hash_get (ftkm->sa_by_rspi, fsa->rspi);
3594   if (p)
3595     {
3596       hash_unset (ftkm->sa_by_rspi, fsa->rspi);
3597       pool_put (ftkm->sas, fsa);
3598     }
3599
3600
3601   return 0;
3602 }
3603
3604 static void
3605 ikev2_rekey_child_sa_internal (vlib_main_t * vm, ikev2_sa_t * sa,
3606                                ikev2_child_sa_t * csa)
3607 {
3608   /* Create the Initiator request for create child SA */
3609   ike_header_t *ike0;
3610   u32 bi0 = 0;
3611   int len;
3612
3613
3614   bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3615
3616
3617   ike0->version = IKE_VERSION_2;
3618   ike0->flags = IKEV2_HDR_FLAG_INITIATOR;
3619   ike0->exchange = IKEV2_EXCHANGE_CREATE_CHILD_SA;
3620   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3621   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3622   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3623   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3624
3625   ikev2_rekey_t *rekey;
3626   vec_add2 (sa->rekey, rekey, 1);
3627   ikev2_sa_proposal_t *proposals = vec_dup (csa->i_proposals);
3628
3629   /*need new ispi */
3630   RAND_bytes ((u8 *) & proposals[0].spi, sizeof (proposals[0].spi));
3631   rekey->spi = proposals[0].spi;
3632   rekey->ispi = csa->i_proposals->spi;
3633   len = ikev2_generate_message (sa, ike0, proposals);
3634   ikev2_send_ike (vm, &sa->iaddr, &sa->raddr, bi0, len);
3635   vec_free (proposals);
3636 }
3637
3638 clib_error_t *
3639 ikev2_initiate_rekey_child_sa (vlib_main_t * vm, u32 ispi)
3640 {
3641   clib_error_t *r;
3642   ikev2_main_t *km = &ikev2_main;
3643   ikev2_main_per_thread_data_t *tkm;
3644   ikev2_sa_t *fsa = 0;
3645   ikev2_child_sa_t *fchild = 0;
3646
3647   /* Search for the child SA */
3648   vec_foreach (tkm, km->per_thread_data)
3649   {
3650     ikev2_sa_t *sa;
3651     if (fchild)
3652       break;
3653     /* *INDENT-OFF* */
3654     pool_foreach (sa, tkm->sas, ({
3655       fchild = ikev2_sa_get_child(sa, ispi, IKEV2_PROTOCOL_ESP, 1);
3656       if (fchild)
3657         {
3658           fsa = sa;
3659           break;
3660         }
3661     }));
3662     /* *INDENT-ON* */
3663   }
3664
3665   if (!fchild || !fsa)
3666     {
3667       r = clib_error_return (0, "Child SA not found");
3668       return r;
3669     }
3670   else
3671     {
3672       ikev2_rekey_child_sa_internal (vm, fsa, fchild);
3673     }
3674
3675   return 0;
3676 }
3677
3678 clib_error_t *
3679 ikev2_init (vlib_main_t * vm)
3680 {
3681   ikev2_main_t *km = &ikev2_main;
3682   vlib_thread_main_t *tm = vlib_get_thread_main ();
3683   int thread_id;
3684
3685   clib_memset (km, 0, sizeof (ikev2_main_t));
3686   km->vnet_main = vnet_get_main ();
3687   km->vlib_main = vm;
3688
3689   ikev2_crypto_init (km);
3690
3691   mhash_init_vec_string (&km->profile_index_by_name, sizeof (uword));
3692
3693   vec_validate_aligned (km->per_thread_data, tm->n_vlib_mains - 1,
3694                         CLIB_CACHE_LINE_BYTES);
3695   for (thread_id = 0; thread_id < tm->n_vlib_mains - 1; thread_id++)
3696     {
3697       km->per_thread_data[thread_id].sa_by_rspi =
3698         hash_create (0, sizeof (uword));
3699     }
3700
3701   km->sa_by_ispi = hash_create (0, sizeof (uword));
3702   km->sw_if_indices = hash_create (0, 0);
3703   km->udp_ports = hash_create (0, sizeof (uword));
3704
3705   udp_register_dst_port (vm, 500, ikev2_node.index, 1);
3706
3707   ikev2_cli_reference ();
3708
3709   km->log_level = IKEV2_LOG_ERROR;
3710   km->log_class = vlib_log_register_class ("ikev2", 0);
3711   return 0;
3712 }
3713
3714 /* *INDENT-OFF* */
3715 VLIB_INIT_FUNCTION (ikev2_init) =
3716 {
3717   .runs_after = VLIB_INITS("ipsec_init"),
3718 };
3719 /* *INDENT-ON* */
3720
3721 static u8
3722 ikev2_mngr_process_child_sa (ikev2_sa_t * sa, ikev2_child_sa_t * csa,
3723                              u8 del_old_ids)
3724 {
3725   ikev2_main_t *km = &ikev2_main;
3726   ikev2_profile_t *p = 0;
3727   vlib_main_t *vm = km->vlib_main;
3728   f64 now = vlib_time_now (vm);
3729   u8 res = 0;
3730
3731   if (sa->is_profile_index_set)
3732     p = pool_elt_at_index (km->profiles, sa->profile_index);
3733
3734   if (sa->is_initiator && p && csa->time_to_expiration
3735       && now > csa->time_to_expiration)
3736     {
3737       if (!csa->is_expired || csa->rekey_retries > 0)
3738         {
3739           ikev2_rekey_child_sa_internal (vm, sa, csa);
3740           csa->time_to_expiration = now + p->handover;
3741           csa->is_expired = 1;
3742           if (csa->rekey_retries == 0)
3743             {
3744               csa->rekey_retries = 5;
3745             }
3746           else if (csa->rekey_retries > 0)
3747             {
3748               csa->rekey_retries--;
3749               ikev2_log_debug ("Rekeying Child SA 0x%x, retries left %d",
3750                                csa->i_proposals->spi, csa->rekey_retries);
3751               if (csa->rekey_retries == 0)
3752                 {
3753                   csa->rekey_retries = -1;
3754                 }
3755             }
3756           res |= 1;
3757         }
3758       else
3759         {
3760           csa->time_to_expiration = 0;
3761           ikev2_delete_child_sa_internal (vm, sa, csa);
3762           res |= 1;
3763         }
3764     }
3765
3766   if (del_old_ids)
3767     {
3768       ipip_tunnel_t *ipip = NULL;
3769       u32 sw_if_index = sa->is_tun_itf_set ? sa->tun_itf : ~0;
3770       if (~0 == sw_if_index)
3771         {
3772           ip46_address_t local_ip;
3773           ip46_address_t remote_ip;
3774           if (sa->is_initiator)
3775             {
3776               ip46_address_set_ip4 (&local_ip, &sa->iaddr);
3777               ip46_address_set_ip4 (&remote_ip, &sa->raddr);
3778             }
3779           else
3780             {
3781               ip46_address_set_ip4 (&local_ip, &sa->raddr);
3782               ip46_address_set_ip4 (&remote_ip, &sa->iaddr);
3783             }
3784
3785        /* *INDENT-OFF* */
3786        ipip_tunnel_key_t key = {
3787          .src = local_ip,
3788          .dst = remote_ip,
3789          .transport = IPIP_TRANSPORT_IP4,
3790          .fib_index = 0,
3791        };
3792        /* *INDENT-ON* */
3793
3794           ipip = ipip_tunnel_db_find (&key);
3795
3796           if (ipip)
3797             sw_if_index = ipip->sw_if_index;
3798           else
3799             return res;
3800         }
3801
3802       u32 *sas_in = NULL;
3803       vec_add1 (sas_in, csa->remote_sa_id);
3804       ipsec_tun_protect_update (sw_if_index, NULL, csa->local_sa_id, sas_in);
3805       ipsec_sa_unlock_id (ikev2_flip_alternate_sa_bit (csa->remote_sa_id));
3806     }
3807
3808   return res;
3809 }
3810
3811 int
3812 ikev2_set_log_level (ikev2_log_level_t log_level)
3813 {
3814   ikev2_main_t *km = &ikev2_main;
3815
3816   if (log_level >= IKEV2_LOG_MAX)
3817     {
3818       ikev2_log_error ("unknown logging level %d", log_level);
3819       return -1;
3820     }
3821
3822   km->log_level = log_level;
3823   return 0;
3824 }
3825
3826 static void
3827 ikev2_mngr_process_ipsec_sa (ipsec_sa_t * ipsec_sa)
3828 {
3829   ikev2_main_t *km = &ikev2_main;
3830   vlib_main_t *vm = km->vlib_main;
3831   ikev2_main_per_thread_data_t *tkm;
3832   ikev2_sa_t *fsa = 0;
3833   ikev2_profile_t *p = 0;
3834   ikev2_child_sa_t *fchild = 0;
3835   f64 now = vlib_time_now (vm);
3836   vlib_counter_t counts;
3837
3838   /* Search for the SA and child SA */
3839   vec_foreach (tkm, km->per_thread_data)
3840   {
3841     ikev2_sa_t *sa;
3842     if (fchild)
3843       break;
3844     /* *INDENT-OFF* */
3845     pool_foreach (sa, tkm->sas, ({
3846       fchild = ikev2_sa_get_child(sa, ipsec_sa->spi, IKEV2_PROTOCOL_ESP, 1);
3847       if (fchild)
3848         {
3849           fsa = sa;
3850           break;
3851         }
3852     }));
3853     /* *INDENT-ON* */
3854   }
3855   vlib_get_combined_counter (&ipsec_sa_counters,
3856                              ipsec_sa->stat_index, &counts);
3857
3858   if (fsa && fsa->is_profile_index_set)
3859     p = pool_elt_at_index (km->profiles, fsa->profile_index);
3860
3861   if (fchild && p && p->lifetime_maxdata)
3862     {
3863       if (!fchild->is_expired && counts.bytes > p->lifetime_maxdata)
3864         {
3865           fchild->time_to_expiration = now;
3866         }
3867     }
3868 }
3869
3870 static void
3871 ikev2_process_pending_sa_init (ikev2_main_t * km)
3872 {
3873   u32 sai;
3874   u64 ispi;
3875   ikev2_sa_t *sa;
3876
3877   /* *INDENT-OFF* */
3878   hash_foreach (ispi, sai, km->sa_by_ispi,
3879   ({
3880     sa = pool_elt_at_index (km->sais, sai);
3881     u32 bi0;
3882     if (vlib_buffer_alloc (km->vlib_main, &bi0, 1) != 1)
3883       return;
3884
3885     vlib_buffer_t * b = vlib_get_buffer (km->vlib_main, bi0);
3886     clib_memcpy_fast (vlib_buffer_get_current (b),
3887         sa->last_sa_init_req_packet_data,
3888         vec_len (sa->last_sa_init_req_packet_data));
3889     ikev2_send_ike (km->vlib_main, &sa->iaddr, &sa->raddr, bi0,
3890         vec_len (sa->last_sa_init_req_packet_data));
3891   }));
3892   /* *INDENT-ON* */
3893 }
3894
3895 static vlib_node_registration_t ikev2_mngr_process_node;
3896
3897 static uword
3898 ikev2_mngr_process_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
3899                        vlib_frame_t * f)
3900 {
3901   ikev2_main_t *km = &ikev2_main;
3902   ipsec_main_t *im = &ipsec_main;
3903
3904   while (1)
3905     {
3906       u8 req_sent = 0;
3907       vlib_process_wait_for_event_or_clock (vm, 1);
3908       vlib_process_get_events (vm, NULL);
3909
3910       /* process ike child sas */
3911       ikev2_main_per_thread_data_t *tkm;
3912       vec_foreach (tkm, km->per_thread_data)
3913       {
3914         ikev2_sa_t *sa;
3915         /* *INDENT-OFF* */
3916         pool_foreach (sa, tkm->sas, ({
3917           ikev2_child_sa_t *c;
3918           u8 del_old_ids = 0;
3919           if (sa->old_remote_id_present && 0 > sa->old_id_expiration)
3920             {
3921               sa->old_remote_id_present = 0;
3922               del_old_ids = 1;
3923             }
3924           else
3925             sa->old_id_expiration -= 1;
3926
3927           vec_foreach (c, sa->childs)
3928             {
3929             req_sent |= ikev2_mngr_process_child_sa(sa, c, del_old_ids);
3930             }
3931         }));
3932         /* *INDENT-ON* */
3933       }
3934
3935       /* process ipsec sas */
3936       ipsec_sa_t *sa;
3937       /* *INDENT-OFF* */
3938       pool_foreach (sa, im->sad, ({
3939         ikev2_mngr_process_ipsec_sa(sa);
3940       }));
3941       /* *INDENT-ON* */
3942
3943       ikev2_process_pending_sa_init (km);
3944
3945       if (req_sent)
3946         {
3947           vlib_process_wait_for_event_or_clock (vm, 5);
3948           vlib_process_get_events (vm, NULL);
3949           req_sent = 0;
3950         }
3951
3952     }
3953   return 0;
3954 }
3955
3956 /* *INDENT-OFF* */
3957 VLIB_REGISTER_NODE (ikev2_mngr_process_node, static) = {
3958     .function = ikev2_mngr_process_fn,
3959     .type = VLIB_NODE_TYPE_PROCESS,
3960     .name =
3961     "ikev2-manager-process",
3962 };
3963
3964 VLIB_PLUGIN_REGISTER () = {
3965     .version = VPP_BUILD_VER,
3966     .description = "Internet Key Exchange (IKEv2) Protocol",
3967 };
3968 /* *INDENT-ON* */
3969
3970 /*
3971  * fd.io coding-style-patch-verification: ON
3972  *
3973  * Local Variables:
3974  * eval: (c-set-style "gnu")
3975  * End:
3976  */