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