ikev2: use thread local vlib_main in vlib_time_now
[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 3
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 (vlib_main_t * vm,
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 = vlib_time_now (vm) + p->lifetime;
1760       if (p->lifetime_jitter)
1761         {
1762           // This is not much better than rand(3), which Coverity warns
1763           // is unsuitable for security applications; random_u32 is
1764           // however fast. If this perturbance to the expiration time
1765           // needs to use a better RNG then we may need to use something
1766           // like /dev/urandom which has significant overhead.
1767           u32 rnd = (u32) (vlib_time_now (vm) * 1e6);
1768           rnd = random_u32 (&rnd);
1769
1770           child->time_to_expiration += 1 + (rnd % p->lifetime_jitter);
1771         }
1772     }
1773
1774   if (thread_index & 0xffffffc0)
1775     ikev2_elog_error ("error: thread index exceeds max range 0x3f!");
1776
1777   if (child_index & 0xfffff000 || sa_index & 0xfffff000)
1778     ikev2_elog_error ("error: sa/child index exceeds max range 0xfff!");
1779
1780   child->local_sa_id =
1781     a.local_sa_id =
1782     ikev2_mk_local_sa_id (sa_index, child_index, thread_index);
1783
1784   u32 remote_sa_id = ikev2_mk_remote_sa_id (sa_index, child_index,
1785                                             thread_index);
1786
1787   if (is_rekey)
1788     {
1789       /* create a new remote SA ID to keep the old SA for a bit longer
1790        * so the peer has some time to swap their SAs */
1791
1792       /* use most significat bit of child index part in id */
1793       u32 mask = 0x800;
1794       if (sa->current_remote_id_mask)
1795         {
1796           sa->old_remote_id = a.old_remote_sa_id = remote_sa_id | mask;
1797           sa->current_remote_id_mask = 0;
1798         }
1799       else
1800         {
1801           sa->old_remote_id = a.old_remote_sa_id = remote_sa_id;
1802           sa->current_remote_id_mask = mask;
1803           remote_sa_id |= mask;
1804         }
1805       sa->old_id_expiration = 3.0;
1806       sa->old_remote_id_present = 1;
1807     }
1808
1809   child->remote_sa_id = a.remote_sa_id = remote_sa_id;
1810
1811   a.sw_if_index = (sa->is_tun_itf_set ? sa->tun_itf : ~0);
1812   a.dst_port = sa->dst_port;
1813
1814   vl_api_rpc_call_main_thread (ikev2_add_tunnel_from_main,
1815                                (u8 *) & a, sizeof (a));
1816   return 0;
1817 }
1818
1819 typedef struct
1820 {
1821   ip46_address_t local_ip;
1822   ip46_address_t remote_ip;
1823   u32 remote_sa_id;
1824   u32 local_sa_id;
1825   u32 sw_if_index;
1826 } ikev2_del_ipsec_tunnel_args_t;
1827
1828 static_always_inline u32
1829 ikev2_flip_alternate_sa_bit (u32 id)
1830 {
1831   u32 mask = 0x800;
1832   if (mask & id)
1833     return id & ~mask;
1834   return id | mask;
1835 }
1836
1837 static void
1838 ikev2_del_tunnel_from_main (ikev2_del_ipsec_tunnel_args_t * a)
1839 {
1840   ikev2_main_t *km = &ikev2_main;
1841   ipip_tunnel_t *ipip = NULL;
1842   u32 sw_if_index;
1843
1844   if (~0 == a->sw_if_index)
1845     {
1846     /* *INDENT-OFF* */
1847     ipip_tunnel_key_t key = {
1848       .src = a->local_ip,
1849       .dst = a->remote_ip,
1850       .transport = IPIP_TRANSPORT_IP4,
1851       .fib_index = 0,
1852     };
1853     /* *INDENT-ON* */
1854
1855       ipip = ipip_tunnel_db_find (&key);
1856
1857       if (ipip)
1858         {
1859           sw_if_index = ipip->sw_if_index;
1860           hash_unset (km->sw_if_indices, ipip->sw_if_index);
1861         }
1862       else
1863         sw_if_index = ~0;
1864     }
1865   else
1866     {
1867       sw_if_index = a->sw_if_index;
1868       vnet_sw_interface_admin_down (vnet_get_main (), sw_if_index);
1869     }
1870
1871   if (~0 != sw_if_index)
1872     ipsec_tun_protect_del (sw_if_index, NULL);
1873
1874   ipsec_sa_unlock_id (a->remote_sa_id);
1875   ipsec_sa_unlock_id (a->local_sa_id);
1876   ipsec_sa_unlock_id (ikev2_flip_alternate_sa_bit (a->remote_sa_id));
1877
1878   if (ipip)
1879     ipip_del_tunnel (ipip->sw_if_index);
1880 }
1881
1882 static int
1883 ikev2_delete_tunnel_interface (vnet_main_t * vnm, ikev2_sa_t * sa,
1884                                ikev2_child_sa_t * child)
1885 {
1886   ikev2_del_ipsec_tunnel_args_t a;
1887
1888   clib_memset (&a, 0, sizeof (a));
1889
1890   if (sa->is_initiator)
1891     {
1892       ip46_address_set_ip4 (&a.local_ip, &sa->iaddr);
1893       ip46_address_set_ip4 (&a.remote_ip, &sa->raddr);
1894     }
1895   else
1896     {
1897       ip46_address_set_ip4 (&a.local_ip, &sa->raddr);
1898       ip46_address_set_ip4 (&a.remote_ip, &sa->iaddr);
1899     }
1900
1901   a.remote_sa_id = child->remote_sa_id;
1902   a.local_sa_id = child->local_sa_id;
1903   a.sw_if_index = (sa->is_tun_itf_set ? sa->tun_itf : ~0);
1904
1905   vl_api_rpc_call_main_thread (ikev2_del_tunnel_from_main, (u8 *) & a,
1906                                sizeof (a));
1907   return 0;
1908 }
1909
1910 static u32
1911 ikev2_generate_message (ikev2_sa_t * sa, ike_header_t * ike, void *user)
1912 {
1913   v8 *integ = 0;
1914   ike_payload_header_t *ph;
1915   u16 plen;
1916   u32 tlen = 0;
1917
1918   ikev2_sa_transform_t *tr_encr, *tr_integ;
1919   tr_encr =
1920     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR);
1921   tr_integ =
1922     ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG);
1923
1924   ikev2_payload_chain_t *chain = 0;
1925   ikev2_payload_new_chain (chain);
1926
1927   if (ike->exchange == IKEV2_EXCHANGE_SA_INIT)
1928     {
1929       if (sa->r_proposals == 0)
1930         {
1931           ikev2_payload_add_notify (chain,
1932                                     IKEV2_NOTIFY_MSG_NO_PROPOSAL_CHOSEN, 0);
1933           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1934         }
1935       else if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE)
1936         {
1937           u8 *data = vec_new (u8, 2);
1938           ikev2_sa_transform_t *tr_dh;
1939           tr_dh =
1940             ikev2_sa_get_td_for_type (sa->r_proposals,
1941                                       IKEV2_TRANSFORM_TYPE_DH);
1942           ASSERT (tr_dh && tr_dh->dh_type);
1943
1944           data[0] = (tr_dh->dh_type >> 8) & 0xff;
1945           data[1] = (tr_dh->dh_type) & 0xff;
1946
1947           ikev2_payload_add_notify (chain,
1948                                     IKEV2_NOTIFY_MSG_INVALID_KE_PAYLOAD,
1949                                     data);
1950           vec_free (data);
1951           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1952         }
1953       else if (sa->state == IKEV2_STATE_NOTIFY_AND_DELETE)
1954         {
1955           u8 *data = vec_new (u8, 1);
1956
1957           data[0] = sa->unsupported_cp;
1958           ikev2_payload_add_notify (chain,
1959                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
1960                                     data);
1961           vec_free (data);
1962         }
1963       else
1964         {
1965           ike->rspi = clib_host_to_net_u64 (sa->rspi);
1966           ikev2_payload_add_sa (chain, sa->r_proposals);
1967           ikev2_payload_add_ke (chain, sa->dh_group, sa->r_dh_data);
1968           ikev2_payload_add_nonce (chain, sa->r_nonce);
1969         }
1970     }
1971   else if (ike->exchange == IKEV2_EXCHANGE_IKE_AUTH)
1972     {
1973       if (sa->state == IKEV2_STATE_AUTHENTICATED)
1974         {
1975           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
1976           ikev2_payload_add_auth (chain, &sa->r_auth);
1977           ikev2_payload_add_sa (chain, sa->childs[0].r_proposals);
1978           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
1979           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
1980         }
1981       else if (sa->state == IKEV2_STATE_AUTH_FAILED)
1982         {
1983           ikev2_payload_add_notify (chain,
1984                                     IKEV2_NOTIFY_MSG_AUTHENTICATION_FAILED,
1985                                     0);
1986           ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
1987         }
1988       else if (sa->state == IKEV2_STATE_TS_UNACCEPTABLE)
1989         {
1990           ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_TS_UNACCEPTABLE,
1991                                     0);
1992           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
1993           ikev2_payload_add_auth (chain, &sa->r_auth);
1994         }
1995       else if (sa->state == IKEV2_STATE_NO_PROPOSAL_CHOSEN)
1996         {
1997           ikev2_payload_add_notify (chain,
1998                                     IKEV2_NOTIFY_MSG_NO_PROPOSAL_CHOSEN, 0);
1999           ikev2_payload_add_id (chain, &sa->r_id, IKEV2_PAYLOAD_IDR);
2000           ikev2_payload_add_auth (chain, &sa->r_auth);
2001           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
2002           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
2003         }
2004       else if (sa->state == IKEV2_STATE_NOTIFY_AND_DELETE)
2005         {
2006           u8 *data = vec_new (u8, 1);
2007
2008           data[0] = sa->unsupported_cp;
2009           ikev2_payload_add_notify (chain,
2010                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2011                                     data);
2012           vec_free (data);
2013         }
2014       else if (sa->state == IKEV2_STATE_SA_INIT)
2015         {
2016           ikev2_payload_add_id (chain, &sa->i_id, IKEV2_PAYLOAD_IDI);
2017           ikev2_payload_add_auth (chain, &sa->i_auth);
2018           ikev2_payload_add_sa (chain, sa->childs[0].i_proposals);
2019           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
2020           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
2021           ikev2_payload_add_notify (chain, IKEV2_NOTIFY_MSG_INITIAL_CONTACT,
2022                                     0);
2023         }
2024       else
2025         {
2026           ikev2_set_state (sa, IKEV2_STATE_DELETED);
2027           goto done;
2028         }
2029     }
2030   else if (ike->exchange == IKEV2_EXCHANGE_INFORMATIONAL)
2031     {
2032       /* if pending delete */
2033       if (sa->del)
2034         {
2035           if (sa->del[0].protocol_id == IKEV2_PROTOCOL_IKE)
2036             {
2037               if (sa->is_initiator)
2038                 ikev2_payload_add_delete (chain, sa->del);
2039
2040               /* The response to a request that deletes the IKE SA is an empty
2041                  INFORMATIONAL response. */
2042               ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE);
2043             }
2044           /* The response to a request that deletes ESP or AH SAs will contain
2045              delete payloads for the paired SAs going in the other direction. */
2046           else
2047             {
2048               ikev2_payload_add_delete (chain, sa->del);
2049             }
2050           vec_free (sa->del);
2051           sa->del = 0;
2052         }
2053       /* received N(AUTHENTICATION_FAILED) */
2054       else if (sa->state == IKEV2_STATE_AUTH_FAILED)
2055         {
2056           ikev2_set_state (sa, IKEV2_STATE_DELETED);
2057           goto done;
2058         }
2059       /* received unsupported critical payload */
2060       else if (sa->unsupported_cp)
2061         {
2062           u8 *data = vec_new (u8, 1);
2063
2064           data[0] = sa->unsupported_cp;
2065           ikev2_payload_add_notify (chain,
2066                                     IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2067                                     data);
2068           vec_free (data);
2069           sa->unsupported_cp = 0;
2070         }
2071       /* else send empty response */
2072     }
2073   else if (ike->exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
2074     {
2075       if (sa->is_initiator)
2076         {
2077
2078           ikev2_sa_proposal_t *proposals = (ikev2_sa_proposal_t *) user;
2079           ikev2_notify_t notify;
2080           u8 *data = vec_new (u8, 4);
2081           clib_memset (&notify, 0, sizeof (notify));
2082           notify.protocol_id = IKEV2_PROTOCOL_ESP;
2083           notify.spi = sa->childs[0].i_proposals->spi;
2084           *(u32 *) data = clib_host_to_net_u32 (notify.spi);
2085
2086           ikev2_payload_add_sa (chain, proposals);
2087           ikev2_payload_add_nonce (chain, sa->i_nonce);
2088           ikev2_payload_add_ts (chain, sa->childs[0].tsi, IKEV2_PAYLOAD_TSI);
2089           ikev2_payload_add_ts (chain, sa->childs[0].tsr, IKEV2_PAYLOAD_TSR);
2090           ikev2_payload_add_notify_2 (chain, IKEV2_NOTIFY_MSG_REKEY_SA, data,
2091                                       &notify);
2092
2093           vec_free (data);
2094         }
2095       else
2096         {
2097           if (sa->rekey)
2098             {
2099               ikev2_payload_add_sa (chain, sa->rekey[0].r_proposal);
2100               ikev2_payload_add_nonce (chain, sa->r_nonce);
2101               ikev2_payload_add_ts (chain, sa->rekey[0].tsi,
2102                                     IKEV2_PAYLOAD_TSI);
2103               ikev2_payload_add_ts (chain, sa->rekey[0].tsr,
2104                                     IKEV2_PAYLOAD_TSR);
2105               vec_del1 (sa->rekey, 0);
2106             }
2107           else if (sa->unsupported_cp)
2108             {
2109               u8 *data = vec_new (u8, 1);
2110
2111               data[0] = sa->unsupported_cp;
2112               ikev2_payload_add_notify (chain,
2113                                         IKEV2_NOTIFY_MSG_UNSUPPORTED_CRITICAL_PAYLOAD,
2114                                         data);
2115               vec_free (data);
2116               sa->unsupported_cp = 0;
2117             }
2118           else
2119             {
2120               ikev2_payload_add_notify (chain,
2121                                         IKEV2_NOTIFY_MSG_NO_ADDITIONAL_SAS,
2122                                         0);
2123             }
2124         }
2125     }
2126
2127   /* IKEv2 header */
2128   ike->version = IKE_VERSION_2;
2129   ike->nextpayload = IKEV2_PAYLOAD_SK;
2130   tlen = sizeof (*ike);
2131   if (sa->is_initiator)
2132     {
2133       ike->flags = IKEV2_HDR_FLAG_INITIATOR;
2134       sa->last_init_msg_id = clib_net_to_host_u32 (ike->msgid);
2135     }
2136   else
2137     {
2138       ike->flags = IKEV2_HDR_FLAG_RESPONSE;
2139     }
2140
2141
2142   if (ike->exchange == IKEV2_EXCHANGE_SA_INIT)
2143     {
2144       tlen += vec_len (chain->data);
2145       ike->nextpayload = chain->first_payload_type;
2146       ike->length = clib_host_to_net_u32 (tlen);
2147       clib_memcpy_fast (ike->payload, chain->data, vec_len (chain->data));
2148
2149       /* store whole IKE payload - needed for PSK auth */
2150       vec_free (sa->last_sa_init_res_packet_data);
2151       vec_add (sa->last_sa_init_res_packet_data, ike, tlen);
2152     }
2153   else
2154     {
2155
2156       ikev2_payload_chain_add_padding (chain, tr_encr->block_size);
2157
2158       /* SK payload */
2159       plen = sizeof (*ph);
2160       ph = (ike_payload_header_t *) & ike->payload[0];
2161       ph->nextpayload = chain->first_payload_type;
2162       ph->flags = 0;
2163       int enc_len = ikev2_encrypt_data (sa, chain->data, ph->payload);
2164       plen += enc_len;
2165
2166       /* add space for hmac */
2167       plen += tr_integ->key_trunc;
2168       tlen += plen;
2169
2170       /* payload and total length */
2171       ph->length = clib_host_to_net_u16 (plen);
2172       ike->length = clib_host_to_net_u32 (tlen);
2173
2174       /* calc integrity data for whole packet except hash itself */
2175       integ =
2176         ikev2_calc_integr (tr_integ, sa->is_initiator ? sa->sk_ai : sa->sk_ar,
2177                            (u8 *) ike, tlen - tr_integ->key_trunc);
2178
2179       clib_memcpy_fast (ike->payload + tlen - tr_integ->key_trunc -
2180                         sizeof (*ike), integ, tr_integ->key_trunc);
2181
2182       /* store whole IKE payload - needed for retransmit */
2183       vec_free (sa->last_res_packet_data);
2184       vec_add (sa->last_res_packet_data, ike, tlen);
2185     }
2186
2187 done:
2188   ikev2_payload_destroy_chain (chain);
2189   vec_free (integ);
2190   return tlen;
2191 }
2192
2193 static int
2194 ikev2_retransmit_sa_init (ike_header_t * ike,
2195                           ip4_address_t iaddr, ip4_address_t raddr)
2196 {
2197   ikev2_main_t *km = &ikev2_main;
2198   ikev2_sa_t *sa;
2199   u32 thread_index = vlib_get_thread_index ();
2200
2201   /* *INDENT-OFF* */
2202   pool_foreach (sa, km->per_thread_data[thread_index].sas, ({
2203     if (sa->ispi == clib_net_to_host_u64(ike->ispi) &&
2204         sa->iaddr.as_u32 == iaddr.as_u32 &&
2205         sa->raddr.as_u32 == raddr.as_u32)
2206       {
2207         int p = 0;
2208         u32 len = clib_net_to_host_u32(ike->length);
2209         u8 payload = ike->nextpayload;
2210
2211         while (p < len && payload!= IKEV2_PAYLOAD_NONE) {
2212           ike_payload_header_t * ikep = (ike_payload_header_t *) &ike->payload[p];
2213           u32 plen = clib_net_to_host_u16(ikep->length);
2214
2215           if (plen < sizeof(ike_payload_header_t))
2216             return -1;
2217
2218           if (payload == IKEV2_PAYLOAD_NONCE)
2219             {
2220               if (!memcmp(sa->i_nonce, ikep->payload, plen - sizeof(*ikep)))
2221                 {
2222                   /* req is retransmit */
2223                   if (sa->state == IKEV2_STATE_SA_INIT)
2224                     {
2225                       ike_header_t * tmp;
2226                       tmp = (ike_header_t*)sa->last_sa_init_res_packet_data;
2227                       ike->ispi = tmp->ispi;
2228                       ike->rspi = tmp->rspi;
2229                       ike->nextpayload = tmp->nextpayload;
2230                       ike->version = tmp->version;
2231                       ike->exchange = tmp->exchange;
2232                       ike->flags = tmp->flags;
2233                       ike->msgid = tmp->msgid;
2234                       ike->length = tmp->length;
2235                       clib_memcpy_fast(ike->payload, tmp->payload,
2236                              clib_net_to_host_u32(tmp->length) - sizeof(*ike));
2237                       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG,
2238                                              "ispi %lx IKE_SA_INIT retransmit "
2239                                              "from %d.%d.%d.%d to %d.%d.%d.%d",
2240                                              ike->ispi,
2241                                              raddr.as_u32, iaddr.as_u32);
2242                       return 1;
2243                     }
2244                   /* else ignore req */
2245                   else
2246                     {
2247                       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG,
2248                                              "ispi %lx IKE_SA_INIT ignore "
2249                                              "from %d.%d.%d.%d to %d.%d.%d.%d",
2250                                              ike->ispi,
2251                                              raddr.as_u32, iaddr.as_u32);
2252                       return -1;
2253                     }
2254                 }
2255             }
2256           payload = ikep->nextpayload;
2257           p+=plen;
2258         }
2259       }
2260   }));
2261   /* *INDENT-ON* */
2262
2263   /* req is not retransmit */
2264   return 0;
2265 }
2266
2267 static int
2268 ikev2_retransmit_resp (ikev2_sa_t * sa, ike_header_t * ike)
2269 {
2270   u32 msg_id = clib_net_to_host_u32 (ike->msgid);
2271
2272   /* new req */
2273   if (msg_id > sa->last_msg_id)
2274     {
2275       sa->last_msg_id = msg_id;
2276       return 0;
2277     }
2278   /* retransmitted req */
2279   else if (msg_id == sa->last_msg_id)
2280     {
2281       ike_header_t *tmp;
2282       tmp = (ike_header_t *) sa->last_res_packet_data;
2283       ike->ispi = tmp->ispi;
2284       ike->rspi = tmp->rspi;
2285       ike->nextpayload = tmp->nextpayload;
2286       ike->version = tmp->version;
2287       ike->exchange = tmp->exchange;
2288       ike->flags = tmp->flags;
2289       ike->msgid = tmp->msgid;
2290       ike->length = tmp->length;
2291       clib_memcpy_fast (ike->payload, tmp->payload,
2292                         clib_net_to_host_u32 (tmp->length) - sizeof (*ike));
2293       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG, "IKE retransmit msgid %d",
2294                              msg_id, sa->raddr.as_u32, sa->iaddr.as_u32);
2295       return 1;
2296     }
2297   /* old req ignore */
2298   else
2299     {
2300       ikev2_elog_uint_peers (IKEV2_LOG_DEBUG, "IKE req ignore msgid %d",
2301                              msg_id, sa->raddr.as_u32, sa->iaddr.as_u32);
2302     }
2303   return -1;
2304 }
2305
2306 static void
2307 ikev2_init_sa (vlib_main_t * vm, ikev2_sa_t * sa)
2308 {
2309   ikev2_main_t *km = &ikev2_main;
2310   sa->liveness_period_check = vlib_time_now (vm) + km->liveness_period;
2311 }
2312
2313 static uword
2314 ikev2_node_fn (vlib_main_t * vm,
2315                vlib_node_runtime_t * node, vlib_frame_t * frame)
2316 {
2317   u32 n_left_from, *from, *to_next;
2318   ikev2_next_t next_index;
2319   ikev2_main_t *km = &ikev2_main;
2320   u32 thread_index = vlib_get_thread_index ();
2321
2322   from = vlib_frame_vector_args (frame);
2323   n_left_from = frame->n_vectors;
2324   next_index = node->cached_next_index;
2325
2326   while (n_left_from > 0)
2327     {
2328       u32 n_left_to_next;
2329
2330       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2331
2332       while (n_left_from > 0 && n_left_to_next > 0)
2333         {
2334           u32 bi0;
2335           vlib_buffer_t *b0;
2336           u32 next0 = IKEV2_NEXT_ERROR_DROP;
2337           u32 sw_if_index0;
2338           ip4_header_t *ip40;
2339           udp_header_t *udp0;
2340           ike_header_t *ike0;
2341           ikev2_sa_t *sa0 = 0;
2342           ikev2_sa_t sa;        /* temporary store for SA */
2343           int len = 0;
2344           int r;
2345
2346           /* speculatively enqueue b0 to the current next frame */
2347           bi0 = from[0];
2348           to_next[0] = bi0;
2349           from += 1;
2350           to_next += 1;
2351           n_left_from -= 1;
2352           n_left_to_next -= 1;
2353
2354           b0 = vlib_get_buffer (vm, bi0);
2355           ike0 = vlib_buffer_get_current (b0);
2356           vlib_buffer_advance (b0, -sizeof (*udp0));
2357           udp0 = vlib_buffer_get_current (b0);
2358           vlib_buffer_advance (b0, -sizeof (*ip40));
2359           ip40 = vlib_buffer_get_current (b0);
2360
2361           if (ike0->version != IKE_VERSION_2)
2362             {
2363               vlib_node_increment_counter (vm, ikev2_node.index,
2364                                            IKEV2_ERROR_NOT_IKEV2, 1);
2365               goto dispatch0;
2366             }
2367
2368           if (ike0->exchange == IKEV2_EXCHANGE_SA_INIT)
2369             {
2370               sa0 = &sa;
2371               clib_memset (sa0, 0, sizeof (*sa0));
2372
2373               if (ike0->flags & IKEV2_HDR_FLAG_INITIATOR)
2374                 {
2375                   if (ike0->rspi == 0)
2376                     {
2377                       sa0->raddr.as_u32 = ip40->dst_address.as_u32;
2378                       sa0->iaddr.as_u32 = ip40->src_address.as_u32;
2379
2380                       r = ikev2_retransmit_sa_init (ike0, sa0->iaddr,
2381                                                     sa0->raddr);
2382                       if (r == 1)
2383                         {
2384                           vlib_node_increment_counter (vm, ikev2_node.index,
2385                                                        IKEV2_ERROR_IKE_SA_INIT_RETRANSMIT,
2386                                                        1);
2387                           len = clib_net_to_host_u32 (ike0->length);
2388                           goto dispatch0;
2389                         }
2390                       else if (r == -1)
2391                         {
2392                           vlib_node_increment_counter (vm, ikev2_node.index,
2393                                                        IKEV2_ERROR_IKE_SA_INIT_IGNORE,
2394                                                        1);
2395                           goto dispatch0;
2396                         }
2397
2398                       ikev2_process_sa_init_req (vm, sa0, ike0);
2399
2400                       if (sa0->state == IKEV2_STATE_SA_INIT)
2401                         {
2402                           ikev2_sa_free_proposal_vector (&sa0->r_proposals);
2403                           sa0->r_proposals =
2404                             ikev2_select_proposal (sa0->i_proposals,
2405                                                    IKEV2_PROTOCOL_IKE);
2406                           ikev2_generate_sa_init_data (sa0);
2407                         }
2408
2409                       if (sa0->state == IKEV2_STATE_SA_INIT
2410                           || sa0->state == IKEV2_STATE_NOTIFY_AND_DELETE)
2411                         {
2412                           len = ikev2_generate_message (sa0, ike0, 0);
2413                         }
2414
2415                       if (sa0->state == IKEV2_STATE_SA_INIT)
2416                         {
2417                           /* add SA to the pool */
2418                           pool_get (km->per_thread_data[thread_index].sas,
2419                                     sa0);
2420                           clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
2421                           ikev2_init_sa (vm, sa0);
2422                           hash_set (km->
2423                                     per_thread_data[thread_index].sa_by_rspi,
2424                                     sa0->rspi,
2425                                     sa0 -
2426                                     km->per_thread_data[thread_index].sas);
2427                         }
2428                       else
2429                         {
2430                           ikev2_sa_free_all_vec (sa0);
2431                         }
2432                     }
2433                 }
2434               else              //received sa_init without initiator flag
2435                 {
2436                   ikev2_process_sa_init_resp (vm, sa0, ike0);
2437
2438                   if (sa0->state == IKEV2_STATE_SA_INIT)
2439                     {
2440                       ike0->exchange = IKEV2_EXCHANGE_IKE_AUTH;
2441                       uword *p = hash_get (km->sa_by_ispi, ike0->ispi);
2442                       if (p)
2443                         {
2444                           ikev2_sa_t *sai =
2445                             pool_elt_at_index (km->sais, p[0]);
2446
2447                           if (sai->init_response_received)
2448                             {
2449                               /* we've already processed sa-init response */
2450                               sa0->state = IKEV2_STATE_UNKNOWN;
2451                             }
2452                           else
2453                             {
2454                               ikev2_complete_sa_data (sa0, sai);
2455                               ikev2_calc_keys (sa0);
2456                               ikev2_sa_auth_init (sa0);
2457                               len = ikev2_generate_message (sa0, ike0, 0);
2458                             }
2459                         }
2460                     }
2461
2462                   if (sa0->state == IKEV2_STATE_SA_INIT)
2463                     {
2464                       /* add SA to the pool */
2465                       pool_get (km->per_thread_data[thread_index].sas, sa0);
2466                       clib_memcpy_fast (sa0, &sa, sizeof (*sa0));
2467                       hash_set (km->per_thread_data[thread_index].sa_by_rspi,
2468                                 sa0->rspi,
2469                                 sa0 - km->per_thread_data[thread_index].sas);
2470                     }
2471                   else
2472                     {
2473                       ikev2_sa_free_all_vec (sa0);
2474                     }
2475                 }
2476             }
2477           else if (ike0->exchange == IKEV2_EXCHANGE_IKE_AUTH)
2478             {
2479               uword *p;
2480               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2481                             clib_net_to_host_u64 (ike0->rspi));
2482               if (p)
2483                 {
2484                   sa0 =
2485                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2486                                        p[0]);
2487
2488                   r = ikev2_retransmit_resp (sa0, ike0);
2489                   if (r == 1)
2490                     {
2491                       vlib_node_increment_counter (vm, ikev2_node.index,
2492                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2493                                                    1);
2494                       len = clib_net_to_host_u32 (ike0->length);
2495                       goto dispatch0;
2496                     }
2497                   else if (r == -1)
2498                     {
2499                       vlib_node_increment_counter (vm, ikev2_node.index,
2500                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2501                                                    1);
2502                       goto dispatch0;
2503                     }
2504
2505                   ikev2_process_auth_req (vm, sa0, ike0);
2506                   ikev2_sa_auth (sa0);
2507                   if (sa0->state == IKEV2_STATE_AUTHENTICATED)
2508                     {
2509                       ikev2_initial_contact_cleanup (sa0);
2510                       ikev2_sa_match_ts (sa0);
2511                       if (sa0->state != IKEV2_STATE_TS_UNACCEPTABLE)
2512                         ikev2_create_tunnel_interface (vm, thread_index, sa0,
2513                                                        &sa0->childs[0],
2514                                                        p[0], 0, 0);
2515                     }
2516
2517                   if (sa0->is_initiator)
2518                     {
2519                       uword *p = hash_get (km->sa_by_ispi, ike0->ispi);
2520                       if (p)
2521                         {
2522                           ikev2_sa_t *sai =
2523                             pool_elt_at_index (km->sais, p[0]);
2524                           hash_unset (km->sa_by_ispi, sai->ispi);
2525                           ikev2_sa_free_all_vec (sai);
2526                           pool_put (km->sais, sai);
2527                         }
2528                     }
2529                   else
2530                     {
2531                       len = ikev2_generate_message (sa0, ike0, 0);
2532                     }
2533                 }
2534             }
2535           else if (ike0->exchange == IKEV2_EXCHANGE_INFORMATIONAL)
2536             {
2537               uword *p;
2538               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2539                             clib_net_to_host_u64 (ike0->rspi));
2540               if (p)
2541                 {
2542                   sa0 =
2543                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2544                                        p[0]);
2545
2546                   r = ikev2_retransmit_resp (sa0, ike0);
2547                   if (r == 1)
2548                     {
2549                       vlib_node_increment_counter (vm, ikev2_node.index,
2550                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2551                                                    1);
2552                       len = clib_net_to_host_u32 (ike0->length);
2553                       goto dispatch0;
2554                     }
2555                   else if (r == -1)
2556                     {
2557                       vlib_node_increment_counter (vm, ikev2_node.index,
2558                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2559                                                    1);
2560                       goto dispatch0;
2561                     }
2562
2563                   ikev2_process_informational_req (vm, sa0, ike0);
2564                   if (sa0->del)
2565                     {
2566                       if (sa0->del[0].protocol_id != IKEV2_PROTOCOL_IKE)
2567                         {
2568                           ikev2_delete_t *d, *tmp, *resp = 0;
2569                           vec_foreach (d, sa0->del)
2570                           {
2571                             ikev2_child_sa_t *ch_sa;
2572                             ch_sa = ikev2_sa_get_child (sa0, d->spi,
2573                                                         d->protocol_id,
2574                                                         !sa0->is_initiator);
2575                             if (ch_sa)
2576                               {
2577                                 ikev2_delete_tunnel_interface (km->vnet_main,
2578                                                                sa0, ch_sa);
2579                                 if (!sa0->is_initiator)
2580                                   {
2581                                     vec_add2 (resp, tmp, 1);
2582                                     tmp->protocol_id = d->protocol_id;
2583                                     tmp->spi = ch_sa->r_proposals[0].spi;
2584                                   }
2585                                 ikev2_sa_del_child_sa (sa0, ch_sa);
2586                               }
2587                           }
2588                           if (!sa0->is_initiator)
2589                             {
2590                               vec_free (sa0->del);
2591                               sa0->del = resp;
2592                             }
2593                         }
2594                     }
2595                   if (!(ike0->flags & IKEV2_HDR_FLAG_RESPONSE))
2596                     {
2597                       ike0->flags |= IKEV2_HDR_FLAG_RESPONSE;
2598                       len = ikev2_generate_message (sa0, ike0, 0);
2599                     }
2600                 }
2601             }
2602           else if (ike0->exchange == IKEV2_EXCHANGE_CREATE_CHILD_SA)
2603             {
2604               uword *p;
2605               p = hash_get (km->per_thread_data[thread_index].sa_by_rspi,
2606                             clib_net_to_host_u64 (ike0->rspi));
2607               if (p)
2608                 {
2609                   sa0 =
2610                     pool_elt_at_index (km->per_thread_data[thread_index].sas,
2611                                        p[0]);
2612
2613                   r = ikev2_retransmit_resp (sa0, ike0);
2614                   if (r == 1)
2615                     {
2616                       vlib_node_increment_counter (vm, ikev2_node.index,
2617                                                    IKEV2_ERROR_IKE_REQ_RETRANSMIT,
2618                                                    1);
2619                       len = clib_net_to_host_u32 (ike0->length);
2620                       goto dispatch0;
2621                     }
2622                   else if (r == -1)
2623                     {
2624                       vlib_node_increment_counter (vm, ikev2_node.index,
2625                                                    IKEV2_ERROR_IKE_REQ_IGNORE,
2626                                                    1);
2627                       goto dispatch0;
2628                     }
2629
2630                   ikev2_process_create_child_sa_req (vm, sa0, ike0);
2631                   if (sa0->rekey)
2632                     {
2633                       if (sa0->rekey[0].protocol_id != IKEV2_PROTOCOL_IKE)
2634                         {
2635                           if (sa0->childs)
2636                             vec_free (sa0->childs);
2637                           ikev2_child_sa_t *child;
2638                           vec_add2 (sa0->childs, child, 1);
2639                           child->r_proposals = sa0->rekey[0].r_proposal;
2640                           child->i_proposals = sa0->rekey[0].i_proposal;
2641                           child->tsi = sa0->rekey[0].tsi;
2642                           child->tsr = sa0->rekey[0].tsr;
2643                           ikev2_create_tunnel_interface (vm, thread_index,
2644                                                          sa0, 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 = p - km->profiles;
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   km->liveness_period = IKEV2_LIVENESS_PERIOD_CHECK;
3710   km->liveness_max_retries = IKEV2_LIVENESS_RETRIES;
3711   ikev2_crypto_init (km);
3712
3713   mhash_init_vec_string (&km->profile_index_by_name, sizeof (uword));
3714
3715   vec_validate_aligned (km->per_thread_data, tm->n_vlib_mains - 1,
3716                         CLIB_CACHE_LINE_BYTES);
3717   for (thread_id = 0; thread_id < tm->n_vlib_mains - 1; thread_id++)
3718     {
3719       km->per_thread_data[thread_id].sa_by_rspi =
3720         hash_create (0, sizeof (uword));
3721     }
3722
3723   km->sa_by_ispi = hash_create (0, sizeof (uword));
3724   km->sw_if_indices = hash_create (0, 0);
3725   km->udp_ports = hash_create (0, sizeof (uword));
3726
3727   udp_register_dst_port (vm, 500, ikev2_node.index, 1);
3728
3729   ikev2_cli_reference ();
3730
3731   km->log_level = IKEV2_LOG_ERROR;
3732   km->log_class = vlib_log_register_class ("ikev2", 0);
3733   return 0;
3734 }
3735
3736 /* *INDENT-OFF* */
3737 VLIB_INIT_FUNCTION (ikev2_init) =
3738 {
3739   .runs_after = VLIB_INITS("ipsec_init"),
3740 };
3741 /* *INDENT-ON* */
3742
3743 static u8
3744 ikev2_mngr_process_child_sa (ikev2_sa_t * sa, ikev2_child_sa_t * csa,
3745                              u8 del_old_ids)
3746 {
3747   ikev2_main_t *km = &ikev2_main;
3748   ikev2_profile_t *p = 0;
3749   vlib_main_t *vm = km->vlib_main;
3750   f64 now = vlib_time_now (vm);
3751   u8 res = 0;
3752
3753   if (sa->is_profile_index_set)
3754     p = pool_elt_at_index (km->profiles, sa->profile_index);
3755
3756   if (sa->is_initiator && p && csa->time_to_expiration
3757       && now > csa->time_to_expiration)
3758     {
3759       if (!csa->is_expired || csa->rekey_retries > 0)
3760         {
3761           ikev2_rekey_child_sa_internal (vm, sa, csa);
3762           csa->time_to_expiration = now + p->handover;
3763           csa->is_expired = 1;
3764           if (csa->rekey_retries == 0)
3765             {
3766               csa->rekey_retries = 5;
3767             }
3768           else if (csa->rekey_retries > 0)
3769             {
3770               csa->rekey_retries--;
3771               ikev2_log_debug ("Rekeying Child SA 0x%x, retries left %d",
3772                                csa->i_proposals->spi, csa->rekey_retries);
3773               if (csa->rekey_retries == 0)
3774                 {
3775                   csa->rekey_retries = -1;
3776                 }
3777             }
3778           res |= 1;
3779         }
3780       else
3781         {
3782           csa->time_to_expiration = 0;
3783           ikev2_delete_child_sa_internal (vm, sa, csa);
3784           res |= 1;
3785         }
3786     }
3787
3788   if (del_old_ids)
3789     {
3790       ipip_tunnel_t *ipip = NULL;
3791       u32 sw_if_index = sa->is_tun_itf_set ? sa->tun_itf : ~0;
3792       if (~0 == sw_if_index)
3793         {
3794           ip46_address_t local_ip;
3795           ip46_address_t remote_ip;
3796           if (sa->is_initiator)
3797             {
3798               ip46_address_set_ip4 (&local_ip, &sa->iaddr);
3799               ip46_address_set_ip4 (&remote_ip, &sa->raddr);
3800             }
3801           else
3802             {
3803               ip46_address_set_ip4 (&local_ip, &sa->raddr);
3804               ip46_address_set_ip4 (&remote_ip, &sa->iaddr);
3805             }
3806
3807        /* *INDENT-OFF* */
3808        ipip_tunnel_key_t key = {
3809          .src = local_ip,
3810          .dst = remote_ip,
3811          .transport = IPIP_TRANSPORT_IP4,
3812          .fib_index = 0,
3813        };
3814        /* *INDENT-ON* */
3815
3816           ipip = ipip_tunnel_db_find (&key);
3817
3818           if (ipip)
3819             sw_if_index = ipip->sw_if_index;
3820           else
3821             return res;
3822         }
3823
3824       u32 *sas_in = NULL;
3825       vec_add1 (sas_in, csa->remote_sa_id);
3826       ipsec_tun_protect_update (sw_if_index, NULL, csa->local_sa_id, sas_in);
3827       ipsec_sa_unlock_id (ikev2_flip_alternate_sa_bit (csa->remote_sa_id));
3828     }
3829
3830   return res;
3831 }
3832
3833 int
3834 ikev2_set_log_level (ikev2_log_level_t log_level)
3835 {
3836   ikev2_main_t *km = &ikev2_main;
3837
3838   if (log_level >= IKEV2_LOG_MAX)
3839     {
3840       ikev2_log_error ("unknown logging level %d", log_level);
3841       return -1;
3842     }
3843
3844   km->log_level = log_level;
3845   return 0;
3846 }
3847
3848 clib_error_t *
3849 ikev2_set_liveness_params (u32 period, u32 max_retries)
3850 {
3851   ikev2_main_t *km = &ikev2_main;
3852
3853   if (period == 0 || max_retries == 0)
3854     return clib_error_return (0, "invalid args");
3855
3856   km->liveness_period = period;
3857   km->liveness_max_retries = max_retries;
3858   return 0;
3859 }
3860
3861 static void
3862 ikev2_mngr_process_ipsec_sa (ipsec_sa_t * ipsec_sa)
3863 {
3864   ikev2_main_t *km = &ikev2_main;
3865   vlib_main_t *vm = km->vlib_main;
3866   ikev2_main_per_thread_data_t *tkm;
3867   ikev2_sa_t *fsa = 0;
3868   ikev2_profile_t *p = 0;
3869   ikev2_child_sa_t *fchild = 0;
3870   f64 now = vlib_time_now (vm);
3871   vlib_counter_t counts;
3872
3873   /* Search for the SA and child SA */
3874   vec_foreach (tkm, km->per_thread_data)
3875   {
3876     ikev2_sa_t *sa;
3877     if (fchild)
3878       break;
3879     /* *INDENT-OFF* */
3880     pool_foreach (sa, tkm->sas, ({
3881       fchild = ikev2_sa_get_child(sa, ipsec_sa->spi, IKEV2_PROTOCOL_ESP, 1);
3882       if (fchild)
3883         {
3884           fsa = sa;
3885           break;
3886         }
3887     }));
3888     /* *INDENT-ON* */
3889   }
3890   vlib_get_combined_counter (&ipsec_sa_counters,
3891                              ipsec_sa->stat_index, &counts);
3892
3893   if (fsa && fsa->is_profile_index_set)
3894     p = pool_elt_at_index (km->profiles, fsa->profile_index);
3895
3896   if (fchild && p && p->lifetime_maxdata)
3897     {
3898       if (!fchild->is_expired && counts.bytes > p->lifetime_maxdata)
3899         {
3900           fchild->time_to_expiration = now;
3901         }
3902     }
3903 }
3904
3905 static void
3906 ikev2_process_pending_sa_init (ikev2_main_t * km)
3907 {
3908   u32 sai;
3909   u64 ispi;
3910   ikev2_sa_t *sa;
3911
3912   /* *INDENT-OFF* */
3913   hash_foreach (ispi, sai, km->sa_by_ispi,
3914   ({
3915     sa = pool_elt_at_index (km->sais, sai);
3916     if (sa->init_response_received)
3917       continue;
3918
3919     u32 bi0;
3920     if (vlib_buffer_alloc (km->vlib_main, &bi0, 1) != 1)
3921       return;
3922
3923     vlib_buffer_t * b = vlib_get_buffer (km->vlib_main, bi0);
3924     clib_memcpy_fast (vlib_buffer_get_current (b),
3925         sa->last_sa_init_req_packet_data,
3926         vec_len (sa->last_sa_init_req_packet_data));
3927     ikev2_send_ike (km->vlib_main, &sa->iaddr, &sa->raddr, bi0,
3928         vec_len (sa->last_sa_init_req_packet_data));
3929   }));
3930   /* *INDENT-ON* */
3931 }
3932
3933 static vlib_node_registration_t ikev2_mngr_process_node;
3934
3935 static void
3936 ikev2_send_informational_request (ikev2_sa_t * sa)
3937 {
3938   ikev2_main_t *km = &ikev2_main;
3939   ip4_address_t *src, *dst;
3940   ike_header_t *ike0;
3941   u32 bi0 = 0;
3942   int len;
3943
3944   bi0 = ikev2_get_new_ike_header_buff (km->vlib_main, &ike0);
3945
3946   ike0->exchange = IKEV2_EXCHANGE_INFORMATIONAL;
3947   ike0->ispi = clib_host_to_net_u64 (sa->ispi);
3948   ike0->rspi = clib_host_to_net_u64 (sa->rspi);
3949   ike0->msgid = clib_host_to_net_u32 (sa->last_init_msg_id + 1);
3950   sa->last_init_msg_id = clib_net_to_host_u32 (ike0->msgid);
3951   len = ikev2_generate_message (sa, ike0, 0);
3952
3953   if (sa->is_initiator)
3954     {
3955       src = &sa->iaddr;
3956       dst = &sa->raddr;
3957     }
3958   else
3959     {
3960
3961       dst = &sa->iaddr;
3962       src = &sa->raddr;
3963     }
3964
3965   ikev2_send_ike (km->vlib_main, src, dst, bi0, len);
3966 }
3967
3968 static_always_inline int
3969 ikev2_mngr_process_responder_sas (ikev2_sa_t * sa)
3970 {
3971   ikev2_main_t *km = &ikev2_main;
3972   vlib_main_t *vm = km->vlib_main;
3973
3974   if (!sa->sk_ai || !sa->sk_ar)
3975     return 0;
3976
3977   if (sa->liveness_retries >= km->liveness_max_retries)
3978     return 1;
3979
3980   f64 now = vlib_time_now (vm);
3981
3982   if (sa->liveness_period_check < now)
3983     {
3984       sa->liveness_retries++;
3985       sa->liveness_period_check = now + km->liveness_period;
3986       ikev2_send_informational_request (sa);
3987     }
3988   return 0;
3989 }
3990
3991 static uword
3992 ikev2_mngr_process_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
3993                        vlib_frame_t * f)
3994 {
3995   ikev2_main_t *km = &ikev2_main;
3996   ipsec_main_t *im = &ipsec_main;
3997   ikev2_profile_t *p;
3998   ikev2_child_sa_t *c;
3999   u32 *sai;
4000
4001   while (1)
4002     {
4003       u8 req_sent = 0;
4004       vlib_process_wait_for_event_or_clock (vm, 1);
4005       vlib_process_get_events (vm, NULL);
4006
4007       /* process ike child sas */
4008       ikev2_main_per_thread_data_t *tkm;
4009       vec_foreach (tkm, km->per_thread_data)
4010       {
4011         ikev2_sa_t *sa;
4012         u32 *to_be_deleted = 0;
4013
4014         /* *INDENT-OFF* */
4015         pool_foreach (sa, tkm->sas, ({
4016           ikev2_child_sa_t *c;
4017           u8 del_old_ids = 0;
4018           if (sa->old_remote_id_present && 0 > sa->old_id_expiration)
4019             {
4020               sa->old_remote_id_present = 0;
4021               del_old_ids = 1;
4022             }
4023           else
4024             sa->old_id_expiration -= 1;
4025
4026           vec_foreach (c, sa->childs)
4027             {
4028             req_sent |= ikev2_mngr_process_child_sa(sa, c, del_old_ids);
4029             }
4030
4031           if (ikev2_mngr_process_responder_sas (sa))
4032             vec_add1 (to_be_deleted, sa - tkm->sas);
4033         }));
4034         /* *INDENT-ON* */
4035
4036         vec_foreach (sai, to_be_deleted)
4037         {
4038           sa = pool_elt_at_index (tkm->sas, sai[0]);
4039           if (sa->is_initiator && sa->is_profile_index_set)
4040             {
4041               p = pool_elt_at_index (km->profiles, sa->profile_index);
4042               if (p)
4043                 {
4044                   ikev2_initiate_sa_init (vm, p->name);
4045                   continue;
4046                 }
4047             }
4048           vec_foreach (c, sa->childs)
4049             ikev2_delete_tunnel_interface (km->vnet_main, sa, c);
4050           hash_unset (tkm->sa_by_rspi, sa->rspi);
4051           pool_put (tkm->sas, sa);
4052         }
4053       }
4054
4055       /* process ipsec sas */
4056       ipsec_sa_t *sa;
4057       /* *INDENT-OFF* */
4058       pool_foreach (sa, im->sad, ({
4059         ikev2_mngr_process_ipsec_sa(sa);
4060       }));
4061       /* *INDENT-ON* */
4062
4063       ikev2_process_pending_sa_init (km);
4064
4065       if (req_sent)
4066         {
4067           vlib_process_wait_for_event_or_clock (vm, 5);
4068           vlib_process_get_events (vm, NULL);
4069           req_sent = 0;
4070         }
4071
4072     }
4073   return 0;
4074 }
4075
4076 /* *INDENT-OFF* */
4077 VLIB_REGISTER_NODE (ikev2_mngr_process_node, static) = {
4078     .function = ikev2_mngr_process_fn,
4079     .type = VLIB_NODE_TYPE_PROCESS,
4080     .name =
4081     "ikev2-manager-process",
4082 };
4083
4084 VLIB_PLUGIN_REGISTER () = {
4085     .version = VPP_BUILD_VER,
4086     .description = "Internet Key Exchange (IKEv2) Protocol",
4087 };
4088 /* *INDENT-ON* */
4089
4090 /*
4091  * fd.io coding-style-patch-verification: ON
4092  *
4093  * Local Variables:
4094  * eval: (c-set-style "gnu")
4095  * End:
4096  */