1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! Exports the types of user keys available for this implementation.

use kerberos_constants::etypes::{
    AES128_CTS_HMAC_SHA1_96, AES256_CTS_HMAC_SHA1_96, RC4_HMAC,
};

use crate::{AES128_KEY_SIZE, AES256_KEY_SIZE, RC4_KEY_SIZE};

use crate::{Error, Result};
use std::result;

/// Encapsules the possible keys used by this Kerberos implementation.
/// Each key can be used by a different cryptographic algorithm.
#[derive(Debug, PartialEq, Clone)]
pub enum Key {
    /// The secret of the user. This is the most versatile key,
    /// since can it can be use to derive the rest of the keys,
    /// and therefore, being used by any cryptographic algorithm.
    Secret(String),

    /// RC4 key used by RC4-HMAC algorithm.
    /// In Windows, this is the NTLM hash of the user password.
    RC4Key([u8; RC4_KEY_SIZE]),

    /// AES key used by AES128-CTS-HMAC-SHA1-96 algorithm.
    AES128Key([u8; AES128_KEY_SIZE]),

    /// AES key used by AES256-CTS-HMAC-SHA1-96 algorithm.
    AES256Key([u8; AES256_KEY_SIZE]),
}

impl Key {
    /// Return the etypes associated with the type of key.
    ///
    /// # Examples
    /// ```
    /// use kerberos_crypto::*;
    /// use kerberos_constants::etypes::*;
    ///
    /// assert_eq!(
    ///     vec![AES256_CTS_HMAC_SHA1_96, AES128_CTS_HMAC_SHA1_96, RC4_HMAC],
    ///     Key::Secret("".to_string()).etypes()
    /// );
    /// assert_eq!(vec![RC4_HMAC], Key::RC4Key([0; RC4_KEY_SIZE]).etypes());
    /// assert_eq!(
    ///     vec![AES128_CTS_HMAC_SHA1_96],
    ///     Key::AES128Key([0; AES128_KEY_SIZE]).etypes()
    /// );
    /// assert_eq!(
    ///     vec![AES256_CTS_HMAC_SHA1_96],
    ///     Key::AES256Key([0; AES256_KEY_SIZE]).etypes()
    /// );
    /// ```
    pub fn etypes(&self) -> Vec<i32> {
        match self {
            Key::Secret(_) => {
                vec![AES256_CTS_HMAC_SHA1_96, AES128_CTS_HMAC_SHA1_96, RC4_HMAC]
            }
            Key::RC4Key(_) => vec![RC4_HMAC],
            Key::AES128Key(_) => vec![AES128_CTS_HMAC_SHA1_96],
            Key::AES256Key(_) => vec![AES256_CTS_HMAC_SHA1_96],
        }
    }

