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