/* * Copyright (c) 2015 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include #include #include #include #include #include #include ikev2_main_t ikev2_main; static int ikev2_delete_tunnel_interface (vnet_main_t * vnm, ikev2_sa_t * sa, ikev2_child_sa_t * child); #define ikev2_set_state(sa, v) do { \ (sa)->state = v; \ clib_warning("sa state changed to " #v); \ } while(0); typedef struct { u32 next_index; u32 sw_if_index; } ikev2_trace_t; static u8 * format_ikev2_trace (u8 * s, va_list * args) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *); ikev2_trace_t *t = va_arg (*args, ikev2_trace_t *); s = format (s, "ikev2: sw_if_index %d, next index %d", t->sw_if_index, t->next_index); return s; } static vlib_node_registration_t ikev2_node; #define foreach_ikev2_error \ _(PROCESSED, "IKEv2 packets processed") \ _(IKE_SA_INIT_RETRANSMIT, "IKE_SA_INIT retransmit ") \ _(IKE_SA_INIT_IGNORE, "IKE_SA_INIT ignore (IKE SA already auth)") \ _(IKE_REQ_RETRANSMIT, "IKE request retransmit") \ _(IKE_REQ_IGNORE, "IKE request ignore (old msgid)") \ _(NOT_IKEV2, "Non IKEv2 packets received") typedef enum { #define _(sym,str) IKEV2_ERROR_##sym, foreach_ikev2_error #undef _ IKEV2_N_ERROR, } ikev2_error_t; static char *ikev2_error_strings[] = { #define _(sym,string) string, foreach_ikev2_error #undef _ }; typedef enum { IKEV2_NEXT_IP4_LOOKUP, IKEV2_NEXT_ERROR_DROP, IKEV2_N_NEXT, } ikev2_next_t; static ikev2_sa_transform_t * ikev2_find_transform_data (ikev2_sa_transform_t * t) { ikev2_main_t *km = &ikev2_main; ikev2_sa_transform_t *td; vec_foreach (td, km->supported_transforms) { if (td->type != t->type) continue; if (td->transform_id != t->transform_id) continue; if (td->type == IKEV2_TRANSFORM_TYPE_ENCR) { if (vec_len (t->attrs) != 4 || t->attrs[0] != 0x80 || t->attrs[1] != 14) continue; if (((t->attrs[2] << 8 | t->attrs[3]) / 8) != td->key_len) continue; } return td; } return 0; } static ikev2_sa_proposal_t * ikev2_select_proposal (ikev2_sa_proposal_t * proposals, ikev2_protocol_id_t prot_id) { ikev2_sa_proposal_t *rv = 0; ikev2_sa_proposal_t *proposal; ikev2_sa_transform_t *transform, *new_t; u8 mandatory_bitmap, optional_bitmap; if (prot_id == IKEV2_PROTOCOL_IKE) { mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_ENCR) | (1 << IKEV2_TRANSFORM_TYPE_PRF) | (1 << IKEV2_TRANSFORM_TYPE_INTEG) | (1 << IKEV2_TRANSFORM_TYPE_DH); optional_bitmap = mandatory_bitmap; } else if (prot_id == IKEV2_PROTOCOL_ESP) { mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_ENCR) | (1 << IKEV2_TRANSFORM_TYPE_ESN); optional_bitmap = mandatory_bitmap | (1 << IKEV2_TRANSFORM_TYPE_INTEG) | (1 << IKEV2_TRANSFORM_TYPE_DH); } else if (prot_id == IKEV2_PROTOCOL_AH) { mandatory_bitmap = (1 << IKEV2_TRANSFORM_TYPE_INTEG) | (1 << IKEV2_TRANSFORM_TYPE_ESN); optional_bitmap = mandatory_bitmap | (1 << IKEV2_TRANSFORM_TYPE_DH); } else return 0; vec_add2 (rv, proposal, 1); vec_foreach (proposal, proposals) { u8 bitmap = 0; if (proposal->protocol_id != prot_id) continue; vec_foreach (transform, proposal->transforms) { if ((1 << transform->type) & bitmap) continue; if (ikev2_find_transform_data (transform)) { bitmap |= 1 << transform->type; vec_add2 (rv->transforms, new_t, 1); clib_memcpy (new_t, transform, sizeof (*new_t)); new_t->attrs = vec_dup (transform->attrs); } } clib_warning ("bitmap is %x mandatory is %x optional is %x", bitmap, mandatory_bitmap, optional_bitmap); if ((bitmap & mandatory_bitmap) == mandatory_bitmap && (bitmap & ~optional_bitmap) == 0) { rv->proposal_num = proposal->proposal_num; rv->protocol_id = proposal->protocol_id; RAND_bytes ((u8 *) & rv->spi, sizeof (rv->spi)); goto done; } else { vec_free (rv->transforms); } } vec_free (rv); done: return rv; } ikev2_sa_transform_t * ikev2_sa_get_td_for_type (ikev2_sa_proposal_t * p, ikev2_transform_type_t type) { ikev2_sa_transform_t *t; if (!p) return 0; vec_foreach (t, p->transforms) { if (t->type == type) return ikev2_find_transform_data (t); } return 0; } ikev2_child_sa_t * ikev2_sa_get_child (ikev2_sa_t * sa, u32 spi, ikev2_protocol_id_t prot_id, int by_initiator) { ikev2_child_sa_t *c; vec_foreach (c, sa->childs) { ikev2_sa_proposal_t *proposal = by_initiator ? &c->i_proposals[0] : &c->r_proposals[0]; if (proposal && proposal->spi == spi && proposal->protocol_id == prot_id) return c; } return 0; } void ikev2_sa_free_proposal_vector (ikev2_sa_proposal_t ** v) { ikev2_sa_proposal_t *p; ikev2_sa_transform_t *t; if (!*v) return; vec_foreach (p, *v) { vec_foreach (t, p->transforms) { vec_free (t->attrs); } vec_free (p->transforms); } vec_free (*v); }; static void ikev2_sa_free_all_child_sa (ikev2_child_sa_t ** childs) { ikev2_child_sa_t *c; vec_foreach (c, *childs) { ikev2_sa_free_proposal_vector (&c->r_proposals); ikev2_sa_free_proposal_vector (&c->i_proposals); vec_free (c->sk_ai); vec_free (c->sk_ar); vec_free (c->sk_ei); vec_free (c->sk_er); } vec_free (*childs); } static void ikev2_sa_del_child_sa (ikev2_sa_t * sa, ikev2_child_sa_t * child) { ikev2_sa_free_proposal_vector (&child->r_proposals); ikev2_sa_free_proposal_vector (&child->i_proposals); vec_free (child->sk_ai); vec_free (child->sk_ar); vec_free (child->sk_ei); vec_free (child->sk_er); vec_del1 (sa->childs, child - sa->childs); } static void ikev2_sa_free_all_vec (ikev2_sa_t * sa) { vec_free (sa->i_nonce); vec_free (sa->i_dh_data); vec_free (sa->dh_shared_key); vec_free (sa->dh_private_key); ikev2_sa_free_proposal_vector (&sa->r_proposals); ikev2_sa_free_proposal_vector (&sa->i_proposals); vec_free (sa->sk_d); vec_free (sa->sk_ai); vec_free (sa->sk_ar); vec_free (sa->sk_ei); vec_free (sa->sk_er); vec_free (sa->sk_pi); vec_free (sa->sk_pr); vec_free (sa->i_id.data); vec_free (sa->i_auth.data); vec_free (sa->r_id.data); vec_free (sa->r_auth.data); if (sa->r_auth.key) EVP_PKEY_free (sa->r_auth.key); vec_free (sa->del); ikev2_sa_free_all_child_sa (&sa->childs); } static void ikev2_delete_sa (ikev2_sa_t * sa) { ikev2_main_t *km = &ikev2_main; u32 thread_index = vlib_get_thread_index (); uword *p; ikev2_sa_free_all_vec (sa); p = hash_get (km->per_thread_data[thread_index].sa_by_rspi, sa->rspi); if (p) { hash_unset (km->per_thread_data[thread_index].sa_by_rspi, sa->rspi); pool_put (km->per_thread_data[thread_index].sas, sa); } } static void ikev2_generate_sa_init_data (ikev2_sa_t * sa) { ikev2_sa_transform_t *t = 0, *t2; ikev2_main_t *km = &ikev2_main; if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE) { return; } /* check if received DH group is on our list of supported groups */ vec_foreach (t2, km->supported_transforms) { if (t2->type == IKEV2_TRANSFORM_TYPE_DH && sa->dh_group == t2->dh_type) { t = t2; break; } } if (!t) { clib_warning ("unknown dh data group %u (data len %u)", sa->dh_group, vec_len (sa->i_dh_data)); sa->dh_group = IKEV2_TRANSFORM_DH_TYPE_NONE; return; } if (sa->is_initiator) { /* generate rspi */ RAND_bytes ((u8 *) & sa->ispi, 8); /* generate nonce */ sa->i_nonce = vec_new (u8, IKEV2_NONCE_SIZE); RAND_bytes ((u8 *) sa->i_nonce, IKEV2_NONCE_SIZE); } else { /* generate rspi */ RAND_bytes ((u8 *) & sa->rspi, 8); /* generate nonce */ sa->r_nonce = vec_new (u8, IKEV2_NONCE_SIZE); RAND_bytes ((u8 *) sa->r_nonce, IKEV2_NONCE_SIZE); } /* generate dh keys */ ikev2_generate_dh (sa, t); } static void ikev2_complete_sa_data (ikev2_sa_t * sa, ikev2_sa_t * sai) { ikev2_sa_transform_t *t = 0, *t2; ikev2_main_t *km = &ikev2_main; /*move some data to the new SA */ #define _(A) ({void* __tmp__ = (A); (A) = 0; __tmp__;}) sa->i_nonce = _(sai->i_nonce); sa->i_dh_data = _(sai->i_dh_data); sa->dh_private_key = _(sai->dh_private_key); sa->iaddr.as_u32 = sai->iaddr.as_u32; sa->raddr.as_u32 = sai->raddr.as_u32; sa->is_initiator = sai->is_initiator; sa->profile = sai->profile; sa->i_id.type = sai->i_id.type; sa->i_id.data = _(sai->i_id.data); sa->i_auth.method = sai->i_auth.method; sa->i_auth.hex = sai->i_auth.hex; sa->i_auth.data = _(sai->i_auth.data); sa->i_auth.key = _(sai->i_auth.key); sa->last_sa_init_req_packet_data = _(sai->last_sa_init_req_packet_data); sa->childs = _(sai->childs); #undef _ if (sa->dh_group == IKEV2_TRANSFORM_DH_TYPE_NONE) { return; } /* check if received DH group is on our list of supported groups */ vec_foreach (t2, km->supported_transforms) { if (t2->type == IKEV2_TRANSFORM_TYPE_DH && sa->dh_group == t2->dh_type) { t = t2; break; } } if (!t) { clib_warning ("unknown dh data group %u (data len %u)", sa->dh_group, vec_len (sa->i_dh_data)); sa->dh_group = IKEV2_TRANSFORM_DH_TYPE_NONE; return; } /* generate dh keys */ ikev2_complete_dh (sa, t); } static void ikev2_calc_keys (ikev2_sa_t * sa) { u8 *tmp; /* calculate SKEYSEED = prf(Ni | Nr, g^ir) */ u8 *skeyseed = 0; u8 *s = 0; ikev2_sa_transform_t *tr_encr, *tr_prf, *tr_integ; tr_encr = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR); tr_prf = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF); tr_integ = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG); vec_append (s, sa->i_nonce); vec_append (s, sa->r_nonce); skeyseed = ikev2_calc_prf (tr_prf, s, sa->dh_shared_key); /* Calculate S = Ni | Nr | SPIi | SPIr */ u64 *spi; vec_add2 (s, tmp, 2 * sizeof (*spi)); spi = (u64 *) tmp; spi[0] = clib_host_to_net_u64 (sa->ispi); spi[1] = clib_host_to_net_u64 (sa->rspi); /* calculate PRFplus */ u8 *keymat; int len = tr_prf->key_trunc + /* SK_d */ tr_integ->key_len * 2 + /* SK_ai, SK_ar */ tr_encr->key_len * 2 + /* SK_ei, SK_er */ tr_prf->key_len * 2; /* SK_pi, SK_pr */ keymat = ikev2_calc_prfplus (tr_prf, skeyseed, s, len); vec_free (skeyseed); vec_free (s); int pos = 0; /* SK_d */ sa->sk_d = vec_new (u8, tr_prf->key_trunc); clib_memcpy (sa->sk_d, keymat + pos, tr_prf->key_trunc); pos += tr_prf->key_trunc; /* SK_ai */ sa->sk_ai = vec_new (u8, tr_integ->key_len); clib_memcpy (sa->sk_ai, keymat + pos, tr_integ->key_len); pos += tr_integ->key_len; /* SK_ar */ sa->sk_ar = vec_new (u8, tr_integ->key_len); clib_memcpy (sa->sk_ar, keymat + pos, tr_integ->key_len); pos += tr_integ->key_len; /* SK_ei */ sa->sk_ei = vec_new (u8, tr_encr->key_len); clib_memcpy (sa->sk_ei, keymat + pos, tr_encr->key_len); pos += tr_encr->key_len; /* SK_er */ sa->sk_er = vec_new (u8, tr_encr->key_len); clib_memcpy (sa->sk_er, keymat + pos, tr_encr->key_len); pos += tr_encr->key_len; /* SK_pi */ sa->sk_pi = vec_new (u8, tr_prf->key_len); clib_memcpy (sa->sk_pi, keymat + pos, tr_prf->key_len); pos += tr_prf->key_len; /* SK_pr */ sa->sk_pr = vec_new (u8, tr_prf->key_len); clib_memcpy (sa->sk_pr, keymat + pos, tr_prf->key_len); pos += tr_prf->key_len; vec_free (keymat); } static void ikev2_calc_child_keys (ikev2_sa_t * sa, ikev2_child_sa_t * child) { u8 *s = 0; ikev2_sa_transform_t *tr_prf, *ctr_encr, *ctr_integ; tr_prf = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF); ctr_encr = ikev2_sa_get_td_for_type (child->r_proposals, IKEV2_TRANSFORM_TYPE_ENCR); ctr_integ = ikev2_sa_get_td_for_type (child->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG); vec_append (s, sa->i_nonce); vec_append (s, sa->r_nonce); /* calculate PRFplus */ u8 *keymat; int len = ctr_encr->key_len * 2 + ctr_integ->key_len * 2; keymat = ikev2_calc_prfplus (tr_prf, sa->sk_d, s, len); int pos = 0; /* SK_ei */ child->sk_ei = vec_new (u8, ctr_encr->key_len); clib_memcpy (child->sk_ei, keymat + pos, ctr_encr->key_len); pos += ctr_encr->key_len; /* SK_ai */ child->sk_ai = vec_new (u8, ctr_integ->key_len); clib_memcpy (child->sk_ai, keymat + pos, ctr_integ->key_len); pos += ctr_integ->key_len; /* SK_er */ child->sk_er = vec_new (u8, ctr_encr->key_len); clib_memcpy (child->sk_er, keymat + pos, ctr_encr->key_len); pos += ctr_encr->key_len; /* SK_ar */ child->sk_ar = vec_new (u8, ctr_integ->key_len); clib_memcpy (child->sk_ar, keymat + pos, ctr_integ->key_len); pos += ctr_integ->key_len; ASSERT (pos == len); vec_free (keymat); } static void ikev2_process_sa_init_req (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike) { int p = 0; u32 len = clib_net_to_host_u32 (ike->length); u8 payload = ike->nextpayload; clib_warning ("ispi %lx rspi %lx nextpayload %x version %x " "exchange %x flags %x msgid %x length %u", clib_net_to_host_u64 (ike->ispi), clib_net_to_host_u64 (ike->rspi), payload, ike->version, ike->exchange, ike->flags, clib_net_to_host_u32 (ike->msgid), len); sa->ispi = clib_net_to_host_u64 (ike->ispi); /* store whole IKE payload - needed for PSK auth */ vec_free (sa->last_sa_init_req_packet_data); vec_add (sa->last_sa_init_req_packet_data, ike, len); while (p < len && payload != IKEV2_PAYLOAD_NONE) { ike_payload_header_t *ikep = (ike_payload_header_t *) & ike->payload[p]; u32 plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (ike_payload_header_t)) return; if (payload == IKEV2_PAYLOAD_SA) { ikev2_sa_free_proposal_vector (&sa->i_proposals); sa->i_proposals = ikev2_parse_sa_payload (ikep); } else if (payload == IKEV2_PAYLOAD_KE) { ike_ke_payload_header_t *ke = (ike_ke_payload_header_t *) ikep; sa->dh_group = clib_net_to_host_u16 (ke->dh_group); vec_free (sa->i_dh_data); vec_add (sa->i_dh_data, ke->payload, plen - sizeof (*ke)); } else if (payload == IKEV2_PAYLOAD_NONCE) { vec_free (sa->i_nonce); vec_add (sa->i_nonce, ikep->payload, plen - sizeof (*ikep)); } else if (payload == IKEV2_PAYLOAD_NOTIFY) { ikev2_notify_t *n = ikev2_parse_notify_payload (ikep); vec_free (n); } else if (payload == IKEV2_PAYLOAD_VENDOR) { ikev2_parse_vendor_payload (ikep); } else { clib_warning ("unknown payload %u flags %x length %u", payload, ikep->flags, plen); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE); sa->unsupported_cp = payload; return; } } payload = ikep->nextpayload; p += plen; } ikev2_set_state (sa, IKEV2_STATE_SA_INIT); } static void ikev2_process_sa_init_resp (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike) { int p = 0; u32 len = clib_net_to_host_u32 (ike->length); u8 payload = ike->nextpayload; clib_warning ("ispi %lx rspi %lx nextpayload %x version %x " "exchange %x flags %x msgid %x length %u", clib_net_to_host_u64 (ike->ispi), clib_net_to_host_u64 (ike->rspi), payload, ike->version, ike->exchange, ike->flags, clib_net_to_host_u32 (ike->msgid), len); sa->ispi = clib_net_to_host_u64 (ike->ispi); sa->rspi = clib_net_to_host_u64 (ike->rspi); /* store whole IKE payload - needed for PSK auth */ vec_free (sa->last_sa_init_res_packet_data); vec_add (sa->last_sa_init_res_packet_data, ike, len); while (p < len && payload != IKEV2_PAYLOAD_NONE) { ike_payload_header_t *ikep = (ike_payload_header_t *) & ike->payload[p]; u32 plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (ike_payload_header_t)) return; if (payload == IKEV2_PAYLOAD_SA) { ikev2_sa_free_proposal_vector (&sa->r_proposals); sa->r_proposals = ikev2_parse_sa_payload (ikep); if (sa->r_proposals) { ikev2_set_state (sa, IKEV2_STATE_SA_INIT); ike->msgid = clib_host_to_net_u32 (clib_net_to_host_u32 (ike->msgid) + 1); } } else if (payload == IKEV2_PAYLOAD_KE) { ike_ke_payload_header_t *ke = (ike_ke_payload_header_t *) ikep; sa->dh_group = clib_net_to_host_u16 (ke->dh_group); vec_free (sa->r_dh_data); vec_add (sa->r_dh_data, ke->payload, plen - sizeof (*ke)); } else if (payload == IKEV2_PAYLOAD_NONCE) { vec_free (sa->r_nonce); vec_add (sa->r_nonce, ikep->payload, plen - sizeof (*ikep)); } else if (payload == IKEV2_PAYLOAD_NOTIFY) { ikev2_notify_t *n = ikev2_parse_notify_payload (ikep); vec_free (n); } else if (payload == IKEV2_PAYLOAD_VENDOR) { ikev2_parse_vendor_payload (ikep); } else { clib_warning ("unknown payload %u flags %x length %u", payload, ikep->flags, plen); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE); sa->unsupported_cp = payload; return; } } payload = ikep->nextpayload; p += plen; } } static u8 * ikev2_decrypt_sk_payload (ikev2_sa_t * sa, ike_header_t * ike, u8 * payload) { int p = 0; u8 last_payload = 0; u8 *hmac = 0; u32 len = clib_net_to_host_u32 (ike->length); ike_payload_header_t *ikep = 0; u32 plen = 0; ikev2_sa_transform_t *tr_integ; tr_integ = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_INTEG); while (p < len && *payload != IKEV2_PAYLOAD_NONE && last_payload != IKEV2_PAYLOAD_SK) { ikep = (ike_payload_header_t *) & ike->payload[p]; plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (*ikep)) return 0; if (*payload == IKEV2_PAYLOAD_SK) { clib_warning ("received IKEv2 payload SK, len %u", plen - 4); last_payload = *payload; } else { clib_warning ("unknown payload %u flags %x length %u", payload, ikep->flags, plen); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { sa->unsupported_cp = *payload; return 0; } } *payload = ikep->nextpayload; p += plen; } if (last_payload != IKEV2_PAYLOAD_SK) { clib_warning ("Last payload must be SK"); return 0; } hmac = ikev2_calc_integr (tr_integ, sa->is_initiator ? sa->sk_ar : sa->sk_ai, (u8 *) ike, len - tr_integ->key_trunc); plen = plen - sizeof (*ikep) - tr_integ->key_trunc; if (memcmp (hmac, &ikep->payload[plen], tr_integ->key_trunc)) { clib_warning ("message integrity check failed"); vec_free (hmac); return 0; } vec_free (hmac); return ikev2_decrypt_data (sa, ikep->payload, plen); } static void ikev2_initial_contact_cleanup (ikev2_sa_t * sa) { ikev2_main_t *km = &ikev2_main; ikev2_sa_t *tmp; u32 i, *delete = 0; ikev2_child_sa_t *c; u32 thread_index = vlib_get_thread_index (); if (!sa->initial_contact) return; /* find old IKE SAs with the same authenticated identity */ /* *INDENT-OFF* */ pool_foreach (tmp, km->per_thread_data[thread_index].sas, ({ if (tmp->i_id.type != sa->i_id.type || vec_len(tmp->i_id.data) != vec_len(sa->i_id.data) || memcmp(sa->i_id.data, tmp->i_id.data, vec_len(sa->i_id.data))) continue; if (sa->rspi != tmp->rspi) vec_add1(delete, tmp - km->per_thread_data[thread_index].sas); })); /* *INDENT-ON* */ for (i = 0; i < vec_len (delete); i++) { tmp = pool_elt_at_index (km->per_thread_data[thread_index].sas, delete[i]); vec_foreach (c, tmp->childs) ikev2_delete_tunnel_interface (km->vnet_main, tmp, c); ikev2_delete_sa (tmp); } vec_free (delete); sa->initial_contact = 0; } static void ikev2_process_auth_req (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike) { ikev2_child_sa_t *first_child_sa; int p = 0; u32 len = clib_net_to_host_u32 (ike->length); u8 payload = ike->nextpayload; u8 *plaintext = 0; ike_payload_header_t *ikep; u32 plen; clib_warning ("ispi %lx rspi %lx nextpayload %x version %x " "exchange %x flags %x msgid %x length %u", clib_net_to_host_u64 (ike->ispi), clib_net_to_host_u64 (ike->rspi), payload, ike->version, ike->exchange, ike->flags, clib_net_to_host_u32 (ike->msgid), len); ikev2_calc_keys (sa); plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload); if (!plaintext) { if (sa->unsupported_cp) ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE); goto cleanup_and_exit; } /* select or create 1st child SA */ if (sa->is_initiator) { first_child_sa = &sa->childs[0]; } else { ikev2_sa_free_all_child_sa (&sa->childs); vec_add2 (sa->childs, first_child_sa, 1); } /* process encrypted payload */ p = 0; while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE) { ikep = (ike_payload_header_t *) & plaintext[p]; plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (ike_payload_header_t)) goto cleanup_and_exit; if (payload == IKEV2_PAYLOAD_SA) /* 33 */ { clib_warning ("received payload SA, len %u", plen - sizeof (*ikep)); if (sa->is_initiator) { ikev2_sa_free_proposal_vector (&first_child_sa->r_proposals); first_child_sa->r_proposals = ikev2_parse_sa_payload (ikep); } else { ikev2_sa_free_proposal_vector (&first_child_sa->i_proposals); first_child_sa->i_proposals = ikev2_parse_sa_payload (ikep); } } else if (payload == IKEV2_PAYLOAD_IDI) /* 35 */ { ike_id_payload_header_t *id = (ike_id_payload_header_t *) ikep; sa->i_id.type = id->id_type; vec_free (sa->i_id.data); vec_add (sa->i_id.data, id->payload, plen - sizeof (*id)); clib_warning ("received payload IDi, len %u id_type %u", plen - sizeof (*id), id->id_type); } else if (payload == IKEV2_PAYLOAD_IDR) /* 36 */ { ike_id_payload_header_t *id = (ike_id_payload_header_t *) ikep; sa->r_id.type = id->id_type; vec_free (sa->r_id.data); vec_add (sa->r_id.data, id->payload, plen - sizeof (*id)); clib_warning ("received payload IDr len %u id_type %u", plen - sizeof (*id), id->id_type); } else if (payload == IKEV2_PAYLOAD_AUTH) /* 39 */ { ike_auth_payload_header_t *a = (ike_auth_payload_header_t *) ikep; if (sa->is_initiator) { sa->r_auth.method = a->auth_method; vec_free (sa->r_auth.data); vec_add (sa->r_auth.data, a->payload, plen - sizeof (*a)); } else { sa->i_auth.method = a->auth_method; vec_free (sa->i_auth.data); vec_add (sa->i_auth.data, a->payload, plen - sizeof (*a)); } clib_warning ("received payload AUTH, len %u auth_type %u", plen - sizeof (*a), a->auth_method); } else if (payload == IKEV2_PAYLOAD_NOTIFY) /* 41 */ { ikev2_notify_t *n = ikev2_parse_notify_payload (ikep); if (n->msg_type == IKEV2_NOTIFY_MSG_INITIAL_CONTACT) { sa->initial_contact = 1; } vec_free (n); } else if (payload == IKEV2_PAYLOAD_VENDOR) /* 43 */ { ikev2_parse_vendor_payload (ikep); } else if (payload == IKEV2_PAYLOAD_TSI) /* 44 */ { clib_warning ("received payload TSi, len %u", plen - sizeof (*ikep)); vec_free (first_child_sa->tsi); first_child_sa->tsi = ikev2_parse_ts_payload (ikep); } else if (payload == IKEV2_PAYLOAD_TSR) /* 45 */ { clib_warning ("received payload TSr, len %u", plen - sizeof (*ikep)); vec_free (first_child_sa->tsr); first_child_sa->tsr = ikev2_parse_ts_payload (ikep); } else { clib_warning ("unknown payload %u flags %x length %u data %u", payload, ikep->flags, plen - 4, format_hex_bytes, ikep->payload, plen - 4); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { ikev2_set_state (sa, IKEV2_STATE_NOTIFY_AND_DELETE); sa->unsupported_cp = payload; return; } } payload = ikep->nextpayload; p += plen; } cleanup_and_exit: vec_free (plaintext); } static void ikev2_process_informational_req (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike) { int p = 0; u32 len = clib_net_to_host_u32 (ike->length); u8 payload = ike->nextpayload; u8 *plaintext = 0; ike_payload_header_t *ikep; u32 plen; clib_warning ("ispi %lx rspi %lx nextpayload %x version %x " "exchange %x flags %x msgid %x length %u", clib_net_to_host_u64 (ike->ispi), clib_net_to_host_u64 (ike->rspi), payload, ike->version, ike->exchange, ike->flags, clib_net_to_host_u32 (ike->msgid), len); plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload); if (!plaintext) goto cleanup_and_exit; /* process encrypted payload */ p = 0; while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE) { ikep = (ike_payload_header_t *) & plaintext[p]; plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (ike_payload_header_t)) goto cleanup_and_exit; if (payload == IKEV2_PAYLOAD_NOTIFY) /* 41 */ { ikev2_notify_t *n = ikev2_parse_notify_payload (ikep); if (n->msg_type == IKEV2_NOTIFY_MSG_AUTHENTICATION_FAILED) ikev2_set_state (sa, IKEV2_STATE_AUTH_FAILED); vec_free (n); } else if (payload == IKEV2_PAYLOAD_DELETE) /* 42 */ { sa->del = ikev2_parse_delete_payload (ikep); } else if (payload == IKEV2_PAYLOAD_VENDOR) /* 43 */ { ikev2_parse_vendor_payload (ikep); } else { clib_warning ("unknown payload %u flags %x length %u data %u", payload, ikep->flags, plen - 4, format_hex_bytes, ikep->payload, plen - 4); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { sa->unsupported_cp = payload; return; } } payload = ikep->nextpayload; p += plen; } cleanup_and_exit: vec_free (plaintext); } static void ikev2_process_create_child_sa_req (vlib_main_t * vm, ikev2_sa_t * sa, ike_header_t * ike) { int p = 0; u32 len = clib_net_to_host_u32 (ike->length); u8 payload = ike->nextpayload; u8 *plaintext = 0; u8 rekeying = 0; u8 nonce[IKEV2_NONCE_SIZE]; ike_payload_header_t *ikep; u32 plen; ikev2_notify_t *n = 0; ikev2_ts_t *tsi = 0; ikev2_ts_t *tsr = 0; ikev2_sa_proposal_t *proposal = 0; ikev2_child_sa_t *child_sa; clib_warning ("ispi %lx rspi %lx nextpayload %x version %x " "exchange %x flags %x msgid %x length %u", clib_net_to_host_u64 (ike->ispi), clib_net_to_host_u64 (ike->rspi), payload, ike->version, ike->exchange, ike->flags, clib_net_to_host_u32 (ike->msgid), len); plaintext = ikev2_decrypt_sk_payload (sa, ike, &payload); if (!plaintext) goto cleanup_and_exit; /* process encrypted payload */ p = 0; while (p < vec_len (plaintext) && payload != IKEV2_PAYLOAD_NONE) { ikep = (ike_payload_header_t *) & plaintext[p]; plen = clib_net_to_host_u16 (ikep->length); if (plen < sizeof (ike_payload_header_t)) goto cleanup_and_exit; else if (payload == IKEV2_PAYLOAD_SA) { proposal = ikev2_parse_sa_payload (ikep); } else if (payload == IKEV2_PAYLOAD_NOTIFY) { n = ikev2_parse_notify_payload (ikep); if (n->msg_type == IKEV2_NOTIFY_MSG_REKEY_SA) { rekeying = 1; } } else if (payload == IKEV2_PAYLOAD_DELETE) { sa->del = ikev2_parse_delete_payload (ikep); } else if (payload == IKEV2_PAYLOAD_VENDOR) { ikev2_parse_vendor_payload (ikep); } else if (payload == IKEV2_PAYLOAD_NONCE) { clib_memcpy (nonce, ikep->payload, plen - sizeof (*ikep)); } else if (payload == IKEV2_PAYLOAD_TSI) { tsi = ikev2_parse_ts_payload (ikep); } else if (payload == IKEV2_PAYLOAD_TSR) { tsr = ikev2_parse_ts_payload (ikep); } else { clib_warning ("unknown payload %u flags %x length %u data %u", payload, ikep->flags, plen - 4, format_hex_bytes, ikep->payload, plen - 4); if (ikep->flags & IKEV2_PAYLOAD_FLAG_CRITICAL) { sa->unsupported_cp = payload; return; } } payload = ikep->nextpayload; p += plen; } if (sa->is_initiator && proposal->protocol_id == IKEV2_PROTOCOL_ESP) { ikev2_rekey_t *rekey = &sa->rekey[0]; rekey->protocol_id = proposal->protocol_id; rekey->i_proposal = ikev2_select_proposal (proposal, IKEV2_PROTOCOL_ESP); rekey->i_proposal->spi = rekey->spi; rekey->r_proposal = proposal; rekey->tsi = tsi; rekey->tsr = tsr; /* update Nr */ vec_free (sa->r_nonce); vec_add (sa->r_nonce, nonce, IKEV2_NONCE_SIZE); child_sa = ikev2_sa_get_child (sa, rekey->ispi, IKEV2_PROTOCOL_ESP, 1); if (child_sa) { child_sa->rekey_retries = 0; } } else if (rekeying) { ikev2_rekey_t *rekey; child_sa = ikev2_sa_get_child (sa, n->spi, n->protocol_id, 1); if (!child_sa) { clib_warning ("child SA spi %lx not found", n->spi); goto cleanup_and_exit; } vec_add2 (sa->rekey, rekey, 1); rekey->protocol_id = n->protocol_id; rekey->spi = n->spi; rekey->i_proposal = proposal; rekey->r_proposal = ikev2_select_proposal (proposal, IKEV2_PROTOCOL_ESP); rekey->tsi = tsi; rekey->tsr = tsr; /* update Ni */ vec_free (sa->i_nonce); vec_add (sa->i_nonce, nonce, IKEV2_NONCE_SIZE); /* generate new Nr */ vec_free (sa->r_nonce); sa->r_nonce = vec_new (u8, IKEV2_NONCE_SIZE); RAND_bytes ((u8 *) sa->r_nonce, IKEV2_NONCE_SIZE); } cleanup_and_exit: vec_free (plaintext); vec_free (n); } static u8 * ikev2_sa_generate_authmsg (ikev2_sa_t * sa, int is_responder) { u8 *authmsg = 0; u8 *data; u8 *nonce; ikev2_id_t *id; u8 *key; u8 *packet_data; ikev2_sa_transform_t *tr_prf; tr_prf = ikev2_sa_get_td_for_type (sa->r_proposals, IKEV2_TRANSFORM_TYPE_PRF); if (is_responder) { id = &sa->r_id; key = sa->sk_pr; nonce = sa->i_nonce; packet_data = sa->last_sa_init_res_packet_data; } else { id = &sa->i_id; key = sa->sk_pi; nonce = sa->r_nonce; packet_data = sa->last_sa_init_req_packet_data; } data = vec_new (u8, 4); data[0] = id->type; vec_append (data, id->data); u8 *id_hash = ikev2_calc_prf (tr_prf, key, data); vec_append (authmsg, packet_data); vec_append (authmsg, nonce); vec_append (authmsg, id_hash); vec_free (id_hash); vec_free (data); return authmsg; } static int ikev2_ts_cmp (ikev2_ts_t * ts1, ikev2_ts_t * ts2) { if (ts1->ts_type == ts2->ts_type && ts1->protocol_id == ts2->protocol_id && ts1->start_port == ts2->start_port && ts1->end_port == ts2->end_port && ts1->start_addr.as_u32 == ts2->start_addr.as_u32 && ts1->end_addr.as_u32 == ts2->end_addr.as_u32) return 1; return 0; } static void ikev2_sa_match_ts (ikev2_sa_t * sa) { ikev2_main_t *km = &ikev2_main; ikev2_profile_t *p; ikev2_ts_t *ts, *p_tsi, *p_tsr, *tsi = 0, *tsr = 0; ikev2_id_t *id; /* *INDENT-OFF* */ pool_foreach (p, km->profiles, ({ if (sa->is_initiator) { p_tsi = &p->loc_ts; p_tsr = &p->rem_ts; id = &sa->r_id; } else { p_tsi = &p->rem_ts; p_tsr = &p->loc_ts; id = &sa->i_id; } /* check id */ if (p->rem_id.type != id->type || vec_len(p->rem_id.data) != vec_len(id->data) || memcmp(p->rem_id.data, id->data, vec_len(p->rem_id.data))) continue; vec_foreach(ts, sa->childs[0].tsi) { if (ikev2_ts_cmp(p_tsi, ts)) { tsi = vec_dup(ts); break; } } vec_foreach(ts, sa->childs[0].tsr) { if (ikev2_ts_cmp(p_tsr, ts)) { tsr = vec_dup(ts); break; } } break; })); /* *INDENT-ON* */ if (tsi && tsr) { vec_free (sa->childs[0].tsi); vec_free (sa->childs[0].tsr); sa->childs[0].tsi = tsi; sa->childs[0].tsr = tsr; } else { vec_free (tsi); vec_free (tsr); ikev2_set_state (sa, IKEV2_STAT
#!/usr/bin/env python

import unittest

from scapy.layers.l2 import Ether, Raw
from scapy.layers.inet import IP, IPOption
from scapy.contrib.igmpv3 import IGMPv3, IGMPv3gr, IGMPv3mq, IGMPv3mr

from framework import VppTestCase, VppTestRunner, running_extended_tests
from vpp_igmp import find_igmp_state, IGMP_FILTER, IgmpRecord, IGMP_MODE, \
    IgmpSG, VppHostState, wait_for_igmp_event
from vpp_ip_route import find_mroute, VppIpTable


class IgmpMode:
    HOST = 1
    ROUTER = 0


class TestIgmp(VppTestCase):
    """ IGMP Test Case """

    @classmethod
    def setUpClass(cls):
        super(TestIgmp, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(TestIgmp, cls).tearDownClass()

    def setUp(self):
        super(TestIgmp, self).setUp()

        self.create_pg_interfaces(range(4))
        self.sg_list = []
        self.config_list = []

        self.ip_addr = []
        self.ip_table = VppIpTable(self, 1)
        self.ip_table.add_vpp_config()

        for pg in self.pg_interfaces[2:]:
            pg.set_table_ip4(1)
        for pg in self.pg_interfaces:
            pg.admin_up()
            pg.config_ip4()
            pg.resolve_arp()

    def tearDown(self):
        for pg in self.pg_interfaces:
            self.vapi.igmp_clear_interface(pg.sw_if_index)
            pg.unconfig_ip4()
            pg.set_table_ip4(0)
            pg.admin_down()
        super(TestIgmp, self).tearDown()

    def send(self, ti, pkts):
        ti.add_stream(pkts)
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

    def test_igmp_flush(self):
        """ IGMP Link Up/down and Flush """

        #
        # FIX THIS. Link down.
        #

    def test_igmp_enable(self):
        """ IGMP enable/disable on an interface

        check for the addition/removal of the IGMP mroutes """

        self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST)
        self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, IGMP_MODE.HOST)

        self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32))
        self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32))

        self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, IGMP_MODE.HOST)
        self.vapi.igmp_enable_disable(self.pg3.sw_if_index, 1, IGMP_MODE.HOST)

        self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32,
                                    table_id=1))
        self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32,
                                    table_id=1))
        self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST)
        self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, IGMP_MODE.HOST)
        self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, IGMP_MODE.HOST)
        self.vapi.igmp_enable_disable(self.pg3.sw_if_index, 0, IGMP_MODE.HOST)

        self.assertFalse(find_mroute(self, "224.0.0.1", "0.0.0.0", 32))
        self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32))
        self.assertFalse(find_mroute(self, "224.0.0.1", "0.0.0.0", 32,
                                     table_id=1))
        self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32,
                                     table_id=1))

    def verify_general_query(self, p):
        ip = p[IP]
        self.assertEqual(len(ip.options), 1)
        self.assertEqual(ip.options[0].option, 20)
        self.assertEqual(ip.dst, "224.0.0.1")
        self.assertEqual(ip.proto, 2)
        igmp = p[IGMPv3]
        self.assertEqual(igmp.type, 0x11)
        self.assertEqual(igmp.gaddr, "0.0.0.0")

    def verify_group_query(self, p, grp, srcs):
        ip = p[IP]
        self.assertEqual(ip.dst, grp)
        self.assertEqual(ip.proto, 2)
        self.assertEqual(len(ip.options), 1)
        self.assertEqual(ip.options[0].option, 20)
        self.assertEqual(ip.proto, 2)
        igmp = p[IGMPv3]
        self.assertEqual(igmp.type, 0x11)
        self.assertEqual(igmp.gaddr, grp)

    def verify_report(self, rx, records):
        ip = rx[IP]
        self.assertEqual(rx[IP].dst, "224.0.0.22")
        self.assertEqual(len(ip.options), 1)
        self.assertEqual(ip.options[0].option, 20)
        self.assertEqual(ip.proto, 2)
        self.assertEqual(IGMPv3.igmpv3types[rx[IGMPv3].type],
                         "Version 3 Membership Report")
        self.assertEqual(rx[IGMPv3mr].numgrp, len(records))

        received = rx[IGMPv3mr].records

        for ii in range(len(records)):
            gr = received[ii]
            r = records[ii]
            self.assertEqual(IGMPv3gr.igmpv3grtypes[gr.rtype], r.type)
            self.assertEqual(gr.numsrc, len(r.sg.saddrs))
            self.assertEqual(gr.maddr, r.sg.gaddr)
            self.assertEqual(len(gr.srcaddrs), len(r.sg.saddrs))

            self.assertEqual(sorted(gr.srcaddrs),
                             sorted(r.sg.saddrs))

    def add_group(self, itf, sg, n_pkts=2):
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        hs = VppHostState(self,
                          IGMP_FILTER.INCLUDE,
                          itf.sw_if_index,
                          sg)
        hs.add_vpp_config()

        capture = itf.get_capture(n_pkts, timeout=10)

        # reports are transmitted twice due to default rebostness value=2
        self.verify_report(capture[0],
                           [IgmpRecord(sg, "Allow New Sources")]),
        self.verify_report(capture[1],
                           [IgmpRecord(sg, "Allow New Sources")]),

        return hs

    def remove_group(self, hs):
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()
        hs.remove_vpp_config()

        capture = self.pg0.get_capture(1, timeout=10)

        self.verify_report(capture[0],
                           [IgmpRecord(hs.sg, "Block Old Sources")])

    def test_igmp_host(self):
        """ IGMP Host functions """

        #
        # Enable interface for host functions
        #
        self.vapi.igmp_enable_disable(self.pg0.sw_if_index,
                                      1,
                                      IGMP_MODE.HOST)

        #
        # Add one S,G of state and expect a state-change event report
        # indicating the addition of the S,G
        #
        h1 = self.add_group(self.pg0, IgmpSG("239.1.1.1", ["1.1.1.1"]))

        # search for the corresponding state created in VPP
        dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
        self.assertEqual(len(dump), 1)
        self.assertTrue(find_igmp_state(dump, self.pg0,
                                        "239.1.1.1", "1.1.1.1"))

        #
        # Send a general query (to the all router's address)
        # expect VPP to respond with a membership report.
        # Pad the query with 0 - some devices in the big wild
        # internet are prone to this.
        #
        p_g = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
               IP(src=self.pg0.remote_ip4, dst='224.0.0.1', tos=0xc0) /
               IGMPv3(type="Membership Query", mrcode=100) /
               IGMPv3mq(gaddr="0.0.0.0") /
               Raw('\x00' * 10))

        self.send(self.pg0, p_g)

        capture = self.pg0.get_capture(1, timeout=10)
        self.verify_report(capture[0],
                           [IgmpRecord(h1.sg, "Mode Is Include")])

        #
        # Group specific query
        #
        p_gs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
                   options=[IPOption(copy_flag=1, optclass="control",
                                     option="router_alert")]) /
                IGMPv3(type="Membership Query", mrcode=100) /
                IGMPv3mq(gaddr="239.1.1.1"))

        self.send(self.pg0, p_gs)

        capture = self.pg0.get_capture(1, timeout=10)
        self.verify_report(capture[0],
                           [IgmpRecord(h1.sg, "Mode Is Include")])

        #
        # A group and source specific query, with the source matching
        # the source VPP has
        #
        p_gs1 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
                    options=[IPOption(copy_flag=1, optclass="control",
                                      option="router_alert")]) /
                 IGMPv3(type="Membership Query", mrcode=100) /
                 IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1"]))

        self.send(self.pg0, p_gs1)

        capture = self.pg0.get_capture(1, timeout=10)
        self.verify_report(capture[0],
                           [IgmpRecord(h1.sg, "Mode Is Include")])

        #
        # A group and source specific query that reports more sources
        # than the packet actually has.
        #
        p_gs2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
                 IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
                    options=[IPOption(copy_flag=1, optclass="control",
                                      option="router_alert")]) /
                 IGMPv3(type="Membership Query", mrcode=100) /
                 IGMPv3mq(gaddr="239.1.1.1", numsrc=