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