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