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