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