ikev2: fix wrong usage of BN_bn2bin()
[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                   len = ikev2_generate_message (sa0, ike0, 0);
2599                 }
2600             }
2601           else if (ike0->exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
2602             {
2603               uword *p;
2604               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2605                             clib_net_to_host_u64 (ike0->rspi));
2606               if (p)
2607                 {
2608                   sa0 =
2609                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2610                                        p[0]);
2611
2612                   r = ikev2_retransmit_resp (sa0, ike0);
2613                   if (r == 1)
2614                     {
2615                       vlib_node_increment_counter (vm, ikev2_node.index,
2616                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2617                                                    1);
2618                       len = clib_net_to_host_u32 (ike0->length);
2619                       goto dispatch0;
2620                     }
2621                   else if (r == -1)
2622                     {
2623                       vlib_node_increment_counter (vm, ikev2_node.index,
2624                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2625                                                    1);
2626                       goto dispatch0;
2627                     }
2628
2629                   ikev2_process_create_child_sa_req (vm, sa0, ike0);
2630                   if (sa0->rekey)
2631                     {
2632                       if (sa0->rekey[0].protocol_id != IKEV2_PROTOCOL_IKE)
2633                         {
2634                           if (sa0->childs)
2635                             vec_free (sa0->childs);
2636                           ikev2_child_sa_t *child;
2637                           vec_add2 (sa0->childs, child, 1);
2638                           child->r_proposals = sa0->rekey[0].r_proposal;
2639                           child->i_proposals = sa0->rekey[0].i_proposal;
2640                           child->tsi = sa0->rekey[0].tsi;
2641                           child->tsr = sa0->rekey[0].tsr;
2642                           ikev2_create_tunnel_interface (km->vnet_main,
2643                                                          thread_index, sa0,
2644                                                          child, p[0],
2645                                                          child - sa0->childs,
2646                                                          1);
2647                         }
2648                       if (sa0->is_initiator)
2649                         {
2650                           vec_del1 (sa0->rekey, 0);
2651                         }
2652                       else
2653                         {
2654                           len = ikev2_generate_message (sa0, ike0, 0);
2655                         }
2656                     }
2657                 }
2658             }
2659           else
2660             {
2661               ikev2_elog_uint_peers (IKEV2_LOG_WARNING, "IKEv2 exchange %d "
2662                                      "received from %d.%d.%d.%d to %d.%d.%d.%d",
2663                                      ike0->exchange,
2664                                      ip40->src_address.as_u32,
2665                                      ip40->dst_address.as_u32);
2666             }
2667
2668         dispatch0:
2669           /* if we are sending packet back, rewrite headers */
2670           if (len)
2671             {
2672               next0 = IKEV2_NEXT_IP4_LOOKUP;
2673               if (sa0->is_initiator)
2674                 {
2675                   ip40->dst_address.as_u32 = sa0->raddr.as_u32;
2676                   ip40->src_address.as_u32 = sa0->iaddr.as_u32;
2677                 }
2678               else
2679                 {
2680                   ip40->dst_address.as_u32 = sa0->iaddr.as_u32;
2681                   ip40->src_address.as_u32 = sa0->raddr.as_u32;
2682                 }
2683               udp0->length =
2684                 clib_host_to_net_u16 (len + sizeof (udp_header_t));
2685               udp0->checksum = 0;
2686               b0->current_length =
2687                 len + sizeof (ip4_header_t) + sizeof (udp_header_t);
2688               ip40->length = clib_host_to_net_u16 (b0->current_length);
2689               ip40->checksum = ip4_header_checksum (ip40);
2690             }
2691           /* delete sa */
2692           if (sa0 && (sa0->state == IKEV2_STATE_DELETED ||
2693                       sa0->state == IKEV2_STATE_NOTIFY_AND_DELETE))
2694             {
2695               ikev2_child_sa_t *c;
2696
2697               vec_foreach (c, sa0->childs)
2698                 ikev2_delete_tunnel_interface (km->vnet_main, sa0, c);
2699
2700               ikev2_delete_sa (sa0);
2701             }
2702           sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
2703
2704           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
2705                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
2706             {
2707               ikev2_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
2708               t->sw_if_index = sw_if_index0;
2709               t->next_index = next0;
2710             }
2711
2712           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2713                                            n_left_to_next, bi0, next0);
2714         }
2715
2716       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2717     }
2718
2719   vlib_node_increment_counter (vm, ikev2_node.index,
2720                                IKEV2_ERROR_PROCESSED, frame->n_vectors);
2721   return frame->n_vectors;
2722 }
2723
2724 /* *INDENT-OFF* */
2725 VLIB_REGISTER_NODE (ikev2_node,static) = {
2726   .function = ikev2_node_fn,
2727   .name = "ikev2",
2728   .vector_size = sizeof (u32),
2729   .format_trace = format_ikev2_trace,
2730   .type = VLIB_NODE_TYPE_INTERNAL,
2731
2732   .n_errors = ARRAY_LEN(ikev2_error_strings),
2733   .error_strings = ikev2_error_strings,
2734
2735   .n_next_nodes = IKEV2_N_NEXT,
2736
2737   .next_nodes = {
2738     [IKEV2_NEXT_IP4_LOOKUP] = "ip4-lookup",
2739         [IKEV2_NEXT_ERROR_DROP] = "error-drop",
2740   },
2741 };
2742 /* *INDENT-ON* */
2743
2744 // set ikev2 proposals when vpp is used as initiator
2745 static clib_error_t *
2746 ikev2_set_initiator_proposals (vlib_main_t * vm, ikev2_sa_t * sa,
2747                                ikev2_transforms_set * ts,
2748                                ikev2_sa_proposal_t ** proposals, int is_ike)
2749 {
2750   clib_error_t *r;
2751   ikev2_main_t *km = &ikev2_main;
2752   ikev2_sa_proposal_t *proposal;
2753   vec_add2 (*proposals, proposal, 1);
2754   ikev2_sa_transform_t *td;
2755   int error;
2756
2757   /* Encryption */
2758   error = 1;
2759   vec_foreach (td, km->supported_transforms)
2760   {
2761     if (td->type == IKEV2_TRANSFORM_TYPE_ENCR
2762         && td->encr_type == ts->crypto_alg
2763         && td->key_len == ts->crypto_key_size / 8)
2764       {
2765         u16 attr[2];
2766         attr[0] = clib_host_to_net_u16 (14 | (1 << 15));
2767         attr[1] = clib_host_to_net_u16 (td->key_len << 3);
2768         vec_add (td->attrs, (u8 *) attr, 4);
2769         vec_add1 (proposal->transforms, *td);
2770         td->attrs = 0;
2771
2772         error = 0;
2773         break;
2774       }
2775   }
2776   if (error)
2777     {
2778       r = clib_error_return (0, "Unsupported algorithm");
2779       return r;
2780     }
2781
2782   if (is_ike || IKEV2_TRANSFORM_ENCR_TYPE_AES_GCM_16 != ts->crypto_alg)
2783     {
2784       /* Integrity */
2785       error = 1;
2786       vec_foreach (td, km->supported_transforms)
2787       {
2788         if (td->type == IKEV2_TRANSFORM_TYPE_INTEG
2789             && td->integ_type == ts->integ_alg)
2790           {
2791             vec_add1 (proposal->transforms, *td);
2792             error = 0;
2793             break;
2794           }
2795       }
2796       if (error)
2797         {
2798           ikev2_elog_error
2799             ("Didn't find any supported algorithm for IKEV2_TRANSFORM_TYPE_INTEG");
2800           r = clib_error_return (0, "Unsupported algorithm");
2801           return r;
2802         }
2803     }
2804
2805   /* PRF */
2806   if (is_ike)
2807     {
2808       error = 1;
2809       vec_foreach (td, km->supported_transforms)
2810       {
2811         if (td->type == IKEV2_TRANSFORM_TYPE_PRF
2812             && td->prf_type == IKEV2_TRANSFORM_PRF_TYPE_PRF_HMAC_SHA2_256)
2813           {
2814             vec_add1 (proposal->transforms, *td);
2815             error = 0;
2816             break;
2817           }
2818       }
2819       if (error)
2820         {
2821           r = clib_error_return (0, "Unsupported algorithm");
2822           return r;
2823         }
2824     }
2825
2826   /* DH */
2827   if (is_ike || ts->dh_type != IKEV2_TRANSFORM_DH_TYPE_NONE)
2828     {
2829       error = 1;
2830       vec_foreach (td, km->supported_transforms)
2831       {
2832         if (td->type == IKEV2_TRANSFORM_TYPE_DH && td->dh_type == ts->dh_type)
2833           {
2834             vec_add1 (proposal->transforms, *td);
2835             if (is_ike)
2836               {
2837                 sa->dh_group = td->dh_type;
2838               }
2839             error = 0;
2840             break;
2841           }
2842       }
2843       if (error)
2844         {
2845           r = clib_error_return (0, "Unsupported algorithm");
2846           return r;
2847         }
2848     }
2849
2850   if (!is_ike)
2851     {
2852       error = 1;
2853       vec_foreach (td, km->supported_transforms)
2854       {
2855         if (td->type == IKEV2_TRANSFORM_TYPE_ESN)
2856           {
2857             vec_add1 (proposal->transforms, *td);
2858             error = 0;
2859             break;
2860           }
2861       }
2862       if (error)
2863         {
2864           r = clib_error_return (0, "Unsupported algorithm");
2865           return r;
2866         }
2867     }
2868
2869
2870   return 0;
2871 }
2872
2873 static ikev2_profile_t *
2874 ikev2_profile_index_by_name (u8 * name)
2875 {
2876   ikev2_main_t *km = &ikev2_main;
2877   uword *p;
2878
2879   p = mhash_get (&km->profile_index_by_name, name);
2880   if (!p)
2881     return 0;
2882
2883   return pool_elt_at_index (km->profiles, p[0]);
2884 }
2885
2886
2887 static void
2888 ikev2_send_ike (vlib_main_t * vm, ip4_address_t * src, ip4_address_t * dst,
2889                 u32 bi0, u32 len)
2890 {
2891   ip4_header_t *ip40;
2892   udp_header_t *udp0;
2893   vlib_buffer_t *b0;
2894   vlib_frame_t *f;
2895   u32 *to_next;
2896
2897   b0 = vlib_get_buffer (vm, bi0);
2898   vlib_buffer_advance (b0, -sizeof (udp_header_t));
2899   udp0 = vlib_buffer_get_current (b0);
2900   vlib_buffer_advance (b0, -sizeof (ip4_header_t));
2901   ip40 = vlib_buffer_get_current (b0);
2902
2903
2904   ip40->ip_version_and_header_length = 0x45;
2905   ip40->tos = 0;
2906   ip40->fragment_id = 0;
2907   ip40->flags_and_fragment_offset = 0;
2908   ip40->ttl = 0xff;
2909   ip40->protocol = IP_PROTOCOL_UDP;
2910   ip40->dst_address.as_u32 = dst->as_u32;
2911   ip40->src_address.as_u32 = src->as_u32;
2912   udp0->dst_port = clib_host_to_net_u16 (500);
2913   udp0->src_port = clib_host_to_net_u16 (500);
2914   udp0->length = clib_host_to_net_u16 (len + sizeof (udp_header_t));
2915   udp0->checksum = 0;
2916   b0->current_length = len + sizeof (ip4_header_t) + sizeof (udp_header_t);
2917   ip40->length = clib_host_to_net_u16 (b0->current_length);
2918   ip40->checksum = ip4_header_checksum (ip40);
2919
2920
2921   /* send the request */
2922   f = vlib_get_frame_to_node (vm, ip4_lookup_node.index);
2923   to_next = vlib_frame_vector_args (f);
2924   to_next[0] = bi0;
2925   f->n_vectors = 1;
2926   vlib_put_frame_to_node (vm, ip4_lookup_node.index, f);
2927
2928 }
2929
2930 static u32
2931 ikev2_get_new_ike_header_buff (vlib_main_t * vm, ike_header_t ** ike)
2932 {
2933   u32 bi0;
2934   if (vlib_buffer_alloc (vm, &bi0, 1) != 1)
2935     {
2936       *ike = 0;
2937       return 0;
2938     }
2939   vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
2940   *ike = vlib_buffer_get_current (b0);
2941   return bi0;
2942 }
2943
2944 clib_error_t *
2945 ikev2_set_local_key (vlib_main_t * vm, u8 * file)
2946 {
2947   ikev2_main_t *km = &ikev2_main;
2948
2949   km->pkey = ikev2_load_key_file (file);
2950   if (km->pkey == NULL)
2951     return clib_error_return (0, "load key '%s' failed", file);
2952
2953   return 0;
2954 }
2955
2956 static_always_inline vnet_api_error_t
2957 ikev2_register_udp_port (ikev2_profile_t * p, u16 port)
2958 {
2959   ikev2_main_t *km = &ikev2_main;
2960   udp_dst_port_info_t *pi;
2961
2962   uword *v = hash_get (km->udp_ports, port);
2963   pi = udp_get_dst_port_info (&udp_main, port, UDP_IP4);
2964
2965   if (v)
2966     {
2967       /* IKE already uses this port, only increment reference counter */
2968       ASSERT (pi);
2969       v[0]++;
2970     }
2971   else
2972     {
2973       if (pi)
2974         return VNET_API_ERROR_UDP_PORT_TAKEN;
2975
2976       udp_register_dst_port (km->vlib_main, port,
2977                              ipsec4_tun_input_node.index, 1);
2978       hash_set (km->udp_ports, port, 1);
2979     }
2980   p->dst_port = port;
2981   return 0;
2982 }
2983
2984 static_always_inline void
2985 ikev2_unregister_udp_port (ikev2_profile_t * p)
2986 {
2987   ikev2_main_t *km = &ikev2_main;
2988   uword *v;
2989
2990   if (p->dst_port == IPSEC_UDP_PORT_NONE)
2991     return;
2992
2993   v = hash_get (km->udp_ports, p->dst_port);
2994   if (!v)
2995     return;
2996
2997   v[0]--;
2998
2999   if (v[0] == 0)
3000     {
3001       udp_unregister_dst_port (km->vlib_main, p->dst_port, 1);
3002       hash_unset (km->udp_ports, p->dst_port);
3003     }
3004
3005   p->dst_port = IPSEC_UDP_PORT_NONE;
3006 }
3007
3008 clib_error_t *
3009 ikev2_add_del_profile (vlib_main_t * vm, u8 * name, int is_add)
3010 {
3011   ikev2_main_t *km = &ikev2_main;
3012   ikev2_profile_t *p;
3013
3014   if (is_add)
3015     {
3016       if (ikev2_profile_index_by_name (name))
3017         return clib_error_return (0, "policy %v already exists", name);
3018
3019       pool_get (km->profiles, p);
3020       clib_memset (p, 0, sizeof (*p));
3021       p->name = vec_dup (name);
3022       p->dst_port = IPSEC_UDP_PORT_NONE;
3023       p->responder.sw_if_index = ~0;
3024       p->tun_itf = ~0;
3025       uword index = p - km->profiles;
3026       mhash_set_mem (&km->profile_index_by_name, name, &index, 0);
3027     }
3028   else
3029     {
3030       p = ikev2_profile_index_by_name (name);
3031       if (!p)
3032         return clib_error_return (0, "policy %v does not exists", name);
3033
3034       ikev2_unregister_udp_port (p);
3035
3036       vec_free (p->name);
3037       pool_put (km->profiles, p);
3038       mhash_unset (&km->profile_index_by_name, name, 0);
3039     }
3040   return 0;
3041 }
3042
3043 clib_error_t *
3044 ikev2_set_profile_auth (vlib_main_t * vm, u8 * name, u8 auth_method,
3045                         u8 * auth_data, u8 data_hex_format)
3046 {
3047   ikev2_profile_t *p;
3048   clib_error_t *r;
3049
3050   p = ikev2_profile_index_by_name (name);
3051
3052   if (!p)
3053     {
3054       r = clib_error_return (0, "unknown profile %v", name);
3055       return r;
3056     }
3057   vec_free (p->auth.data);
3058   p->auth.method = auth_method;
3059   p->auth.data = vec_dup (auth_data);
3060   p->auth.hex = data_hex_format;
3061
3062   if (auth_method == IKEV2_AUTH_METHOD_RSA_SIG)
3063     {
3064       vec_add1 (p->auth.data, 0);
3065       if (p->auth.key)
3066         EVP_PKEY_free (p->auth.key);
3067       p->auth.key = ikev2_load_cert_file (auth_data);
3068       if (p->auth.key == NULL)
3069         return clib_error_return (0, "load cert '%s' failed", auth_data);
3070     }
3071
3072   return 0;
3073 }
3074
3075 clib_error_t *
3076 ikev2_set_profile_id (vlib_main_t * vm, u8 * name, u8 id_type, u8 * data,
3077                       int is_local)
3078 {
3079   ikev2_profile_t *p;
3080   clib_error_t *r;
3081
3082   if (id_type > IKEV2_ID_TYPE_ID_RFC822_ADDR
3083       && id_type < IKEV2_ID_TYPE_ID_KEY_ID)
3084     {
3085       r = clib_error_return (0, "unsupported identity type %U",
3086                              format_ikev2_id_type, id_type);
3087       return r;
3088     }
3089
3090   p = ikev2_profile_index_by_name (name);
3091
3092   if (!p)
3093     {
3094       r = clib_error_return (0, "unknown profile %v", name);
3095       return r;
3096     }
3097
3098   if (is_local)
3099     {
3100       vec_free (p->loc_id.data);
3101       p->loc_id.type = id_type;
3102       p->loc_id.data = vec_dup (data);
3103     }
3104   else
3105     {
3106       vec_free (p->rem_id.data);
3107       p->rem_id.type = id_type;
3108       p->rem_id.data = vec_dup (data);
3109     }
3110
3111   return 0;
3112 }
3113
3114 clib_error_t *
3115 ikev2_set_profile_ts (vlib_main_t * vm, u8 * name, u8 protocol_id,
3116                       u16 start_port, u16 end_port, ip4_address_t start_addr,
3117                       ip4_address_t end_addr, int is_local)
3118 {
3119   ikev2_profile_t *p;
3120   clib_error_t *r;
3121
3122   p = ikev2_profile_index_by_name (name);
3123
3124   if (!p)
3125     {
3126       r = clib_error_return (0, "unknown profile %v", name);
3127       return r;
3128     }
3129
3130   if (is_local)
3131     {
3132       p->loc_ts.start_addr.as_u32 = start_addr.as_u32;
3133       p->loc_ts.end_addr.as_u32 = end_addr.as_u32;
3134       p->loc_ts.start_port = start_port;
3135       p->loc_ts.end_port = end_port;
3136       p->loc_ts.protocol_id = protocol_id;
3137       p->loc_ts.ts_type = 7;
3138     }
3139   else
3140     {
3141       p->rem_ts.start_addr.as_u32 = start_addr.as_u32;
3142       p->rem_ts.end_addr.as_u32 = end_addr.as_u32;
3143       p->rem_ts.start_port = start_port;
3144       p->rem_ts.end_port = end_port;
3145       p->rem_ts.protocol_id = protocol_id;
3146       p->rem_ts.ts_type = 7;
3147     }
3148
3149   return 0;
3150 }
3151
3152
3153 clib_error_t *
3154 ikev2_set_profile_responder (vlib_main_t * vm, u8 * name,
3155                              u32 sw_if_index, ip4_address_t ip4)
3156 {
3157   ikev2_profile_t *p;
3158   clib_error_t *r;
3159
3160   p = ikev2_profile_index_by_name (name);
3161
3162   if (!p)
3163     {
3164       r = clib_error_return (0, "unknown profile %v", name);
3165       return r;
3166     }
3167
3168   p->responder.sw_if_index = sw_if_index;
3169   p->responder.ip4 = ip4;
3170
3171   return 0;
3172 }
3173
3174 clib_error_t *
3175 ikev2_set_profile_ike_transforms (vlib_main_t * vm, u8 * name,
3176                                   ikev2_transform_encr_type_t crypto_alg,
3177                                   ikev2_transform_integ_type_t integ_alg,
3178                                   ikev2_transform_dh_type_t dh_type,
3179                                   u32 crypto_key_size)
3180 {
3181   ikev2_profile_t *p;
3182   clib_error_t *r;
3183
3184   p = ikev2_profile_index_by_name (name);
3185
3186   if (!p)
3187     {
3188       r = clib_error_return (0, "unknown profile %v", name);
3189       return r;
3190     }
3191
3192   p->ike_ts.crypto_alg = crypto_alg;
3193   p->ike_ts.integ_alg = integ_alg;
3194   p->ike_ts.dh_type = dh_type;
3195   p->ike_ts.crypto_key_size = crypto_key_size;
3196   return 0;
3197 }
3198
3199 clib_error_t *
3200 ikev2_set_profile_esp_transforms (vlib_main_t * vm, u8 * name,
3201                                   ikev2_transform_encr_type_t crypto_alg,
3202                                   ikev2_transform_integ_type_t integ_alg,
3203                                   ikev2_transform_dh_type_t dh_type,
3204                                   u32 crypto_key_size)
3205 {
3206   ikev2_profile_t *p;
3207   clib_error_t *r;
3208
3209   p = ikev2_profile_index_by_name (name);
3210
3211   if (!p)
3212     {
3213       r = clib_error_return (0, "unknown profile %v", name);
3214       return r;
3215     }
3216
3217   p->esp_ts.crypto_alg = crypto_alg;
3218   p->esp_ts.integ_alg = integ_alg;
3219   p->esp_ts.dh_type = dh_type;
3220   p->esp_ts.crypto_key_size = crypto_key_size;
3221   return 0;
3222 }
3223
3224 clib_error_t *
3225 ikev2_set_profile_tunnel_interface (vlib_main_t * vm,
3226                                     u8 * name, u32 sw_if_index)
3227 {
3228   ikev2_profile_t *p;
3229   clib_error_t *r;
3230
3231   p = ikev2_profile_index_by_name (name);
3232
3233   if (!p)
3234     {
3235       r = clib_error_return (0, "unknown profile %v", name);
3236       return r;
3237     }
3238
3239   p->tun_itf = sw_if_index;
3240
3241   return 0;
3242 }
3243
3244 vnet_api_error_t
3245 ikev2_set_profile_ipsec_udp_port (vlib_main_t * vm, u8 * name, u16 port,
3246                                   u8 is_set)
3247 {
3248   ikev2_profile_t *p = ikev2_profile_index_by_name (name);
3249   ikev2_main_t *km = &ikev2_main;
3250   vnet_api_error_t rv = 0;
3251   uword *v;
3252
3253   if (!p)
3254     return VNET_API_ERROR_INVALID_VALUE;
3255
3256   if (is_set)
3257     {
3258       if (p->dst_port != IPSEC_UDP_PORT_NONE)
3259         return VNET_API_ERROR_VALUE_EXIST;
3260
3261       rv = ikev2_register_udp_port (p, port);
3262     }
3263   else
3264     {
3265       v = hash_get (km->udp_ports, port);
3266       if (!v)
3267         return VNET_API_ERROR_IKE_NO_PORT;
3268
3269       if (p->dst_port == IPSEC_UDP_PORT_NONE)
3270         return VNET_API_ERROR_INVALID_VALUE;
3271
3272       ikev2_unregister_udp_port (p);
3273     }
3274   return rv;
3275 }
3276
3277 clib_error_t *
3278 ikev2_set_profile_udp_encap (vlib_main_t * vm, u8 * name)
3279 {
3280   ikev2_profile_t *p = ikev2_profile_index_by_name (name);
3281   clib_error_t *r;
3282
3283   if (!p)
3284     {
3285       r = clib_error_return (0, "unknown profile %v", name);
3286       return r;
3287     }
3288
3289   p->udp_encap = 1;
3290   return 0;
3291 }
3292
3293 clib_error_t *
3294 ikev2_set_profile_sa_lifetime (vlib_main_t * vm, u8 * name,
3295                                u64 lifetime, u32 jitter, u32 handover,
3296                                u64 maxdata)
3297 {
3298   ikev2_profile_t *p;
3299   clib_error_t *r;
3300
3301   p = ikev2_profile_index_by_name (name);
3302
3303   if (!p)
3304     {
3305       r = clib_error_return (0, "unknown profile %v", name);
3306       return r;
3307     }
3308
3309   p->lifetime = lifetime;
3310   p->lifetime_jitter = jitter;
3311   p->handover = handover;
3312   p->lifetime_maxdata = maxdata;
3313   return 0;
3314 }
3315
3316 clib_error_t *
3317 ikev2_initiate_sa_init (vlib_main_t * vm, u8 * name)
3318 {
3319   ikev2_profile_t *p;
3320   clib_error_t *r;
3321   ip4_main_t *im = &ip4_main;
3322   ikev2_main_t *km = &ikev2_main;
3323
3324   p = ikev2_profile_index_by_name (name);
3325
3326   if (!p)
3327     {
3328       r = clib_error_return (0, "unknown profile %v", name);
3329       return r;
3330     }
3331
3332   if (p->responder.sw_if_index == ~0 || p->responder.ip4.data_u32 == 0)
3333     {
3334       r = clib_error_return (0, "responder not set for profile %v", name);
3335       return r;
3336     }
3337
3338
3339   /* Create the Initiator Request */
3340   {
3341     ike_header_t *ike0;
3342     u32 bi0 = 0;
3343     ip_lookup_main_t *lm = &im->lookup_main;
3344     u32 if_add_index0;
3345     int len = sizeof (ike_header_t);
3346
3347     /* Get own iface IP */
3348     if_add_index0 =
3349       lm->if_address_pool_index_by_sw_if_index[p->responder.sw_if_index];
3350     ip_interface_address_t *if_add =
3351       pool_elt_at_index (lm->if_address_pool, if_add_index0);
3352     ip4_address_t *if_ip = ip_interface_address_get_address (lm, if_add);
3353
3354     bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3355
3356     /* Prepare the SA and the IKE payload */
3357     ikev2_sa_t sa;
3358     clib_memset (&sa, 0, sizeof (ikev2_sa_t));
3359     ikev2_payload_chain_t *chain = 0;
3360     ikev2_payload_new_chain (chain);
3361
3362     /* Build the IKE proposal payload */
3363     ikev2_sa_proposal_t *proposals = 0;
3364     ikev2_set_initiator_proposals (vm, &sa, &p->ike_ts, &proposals, 1);
3365     proposals[0].proposal_num = 1;
3366     proposals[0].protocol_id = IKEV2_PROTOCOL_IKE;
3367
3368     /* Add and then cleanup proposal data */
3369     ikev2_payload_add_sa (chain, proposals);
3370     ikev2_sa_free_proposal_vector (&proposals);
3371
3372     sa.is_initiator = 1;
3373     sa.profile_index = km->profiles - p;
3374     sa.is_profile_index_set = 1;
3375     sa.state = IKEV2_STATE_SA_INIT;
3376     sa.tun_itf = p->tun_itf;
3377     sa.udp_encap = p->udp_encap;
3378     sa.dst_port = p->dst_port;
3379     sa.is_tun_itf_set = 1;
3380     sa.initial_contact = 1;
3381     ikev2_generate_sa_init_data (&sa);
3382     ikev2_payload_add_ke (chain, sa.dh_group, sa.i_dh_data);
3383     ikev2_payload_add_nonce (chain, sa.i_nonce);
3384
3385     /* Build the child SA proposal */
3386     vec_resize (sa.childs, 1);
3387     ikev2_set_initiator_proposals (vm, &sa, &p->esp_ts,
3388                                    &sa.childs[0].i_proposals, 0);
3389     sa.childs[0].i_proposals[0].proposal_num = 1;
3390     sa.childs[0].i_proposals[0].protocol_id = IKEV2_PROTOCOL_ESP;
3391     RAND_bytes ((u8 *) & sa.childs[0].i_proposals[0].spi,
3392                 sizeof (sa.childs[0].i_proposals[0].spi));
3393
3394
3395
3396     /* Add NAT detection notification messages (mandatory) */
3397     u8 nat_detection_source[8 + 8 + 4 + 2];
3398     u8 *nat_detection_sha1 = vec_new (u8, 20);
3399
3400     u64 tmpspi = clib_host_to_net_u64 (sa.ispi);
3401     clib_memcpy_fast (&nat_detection_source[0], &tmpspi, sizeof (tmpspi));
3402     tmpspi = clib_host_to_net_u64 (sa.rspi);
3403     clib_memcpy_fast (&nat_detection_source[8], &tmpspi, sizeof (tmpspi));
3404     u16 tmpport = clib_host_to_net_u16 (500);
3405     clib_memcpy_fast (&nat_detection_source[8 + 8 + 4], &tmpport,
3406                       sizeof (tmpport));
3407     u32 tmpip = clib_host_to_net_u32 (if_ip->as_u32);
3408     clib_memcpy_fast (&nat_detection_source[8 + 8], &tmpip, sizeof (tmpip));
3409     SHA1 (nat_detection_source, sizeof (nat_detection_source),
3410           nat_detection_sha1);
3411     ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_NAT_DETECTION_SOURCE_IP,
3412                               nat_detection_sha1);
3413     tmpip = clib_host_to_net_u32 (p->responder.ip4.as_u32);
3414     clib_memcpy_fast (&nat_detection_source[8 + 8], &tmpip, sizeof (tmpip));
3415     SHA1 (nat_detection_source, sizeof (nat_detection_source),
3416           nat_detection_sha1);
3417     ikev2_payload_add_notify (chain,
3418                               IKEV2_NOTIFY_MSG_NAT_DETECTION_DESTINATION_IP,
3419                               nat_detection_sha1);
3420     vec_free (nat_detection_sha1);
3421
3422     u8 *sig_hash_algo = vec_new (u8, 8);
3423     u64 tmpsig = clib_host_to_net_u64 (0x0001000200030004);
3424     clib_memcpy_fast (sig_hash_algo, &tmpsig, sizeof (tmpsig));
3425     ikev2_payload_add_notify (chain,
3426                               IKEV2_NOTIFY_MSG_SIGNATURE_HASH_ALGORITHMS,
3427                               sig_hash_algo);
3428     vec_free (sig_hash_algo);
3429
3430
3431     /* Buffer update and boilerplate */
3432     len += vec_len (chain->data);
3433     ike0->nextpayload = chain->first_payload_type;
3434     ike0->length = clib_host_to_net_u32 (len);
3435     clib_memcpy_fast (ike0->payload, chain->data, vec_len (chain->data));
3436     ikev2_payload_destroy_chain (chain);
3437
3438     ike0->version = IKE_VERSION_2;
3439     ike0->flags = IKEV2_HDR_FLAG_INITIATOR;
3440     ike0->exchange = IKEV2_EXCHANGE_SA_INIT;
3441     ike0->ispi = sa.ispi;
3442     ike0->rspi = 0;
3443     ike0->msgid = 0;
3444
3445     /* store whole IKE payload - needed for PSK auth */
3446     vec_free (sa.last_sa_init_req_packet_data);
3447     vec_add (sa.last_sa_init_req_packet_data, ike0, len);
3448
3449     /* add data to the SA then add it to the pool */
3450     sa.iaddr.as_u32 = if_ip->as_u32;
3451     sa.raddr.as_u32 = p->responder.ip4.as_u32;
3452     sa.i_id.type = p->loc_id.type;
3453     sa.i_id.data = vec_dup (p->loc_id.data);
3454     sa.i_auth.method = p->auth.method;
3455     sa.i_auth.hex = p->auth.hex;
3456     sa.i_auth.data = vec_dup (p->auth.data);
3457     vec_add (sa.childs[0].tsi, &p->loc_ts, 1);
3458     vec_add (sa.childs[0].tsr, &p->rem_ts, 1);
3459
3460     ikev2_initial_contact_cleanup (&sa);
3461
3462     /* add SA to the pool */
3463     ikev2_sa_t *sa0 = 0;
3464     pool_get (km->sais, sa0);
3465     clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
3466     hash_set (km->sa_by_ispi, sa0->ispi, sa0 - km->sais);
3467
3468     ikev2_send_ike (vm, if_ip, &p->responder.ip4, bi0, len);
3469
3470     ikev2_elog_exchange ("ispi %lx rspi %lx IKEV2_EXCHANGE_SA_INIT sent to "
3471                          "%d.%d.%d.%d", clib_host_to_net_u64 (sa0->ispi), 0,
3472                          p->responder.ip4.as_u32);
3473   }
3474
3475   return 0;
3476 }
3477
3478 static void
3479 ikev2_delete_child_sa_internal (vlib_main_t * vm, ikev2_sa_t * sa,
3480                                 ikev2_child_sa_t * csa)
3481 {
3482   /* Create the Initiator notification for child SA removal */
3483   ikev2_main_t *km = &ikev2_main;
3484   ike_header_t *ike0;
3485   u32 bi0 = 0;
3486   int len;
3487
3488   bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3489
3490
3491   ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3492   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3493   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3494   vec_resize (sa->del, 1);
3495   sa->del->protocol_id = IKEV2_PROTOCOL_ESP;
3496   sa->del->spi = csa->i_proposals->spi;
3497   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3498   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3499   len = ikev2_generate_message (sa, ike0, 0);
3500
3501   ikev2_send_ike (vm, &sa->iaddr, &sa->raddr, bi0, len);
3502
3503   /* delete local child SA */
3504   ikev2_delete_tunnel_interface (km->vnet_main, sa, csa);
3505   ikev2_sa_del_child_sa (sa, csa);
3506 }
3507
3508 clib_error_t *
3509 ikev2_initiate_delete_child_sa (vlib_main_t * vm, u32 ispi)
3510 {
3511   clib_error_t *r;
3512   ikev2_main_t *km = &ikev2_main;
3513   ikev2_main_per_thread_data_t *tkm;
3514   ikev2_sa_t *fsa = 0;
3515   ikev2_child_sa_t *fchild = 0;
3516
3517   /* Search for the child SA */
3518   vec_foreach (tkm, km->per_thread_data)
3519   {
3520     ikev2_sa_t *sa;
3521     if (fchild)
3522       break;
3523     /* *INDENT-OFF* */
3524     pool_foreach (sa, tkm->sas, ({
3525       fchild = ikev2_sa_get_child(sa, ispi, IKEV2_PROTOCOL_ESP, 1);
3526       if (fchild)
3527         {
3528           fsa = sa;
3529           break;
3530         }
3531     }));
3532     /* *INDENT-ON* */
3533   }
3534
3535   if (!fchild || !fsa)
3536     {
3537       r = clib_error_return (0, "Child SA not found");
3538       return r;
3539     }
3540   else
3541     {
3542       ikev2_delete_child_sa_internal (vm, fsa, fchild);
3543     }
3544
3545   return 0;
3546 }
3547
3548 clib_error_t *
3549 ikev2_initiate_delete_ike_sa (vlib_main_t * vm, u64 ispi)
3550 {
3551   clib_error_t *r;
3552   ikev2_main_t *km = &ikev2_main;
3553   ikev2_main_per_thread_data_t *tkm;
3554   ikev2_sa_t *fsa = 0;
3555   ikev2_main_per_thread_data_t *ftkm = 0;
3556
3557   /* Search for the IKE SA */
3558   vec_foreach (tkm, km->per_thread_data)
3559   {
3560     ikev2_sa_t *sa;
3561     if (fsa)
3562       break;
3563     /* *INDENT-OFF* */
3564     pool_foreach (sa, tkm->sas, ({
3565       if (sa->ispi == ispi)
3566         {
3567           fsa = sa;
3568           ftkm = tkm;
3569           break;
3570         }
3571     }));
3572     /* *INDENT-ON* */
3573   }
3574
3575   if (!fsa)
3576     {
3577       r = clib_error_return (0, "IKE SA not found");
3578       return r;
3579     }
3580
3581
3582   /* Create the Initiator notification for IKE SA removal */
3583   {
3584     ike_header_t *ike0;
3585     u32 bi0 = 0;
3586     int len;
3587
3588     bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3589
3590
3591     ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3592     ike0->ispi = clib_host_to_net_u64 (fsa->ispi);
3593     ike0->rspi = clib_host_to_net_u64 (fsa->rspi);
3594     vec_resize (fsa->del, 1);
3595     fsa->del->protocol_id = IKEV2_PROTOCOL_IKE;
3596     fsa->del->spi = ispi;
3597     ike0->msgid = clib_host_to_net_u32 (fsa->last_init_msg_id + 1);
3598     fsa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3599     len = ikev2_generate_message (fsa, ike0, 0);
3600
3601     ikev2_send_ike (vm, &fsa->iaddr, &fsa->raddr, bi0, len);
3602   }
3603
3604
3605   /* delete local SA */
3606   ikev2_child_sa_t *c;
3607   vec_foreach (c, fsa->childs)
3608   {
3609     ikev2_delete_tunnel_interface (km->vnet_main, fsa, c);
3610     ikev2_sa_del_child_sa (fsa, c);
3611   }
3612   ikev2_sa_free_all_vec (fsa);
3613   uword *p = hash_get (ftkm->sa_by_rspi, fsa->rspi);
3614   if (p)
3615     {
3616       hash_unset (ftkm->sa_by_rspi, fsa->rspi);
3617       pool_put (ftkm->sas, fsa);
3618     }
3619
3620
3621   return 0;
3622 }
3623
3624 static void
3625 ikev2_rekey_child_sa_internal (vlib_main_t * vm, ikev2_sa_t * sa,
3626                                ikev2_child_sa_t * csa)
3627 {
3628   /* Create the Initiator request for create child SA */
3629   ike_header_t *ike0;
3630   u32 bi0 = 0;
3631   int len;
3632
3633
3634   bi0 = ikev2_get_new_ike_header_buff (vm, &ike0);
3635
3636
3637   ike0->version = IKE_VERSION_2;
3638   ike0->flags = IKEV2_HDR_FLAG_INITIATOR;
3639   ike0->exchange = IKEV2_EXCHANGE_CREATE_CHILD_SA;
3640   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3641   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3642   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3643   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3644
3645   ikev2_rekey_t *rekey;
3646   vec_add2 (sa->rekey, rekey, 1);
3647   ikev2_sa_proposal_t *proposals = vec_dup (csa->i_proposals);
3648
3649   /*need new ispi */
3650   RAND_bytes ((u8 *) & proposals[0].spi, sizeof (proposals[0].spi));
3651   rekey->spi = proposals[0].spi;
3652   rekey->ispi = csa->i_proposals->spi;
3653   len = ikev2_generate_message (sa, ike0, proposals);
3654   ikev2_send_ike (vm, &sa->iaddr, &sa->raddr, bi0, len);
3655   vec_free (proposals);
3656 }
3657
3658 clib_error_t *
3659 ikev2_initiate_rekey_child_sa (vlib_main_t * vm, u32 ispi)
3660 {
3661   clib_error_t *r;
3662   ikev2_main_t *km = &ikev2_main;
3663   ikev2_main_per_thread_data_t *tkm;
3664   ikev2_sa_t *fsa = 0;
3665   ikev2_child_sa_t *fchild = 0;
3666
3667   /* Search for the child SA */
3668   vec_foreach (tkm, km->per_thread_data)
3669   {
3670     ikev2_sa_t *sa;
3671     if (fchild)
3672       break;
3673     /* *INDENT-OFF* */
3674     pool_foreach (sa, tkm->sas, ({
3675       fchild = ikev2_sa_get_child(sa, ispi, IKEV2_PROTOCOL_ESP, 1);
3676       if (fchild)
3677         {
3678           fsa = sa;
3679           break;
3680         }
3681     }));
3682     /* *INDENT-ON* */
3683   }
3684
3685   if (!fchild || !fsa)
3686     {
3687       r = clib_error_return (0, "Child SA not found");
3688       return r;
3689     }
3690   else
3691     {
3692       ikev2_rekey_child_sa_internal (vm, fsa, fchild);
3693     }
3694
3695   return 0;
3696 }
3697
3698 clib_error_t *
3699 ikev2_init (vlib_main_t * vm)
3700 {
3701   ikev2_main_t *km = &ikev2_main;
3702   vlib_thread_main_t *tm = vlib_get_thread_main ();
3703   int thread_id;
3704
3705   clib_memset (km, 0, sizeof (ikev2_main_t));
3706   km->vnet_main = vnet_get_main ();
3707   km->vlib_main = vm;
3708
3709   ikev2_crypto_init (km);
3710
3711   mhash_init_vec_string (&km->profile_index_by_name, sizeof (uword));
3712
3713   vec_validate_aligned (km->per_thread_data, tm->n_vlib_mains - 1,
3714                         CLIB_CACHE_LINE_BYTES);
3715   for (thread_id = 0; thread_id < tm->n_vlib_mains - 1; thread_id++)
3716     {
3717       km->per_thread_data[thread_id].sa_by_rspi =
3718         hash_create (0, sizeof (uword));
3719     }
3720
3721   km->sa_by_ispi = hash_create (0, sizeof (uword));
3722   km->sw_if_indices = hash_create (0, 0);
3723   km->udp_ports = hash_create (0, sizeof (uword));
3724
3725   udp_register_dst_port (vm, 500, ikev2_node.index, 1);
3726
3727   ikev2_cli_reference ();
3728
3729   km->log_level = IKEV2_LOG_ERROR;
3730   km->log_class = vlib_log_register_class ("ikev2", 0);
3731   return 0;
3732 }
3733
3734 /* *INDENT-OFF* */
3735 VLIB_INIT_FUNCTION (ikev2_init) =
3736 {
3737   .runs_after = VLIB_INITS("ipsec_init"),
3738 };
3739 /* *INDENT-ON* */
3740
3741 static u8
3742 ikev2_mngr_process_child_sa (ikev2_sa_t * sa, ikev2_child_sa_t * csa,
3743                              u8 del_old_ids)
3744 {
3745   ikev2_main_t *km = &ikev2_main;
3746   ikev2_profile_t *p = 0;
3747   vlib_main_t *vm = km->vlib_main;
3748   f64 now = vlib_time_now (vm);
3749   u8 res = 0;
3750
3751   if (sa->is_profile_index_set)
3752     p = pool_elt_at_index (km->profiles, sa->profile_index);
3753
3754   if (sa->is_initiator && p && csa->time_to_expiration
3755       && now > csa->time_to_expiration)
3756     {
3757       if (!csa->is_expired || csa->rekey_retries > 0)
3758         {
3759           ikev2_rekey_child_sa_internal (vm, sa, csa);
3760           csa->time_to_expiration = now + p->handover;
3761           csa->is_expired = 1;
3762           if (csa->rekey_retries == 0)
3763             {
3764               csa->rekey_retries = 5;
3765             }
3766           else if (csa->rekey_retries > 0)
3767             {
3768               csa->rekey_retries--;
3769               ikev2_log_debug ("Rekeying Child SA 0x%x, retries left %d",
3770                                csa->i_proposals->spi, csa->rekey_retries);
3771               if (csa->rekey_retries == 0)
3772                 {
3773                   csa->rekey_retries = -1;
3774                 }
3775             }
3776           res |= 1;
3777         }
3778       else
3779         {
3780           csa->time_to_expiration = 0;
3781           ikev2_delete_child_sa_internal (vm, sa, csa);
3782           res |= 1;
3783         }
3784     }
3785
3786   if (del_old_ids)
3787     {
3788       ipip_tunnel_t *ipip = NULL;
3789       u32 sw_if_index = sa->is_tun_itf_set ? sa->tun_itf : ~0;
3790       if (~0 == sw_if_index)
3791         {
3792           ip46_address_t local_ip;
3793           ip46_address_t remote_ip;
3794           if (sa->is_initiator)
3795             {
3796               ip46_address_set_ip4 (&local_ip, &sa->iaddr);
3797               ip46_address_set_ip4 (&remote_ip, &sa->raddr);
3798             }
3799           else
3800             {
3801               ip46_address_set_ip4 (&local_ip, &sa->raddr);
3802               ip46_address_set_ip4 (&remote_ip, &sa->iaddr);
3803             }
3804
3805        /* *INDENT-OFF* */
3806        ipip_tunnel_key_t key = {
3807          .src = local_ip,
3808          .dst = remote_ip,
3809          .transport = IPIP_TRANSPORT_IP4,
3810          .fib_index = 0,
3811        };
3812        /* *INDENT-ON* */
3813
3814           ipip = ipip_tunnel_db_find (&key);
3815
3816           if (ipip)
3817             sw_if_index = ipip->sw_if_index;
3818           else
3819             return res;
3820         }
3821
3822       u32 *sas_in = NULL;
3823       vec_add1 (sas_in, csa->remote_sa_id);
3824       ipsec_tun_protect_update (sw_if_index, NULL, csa->local_sa_id, sas_in);
3825       ipsec_sa_unlock_id (ikev2_flip_alternate_sa_bit (csa->remote_sa_id));
3826     }
3827
3828   return res;
3829 }
3830
3831 int
3832 ikev2_set_log_level (ikev2_log_level_t log_level)
3833 {
3834   ikev2_main_t *km = &ikev2_main;
3835
3836   if (log_level >= IKEV2_LOG_MAX)
3837     {
3838       ikev2_log_error ("unknown logging level %d", log_level);
3839       return -1;
3840     }
3841
3842   km->log_level = log_level;
3843   return 0;
3844 }
3845
3846 static void
3847 ikev2_mngr_process_ipsec_sa (ipsec_sa_t * ipsec_sa)
3848 {
3849   ikev2_main_t *km = &ikev2_main;
3850   vlib_main_t *vm = km->vlib_main;
3851   ikev2_main_per_thread_data_t *tkm;
3852   ikev2_sa_t *fsa = 0;
3853   ikev2_profile_t *p = 0;
3854   ikev2_child_sa_t *fchild = 0;
3855   f64 now = vlib_time_now (vm);
3856   vlib_counter_t counts;
3857
3858   /* Search for the SA and child SA */
3859   vec_foreach (tkm, km->per_thread_data)
3860   {
3861     ikev2_sa_t *sa;
3862     if (fchild)
3863       break;
3864     /* *INDENT-OFF* */
3865     pool_foreach (sa, tkm->sas, ({
3866       fchild = ikev2_sa_get_child(sa, ipsec_sa->spi, IKEV2_PROTOCOL_ESP, 1);
3867       if (fchild)
3868         {
3869           fsa = sa;
3870           break;
3871         }
3872     }));
3873     /* *INDENT-ON* */
3874   }
3875   vlib_get_combined_counter (&ipsec_sa_counters,
3876                              ipsec_sa->stat_index, &counts);
3877
3878   if (fsa && fsa->is_profile_index_set)
3879     p = pool_elt_at_index (km->profiles, fsa->profile_index);
3880
3881   if (fchild && p && p->lifetime_maxdata)
3882     {
3883       if (!fchild->is_expired && counts.bytes > p->lifetime_maxdata)
3884         {
3885           fchild->time_to_expiration = now;
3886         }
3887     }
3888 }
3889
3890 static void
3891 ikev2_process_pending_sa_init (ikev2_main_t * km)
3892 {
3893   u32 sai;
3894   u64 ispi;
3895   ikev2_sa_t *sa;
3896
3897   /* *INDENT-OFF* */
3898   hash_foreach (ispi, sai, km->sa_by_ispi,
3899   ({
3900     sa = pool_elt_at_index (km->sais, sai);
3901     if (sa->init_response_received)
3902       continue;
3903
3904     u32 bi0;
3905     if (vlib_buffer_alloc (km->vlib_main, &bi0, 1) != 1)
3906       return;
3907
3908     vlib_buffer_t * b = vlib_get_buffer (km->vlib_main, bi0);
3909     clib_memcpy_fast (vlib_buffer_get_current (b),
3910         sa->last_sa_init_req_packet_data,
3911         vec_len (sa->last_sa_init_req_packet_data));
3912     ikev2_send_ike (km->vlib_main, &sa->iaddr, &sa->raddr, bi0,
3913         vec_len (sa->last_sa_init_req_packet_data));
3914   }));
3915   /* *INDENT-ON* */
3916 }
3917
3918 static vlib_node_registration_t ikev2_mngr_process_node;
3919
3920 static void
3921 ikev2_send_informational_request (ikev2_sa_t * sa)
3922 {
3923   ikev2_main_t *km = &ikev2_main;
3924   ip4_address_t *src, *dst;
3925   ike_header_t *ike0;
3926   u32 bi0 = 0;
3927   int len;
3928
3929   bi0 = ikev2_get_new_ike_header_buff (km->vlib_main, &ike0);
3930
3931   ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3932   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3933   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3934   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3935   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3936   len = ikev2_generate_message (sa, ike0, 0);
3937
3938   if (sa->is_initiator)
3939     {
3940       src = &sa->iaddr;
3941       dst = &sa->raddr;
3942     }
3943   else
3944     {
3945
3946       dst = &sa->iaddr;
3947       src = &sa->raddr;
3948     }
3949
3950   ikev2_send_ike (km->vlib_main, src, dst, bi0, len);
3951 }
3952
3953 static_always_inline int
3954 ikev2_mngr_process_responder_sas (ikev2_sa_t * sa)
3955 {
3956   ikev2_main_t *km = &ikev2_main;
3957   vlib_main_t *vm = km->vlib_main;
3958
3959   if (sa->liveness_retries > IKEV2_LIVENESS_RETRIES)
3960     return 1;
3961
3962   f64 now = vlib_time_now (vm);
3963
3964   if (sa->liveness_period_check < now)
3965     {
3966       sa->liveness_retries++;
3967       sa->liveness_period_check = now + IKEV2_LIVENESS_PERIOD_CHECK;
3968       ikev2_send_informational_request (sa);
3969     }
3970   return 0;
3971 }
3972
3973 static uword
3974 ikev2_mngr_process_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
3975                        vlib_frame_t * f)
3976 {
3977   ikev2_main_t *km = &ikev2_main;
3978   ipsec_main_t *im = &ipsec_main;
3979   ikev2_profile_t *p;
3980   ikev2_child_sa_t *c;
3981   u32 *sai;
3982
3983   while (1)
3984     {
3985       u8 req_sent = 0;
3986       vlib_process_wait_for_event_or_clock (vm, 1);
3987       vlib_process_get_events (vm, NULL);
3988
3989       /* process ike child sas */
3990       ikev2_main_per_thread_data_t *tkm;
3991       vec_foreach (tkm, km->per_thread_data)
3992       {
3993         ikev2_sa_t *sa;
3994         u32 *to_be_deleted = 0;
3995
3996         /* *INDENT-OFF* */
3997         pool_foreach (sa, tkm->sas, ({
3998           ikev2_child_sa_t *c;
3999           u8 del_old_ids = 0;
4000           if (sa->old_remote_id_present && 0 > sa->old_id_expiration)
4001             {
4002               sa->old_remote_id_present = 0;
4003               del_old_ids = 1;
4004             }
4005           else
4006             sa->old_id_expiration -= 1;
4007
4008           vec_foreach (c, sa->childs)
4009             {
4010             req_sent |= ikev2_mngr_process_child_sa(sa, c, del_old_ids);
4011             }
4012
4013           if (ikev2_mngr_process_responder_sas (sa))
4014             vec_add1 (to_be_deleted, sa - tkm->sas);
4015         }));
4016         /* *INDENT-ON* */
4017
4018         vec_foreach (sai, to_be_deleted)
4019         {
4020           sa = pool_elt_at_index (tkm->sas, sai[0]);
4021           if (sa->is_initiator && sa->is_profile_index_set)
4022             {
4023               p = pool_elt_at_index (km->profiles, sa->profile_index);
4024               if (p)
4025                 {
4026                   ikev2_initiate_sa_init (vm, p->name);
4027                   continue;
4028                 }
4029             }
4030           vec_foreach (c, sa->childs)
4031             ikev2_delete_tunnel_interface (km->vnet_main, sa, c);
4032           hash_unset (tkm->sa_by_rspi, sa->rspi);
4033           pool_put (tkm->sas, sa);
4034         }
4035       }
4036
4037       /* process ipsec sas */
4038       ipsec_sa_t *sa;
4039       /* *INDENT-OFF* */
4040       pool_foreach (sa, im->sad, ({
4041         ikev2_mngr_process_ipsec_sa(sa);
4042       }));
4043       /* *INDENT-ON* */
4044
4045       ikev2_process_pending_sa_init (km);
4046
4047       if (req_sent)
4048         {
4049           vlib_process_wait_for_event_or_clock (vm, 5);
4050           vlib_process_get_events (vm, NULL);
4051           req_sent = 0;
4052         }
4053
4054     }
4055   return 0;
4056 }
4057
4058 /* *INDENT-OFF* */
4059 VLIB_REGISTER_NODE (ikev2_mngr_process_node, static) = {
4060     .function = ikev2_mngr_process_fn,
4061     .type = VLIB_NODE_TYPE_PROCESS,
4062     .name =
4063     "ikev2-manager-process",
4064 };
4065
4066 VLIB_PLUGIN_REGISTER () = {
4067     .version = VPP_BUILD_VER,
4068     .description = "Internet Key Exchange (IKEv2) Protocol",
4069 };
4070 /* *INDENT-ON* */
4071
4072 /*
4073  * fd.io coding-style-patch-verification: ON
4074  *
4075  * Local Variables:
4076  * eval: (c-set-style "gnu")
4077  * End:
4078  */