    /// Retrieve the key as an array of bytes.
    ///
    /// # Examples
    /// ```
    /// use kerberos_crypto::*;
    ///
    /// assert_eq!(&[0x73, 0x65, 0x63, 0x72, 0x65, 0x74], Key::Secret("secret".to_string()).as_bytes());
    /// assert_eq!(&[0; RC4_KEY_SIZE], Key::RC4Key([0; RC4_KEY_SIZE]).as_bytes());
    /// assert_eq!(&[0; AES128_KEY_SIZE], Key::AES128Key([0; AES128_KEY_SIZE]).as_bytes());
    /// assert_eq!(&[0; AES256_KEY_SIZE], Key::AES256Key([0; AES256_KEY_SIZE]).as_bytes());
    /// ```
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            Key::Secret(ref secret) => secret.as_bytes(),
            Key::RC4Key(ref rc4key) => rc4key,
            Key::AES128Key(ref aeskey) => aeskey,
            Key::AES256Key(ref aeskey) => aeskey,
        }
    }

    /// Get a RC4 key from a hexdump.
    /// # Example
    ///
    /// ```
    /// use kerberos_crypto::Key;
    /// assert_eq!(
    ///     Key::RC4Key([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]),
    ///     Key::from_rc4_key_string("0123456789ABCDEF0123456789abcdef").unwrap()
    /// );
    /// ```
    /// # Errors
    /// An error if raised if the argument string has any non hexadecimal character or size is different from 32.
    ///
    pub fn from_rc4_key_string(hex_str: &str) -> Result<Self> {
        let ntlm =
            Self::check_size_and_convert_in_byte_array(hex_str, RC4_KEY_SIZE)?;

        let mut key = [0; RC4_KEY_SIZE];
        key.copy_from_slice(&ntlm[0..RC4_KEY_SIZE]);

        return Ok(Key::RC4Key(key));
    }

    /// Get a AES-128 key from a hexdump.
    /// # Example
    ///
    /// ```
    /// use kerberos_crypto::Key;
    /// assert_eq!(
    ///     Key::AES128Key([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]),
    ///     Key::from_aes_128_key_string("0123456789ABCDEF0123456789abcdef").unwrap()
    /// );
    /// ```
    /// # Errors
    /// An error if raised if the argument string has any non hexadecimal character or size is different from 32.
    ///
    pub fn from_aes_128_key_string(hex_str: &str) -> Result<Self> {
        let ntlm = Self::check_size_and_convert_in_byte_array(
            hex_str,
            AES128_KEY_SIZE,
        )?;

        let mut key = [0; AES128_KEY_SIZE];
        key.copy_from_slice(&ntlm[0..AES128_KEY_SIZE]);

        return Ok(Key::AES128Key(key));
    }

    /// Get a AES-256 key from a hexdump.
    /// # Example
    ///
    /// ```
    /// use kerberos_crypto::Key;
    /// assert_eq!(
    ///     Key::AES256Key([
    ///         0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
    ///         0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
    ///     ]),
    ///     Key::from_aes_256_key_string("0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef").unwrap()
    /// );
    /// ```
    /// # Errors
    /// An error if raised if the argument string has any non hexadecimal character or size is different from 64.
    ///
    pub fn from_aes_256_key_string(hex_str: &str) -> Result<Self> {
        let ntlm = Self::check_size_and_convert_in_byte_array(
            hex_str,
            AES256_KEY_SIZE,
        )?;

        let mut key = [0; AES256_KEY_SIZE];
        key.copy_from_slice(&ntlm[0..AES256_KEY_SIZE]);

        return Ok(Key::AES256Key(key));
    }

    fn check_size_and_convert_in_byte_array(
        hex_str: &str,
        size: usize,
    ) -> Result<Vec<u8>> {
        if hex_str.len() != size * 2 {
            return Err(Error::InvalidKeyLength(size * 2))?;
        }

        return Ok(Self::convert_hex_string_into_byte_array(hex_str)
            .map_err(|_| Error::InvalidKeyCharset)?);
    }

    fn convert_hex_string_into_byte_array(
        hex_str: &str,
    ) -> result::Result<Vec<u8>, std::num::ParseIntError> {
        let key_size = hex_str.len() / 2;
        let mut bytes = Vec::with_capacity(key_size);
        for i in 0..key_size {
            let str_index = i * 2;
            bytes.push(u8::from_str_radix(
                &hex_str[str_index..str_index + 2],
                16,
            )?);
        }

        return Ok(bytes);
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn hex_string_to_rc4_key() {
        assert_eq!(
            Key::RC4Key([0; RC4_KEY_SIZE]),
            Key::from_rc4_key_string("00000000000000000000000000000000")
                .unwrap()
        );
        assert_eq!(
            Key::RC4Key([
                0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23,
                0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
            ]),
            Key::from_rc4_key_string("0123456789ABCDEF0123456789abcdef")
                .unwrap()
        );
    }

    #[should_panic(expected = "InvalidKeyLength(32)")]
    #[test]
    fn invalid_length_hex_string_to_rc4_key() {
        Key::from_rc4_key_string("0").unwrap();
    }

    #[should_panic(expected = "InvalidKeyCharset")]
    #[test]
    fn invalid_chars_hex_string_to_rc4_key() {
        Key::from_rc4_key_string("ERROR_0123456789ABCDEF0123456789").unwrap();
    }

    #[test]
    fn hex_string_to_aes_128_key() {
        assert_eq!(
            Key::AES128Key([0; AES128_KEY_SIZE]),
            Key::from_aes_128_key_string("00000000000000000000000000000000")
                .unwrap()
        );
        assert_eq!(
            Key::AES128Key([
                0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23,
                0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
            ]),
            Key::from_aes_128_key_string("0123456789ABCDEF0123456789abcdef")
                .unwrap()
        );
    }

    #[should_panic(expected = "InvalidKeyLength(32)")]
    #[test]
    fn invalid_length_hex_string_to_aes_128_key() {
        Key::from_aes_128_key_string("0").unwrap();
    }

    #[should_panic(expected = "InvalidKeyCharset")]
    #[test]
    fn invalid_chars_hex_string_to_aes_128_key() {
        Key::from_aes_128_key_string("ERROR_0123456789ABCDEF0123456789")
            .unwrap();
    }

    #[test]
    fn hex_string_to_aes_256_key() {
        assert_eq!(
            Key::AES256Key([0; AES256_KEY_SIZE]),
            Key::from_aes_256_key_string(
                "0000000000000000000000000000000000000000000000000000000000000000"
            )
            .unwrap()
        );
        assert_eq!(
            Key::AES256Key([
                0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab,
                0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67,
                0x89, 0xab, 0xcd, 0xef
            ]),
            Key::from_aes_256_key_string(
                "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef"
            )
            .unwrap()
        );
    }

    #[should_panic(expected = "InvalidKeyLength(64)")]
    #[test]
    fn invalid_length_hex_string_to_aes_256_key() {
        Key::from_aes_256_key_string("0").unwrap();
    }

    #[should_panic(expected = "InvalidKeyCharset")]
    #[test]
    fn invalid_chars_hex_string_to_aes_256_key() {
        Key::from_aes_256_key_string(
            "ERROR_0123456789ABCDEF0123456789ERROR_0123456789ABCDEF0123456789",
        )
        .unwrap();
    }
}