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