Skip to main content

wlan_rsn/key/
gtk.rs

1// Copyright 2018 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::key::Tk;
6use crate::{Error, rsn_ensure};
7use mundane::bytes;
8use std::hash::{Hash, Hasher};
9use wlan_common::ie::rsn::cipher::Cipher;
10
11/// This GTK provider does not support key rotations yet.
12#[derive(Debug)]
13pub struct GtkProvider(Gtk);
14
15impl GtkProvider {
16    #[allow(clippy::result_large_err, reason = "mass allow for https://fxbug.dev/381896734")]
17    pub fn new(cipher: Cipher, key_id: u8, key_rsc: u64) -> Result<GtkProvider, Error> {
18        Ok(GtkProvider(Gtk::generate_random(cipher, key_id, key_rsc)?))
19    }
20
21    pub fn get_gtk(&self) -> &Gtk {
22        &self.0
23    }
24}
25
26#[derive(Debug, Clone, Eq)]
27pub struct Gtk {
28    pub bytes: Box<[u8]>,
29    cipher: Cipher,
30    tk_len: usize,
31    key_id: u8,
32    key_rsc: u64,
33}
34
35/// PartialEq implementation explicitly excludes the RSC.
36/// Both PartialEq and Hash ignore the RSC to prevent key re-installation (KRACK) on retransmissions.
37impl PartialEq for Gtk {
38    fn eq(&self, other: &Self) -> bool {
39        self.bytes == other.bytes && self.tk_len == other.tk_len && self.key_id == other.key_id
40    }
41}
42
43/// Custom Hash implementation which doesn't take the RSC or cipher suite into consideration.
44/// Make sure to check that this property is upheld: `v1 == v2 => hash(v1) == hash(v2)`
45impl Hash for Gtk {
46    fn hash<H: Hasher>(&self, state: &mut H) {
47        self.key_id.hash(state);
48        self.tk().hash(state);
49    }
50}
51
52impl Gtk {
53    #[allow(clippy::result_large_err, reason = "mass allow for https://fxbug.dev/381896734")]
54    pub fn generate_random(cipher: Cipher, key_id: u8, key_rsc: u64) -> Result<Gtk, Error> {
55        // IEEE 802.11-2016 12.7.4 EAPOL-Key frame notation
56        rsn_ensure!(
57            0 < key_id && key_id < 4,
58            "GTK key ID must not be zero and must fit in a two bit field"
59        );
60
61        let tk_len: usize =
62            cipher.tk_bytes().ok_or(Error::GtkHierarchyUnsupportedCipherError)?.into();
63        let mut gtk_bytes: Box<[u8]> = vec![0; tk_len].into();
64        bytes::rand(&mut gtk_bytes[..]);
65
66        Ok(Gtk { bytes: gtk_bytes, cipher, tk_len, key_id, key_rsc })
67    }
68
69    #[allow(clippy::result_large_err, reason = "mass allow for https://fxbug.dev/381896734")]
70    pub fn from_bytes(
71        gtk_bytes: Box<[u8]>,
72        cipher: Cipher,
73        key_id: u8,
74        key_rsc: u64,
75    ) -> Result<Gtk, Error> {
76        // IEEE 802.11-2016 12.7.4 EAPOL-Key frame notation
77        rsn_ensure!(
78            0 < key_id && key_id < 4,
79            "GTK key ID must not be zero and must fit in a two bit field"
80        );
81
82        let tk_len: usize =
83            cipher.tk_bytes().ok_or(Error::GtkHierarchyUnsupportedCipherError)?.into();
84        // TODO(https://fxbug.dev/523310267): Handle the case where `gtk_bytes.len() > tk_len`
85        rsn_ensure!(gtk_bytes.len() >= tk_len, "GTK must be larger than the resulting TK");
86
87        Ok(Gtk { bytes: gtk_bytes, cipher, tk_len, key_id, key_rsc })
88    }
89
90    pub fn cipher(&self) -> &Cipher {
91        &self.cipher
92    }
93
94    pub fn key_id(&self) -> u8 {
95        self.key_id
96    }
97
98    pub fn key_rsc(&self) -> u64 {
99        self.key_rsc
100    }
101}
102
103impl Tk for Gtk {
104    fn tk(&self) -> &[u8] {
105        &self.bytes[0..self.tk_len]
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use std::collections::HashSet;
113    use wlan_common::ie::rsn::cipher;
114    use wlan_common::ie::rsn::suite_selector::OUI;
115
116    #[test]
117    fn generated_gtks_are_not_zero_and_not_constant_with_high_probability() {
118        let mut gtks = HashSet::new();
119        for i in 0..10 {
120            let provider =
121                GtkProvider::new(Cipher { oui: OUI, suite_type: cipher::CCMP_128 }, 2, 5)
122                    .expect("failed creating GTK Provider");
123            let gtk_bytes: Box<[u8]> = provider.get_gtk().tk().into();
124            assert!(gtk_bytes.iter().any(|&x| x != 0));
125            if i > 0 && !gtks.contains(&gtk_bytes) {
126                return;
127            }
128            gtks.insert(gtk_bytes);
129        }
130        panic!("GtkProvider::generate_gtk() generated the same GTK 10 times in a row.");
131    }
132
133    #[test]
134    fn generated_gtk_captures_key_id() {
135        let provider = GtkProvider::new(Cipher { oui: OUI, suite_type: cipher::CCMP_128 }, 1, 3)
136            .expect("failed creating GTK Provider");
137        let gtk = provider.get_gtk();
138        assert_eq!(gtk.key_id(), 1);
139    }
140
141    #[test]
142    fn generated_gtk_captures_key_rsc() {
143        let provider = GtkProvider::new(Cipher { oui: OUI, suite_type: cipher::CCMP_128 }, 1, 3)
144            .expect("failed creating GTK Provider");
145        let gtk = provider.get_gtk();
146        assert_eq!(gtk.key_rsc(), 3);
147    }
148
149    #[test]
150    fn gtk_generation_fails_with_key_id_zero() {
151        GtkProvider::new(Cipher { oui: OUI, suite_type: cipher::CCMP_128 }, 0, 4)
152            .expect_err("GTK provider incorrectly accepts key ID 0");
153    }
154}