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