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