async-snmp 0.18.0

Modern async-first SNMP client library for Rust
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use super::{CryptoError, CryptoProvider, CryptoResult};
use crate::v3::{AuthProtocol, PrivProtocol};

/// Default crypto provider backed by the `RustCrypto` crate ecosystem.
///
/// This is a stateless unit struct that dispatches to the appropriate
/// `RustCrypto` implementations based on the protocol enum values.
pub(crate) struct RustCryptoProvider;

// --- Dispatch macro for auth protocol -> concrete hash type ---

macro_rules! dispatch_auth {
    ($protocol:expr, $fn:ident, $($arg:expr),*) => {
        match $protocol {
            AuthProtocol::Md5 => $fn::<md5::Md5>($($arg),*),
            AuthProtocol::Sha1 => $fn::<sha1::Sha1>($($arg),*),
            AuthProtocol::Sha224 => $fn::<sha2::Sha224>($($arg),*),
            AuthProtocol::Sha256 => $fn::<sha2::Sha256>($($arg),*),
            AuthProtocol::Sha384 => $fn::<sha2::Sha384>($($arg),*),
            AuthProtocol::Sha512 => $fn::<sha2::Sha512>($($arg),*),
        }
    };
}

impl CryptoProvider for RustCryptoProvider {
    fn validate_auth_protocol(&self, _protocol: AuthProtocol) -> CryptoResult<()> {
        Ok(())
    }

    fn validate_priv_protocol(&self, _protocol: PrivProtocol) -> CryptoResult<()> {
        Ok(())
    }

    fn hash(&self, protocol: AuthProtocol, data: &[u8]) -> CryptoResult<Vec<u8>> {
        Ok(dispatch_auth!(protocol, hash_impl, data))
    }

    fn password_to_key(&self, protocol: AuthProtocol, password: &[u8]) -> CryptoResult<Vec<u8>> {
        const EXPANSION_SIZE: usize = 1_048_576; // 1MB
        if password.len() < crate::v3::auth::MIN_PASSWORD_LENGTH {
            return Err(CryptoError::PasswordTooShort);
        }
        Ok(dispatch_auth!(
            protocol,
            password_to_key_impl,
            password,
            EXPANSION_SIZE
        ))
    }

    fn localize_key(
        &self,
        protocol: AuthProtocol,
        master_key: &[u8],
        engine_id: &[u8],
    ) -> CryptoResult<Vec<u8>> {
        Ok(dispatch_auth!(
            protocol,
            localize_key_impl,
            master_key,
            engine_id
        ))
    }

    fn compute_hmac(
        &self,
        protocol: AuthProtocol,
        key: &[u8],
        slices: &[&[u8]],
        truncate_len: usize,
    ) -> CryptoResult<Vec<u8>> {
        let digest_length = protocol.digest_len();
        if truncate_len > digest_length {
            return Err(CryptoError::InvalidHmacTruncationLength {
                requested: truncate_len,
                digest_length,
            });
        }

        Ok(dispatch_auth!(
            protocol,
            compute_hmac_impl,
            key,
            slices,
            truncate_len
        ))
    }

    fn encrypt(
        &self,
        protocol: PrivProtocol,
        key: &[u8],
        iv: &[u8],
        data: &mut Vec<u8>,
    ) -> CryptoResult<()> {
        match protocol {
            PrivProtocol::Des | PrivProtocol::Des3 => {
                // RFC 3414 ยง8.1.1.2: pad only up to the next 8-byte block boundary;
                // the pad value is irrelevant and no full block is added when already
                // aligned (i.e. not PKCS7).
                let block = 8;
                let padded_len = data.len().next_multiple_of(block);
                let pad_byte = (padded_len - data.len()) as u8;
                data.resize(padded_len, pad_byte);
                match protocol {
                    PrivProtocol::Des => encrypt_des_cbc(key, iv, data),
                    _ => encrypt_des3_cbc(key, iv, data),
                }
            }
            PrivProtocol::Aes128
            | PrivProtocol::Aes192Blumenthal
            | PrivProtocol::Aes192Reeder
            | PrivProtocol::Aes256Blumenthal
            | PrivProtocol::Aes256Reeder => encrypt_aes_cfb(key, iv, data),
        }
    }

    fn decrypt(
        &self,
        protocol: PrivProtocol,
        key: &[u8],
        iv: &[u8],
        data: &mut [u8],
    ) -> CryptoResult<()> {
        match protocol {
            PrivProtocol::Des => decrypt_des_cbc(key, iv, data),
            PrivProtocol::Des3 => decrypt_des3_cbc(key, iv, data),
            PrivProtocol::Aes128
            | PrivProtocol::Aes192Blumenthal
            | PrivProtocol::Aes192Reeder
            | PrivProtocol::Aes256Blumenthal
            | PrivProtocol::Aes256Reeder => decrypt_aes_cfb(key, iv, data),
        }
    }
}

// --- Auth primitive implementations ---

use digest::block_api::BlockSizeUser;
use digest::{Digest, KeyInit, Mac, OutputSizeUser};

fn hash_impl<D>(data: &[u8]) -> Vec<u8>
where
    D: Digest + Default,
{
    let mut hasher = D::new();
    hasher.update(data);
    hasher.finalize().to_vec()
}

fn password_to_key_impl<D>(password: &[u8], expansion_size: usize) -> Vec<u8>
where
    D: Digest + Default,
{
    if password.is_empty() {
        return vec![0u8; <D as OutputSizeUser>::output_size()];
    }

    let mut hasher = D::new();

    let mut buf = [0u8; 64];
    let password_len = password.len();
    let mut password_index = 0;
    let mut count = 0;

    while count < expansion_size {
        for byte in &mut buf {
            *byte = password[password_index];
            password_index = (password_index + 1) % password_len;
        }
        hasher.update(buf);
        count += 64;
    }

    hasher.finalize().to_vec()
}

fn localize_key_impl<D>(master_key: &[u8], engine_id: &[u8]) -> Vec<u8>
where
    D: Digest + Default,
{
    let mut hasher = D::new();
    hasher.update(master_key);
    hasher.update(engine_id);
    hasher.update(master_key);
    hasher.finalize().to_vec()
}

fn compute_hmac_impl<D>(key: &[u8], slices: &[&[u8]], truncate_len: usize) -> Vec<u8>
where
    D: Digest + BlockSizeUser + Clone,
{
    use hmac::SimpleHmac;

    let mut mac =
        <SimpleHmac<D> as KeyInit>::new_from_slice(key).expect("HMAC can take key of any size");
    for slice in slices {
        Mac::update(&mut mac, slice);
    }
    let result = mac.finalize().into_bytes();
    result[..truncate_len].to_vec()
}

// --- Privacy primitive implementations ---

fn encrypt_des_cbc(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use cbc::cipher::{BlockModeEncrypt, KeyIvInit};
    type DesCbc = cbc::Encryptor<des::Des>;

    let cipher = DesCbc::new_from_slices(key, iv).map_err(|_| {
        tracing::debug!(target: "async_snmp::crypto", "DES encryption failed: invalid key length");
        CryptoError::InvalidKeyLength
    })?;
    let len = data.len();
    cipher
        .encrypt_padded::<cbc::cipher::block_padding::NoPadding>(data, len)
        .map_err(|_| {
            tracing::debug!(target: "async_snmp::crypto", "DES encryption failed: cipher error");
            CryptoError::CipherError
        })?;
    Ok(())
}

fn decrypt_des_cbc(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
    type DesCbc = cbc::Decryptor<des::Des>;

    let cipher = DesCbc::new_from_slices(key, iv).map_err(|_| {
        tracing::debug!(target: "async_snmp::crypto", "DES decryption failed: invalid key length");
        CryptoError::InvalidKeyLength
    })?;
    cipher
        .decrypt_padded::<cbc::cipher::block_padding::NoPadding>(data)
        .map_err(|_| {
            tracing::debug!(target: "async_snmp::crypto", "DES decryption failed: cipher error");
            CryptoError::CipherError
        })?;
    Ok(())
}

fn encrypt_des3_cbc(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use cbc::cipher::{BlockModeEncrypt, KeyIvInit};
    type Des3Cbc = cbc::Encryptor<des::TdesEde3>;

    let cipher = Des3Cbc::new_from_slices(key, iv).map_err(|_| {
        tracing::debug!(target: "async_snmp::crypto", "3DES encryption failed: invalid key length");
        CryptoError::InvalidKeyLength
    })?;
    let len = data.len();
    cipher
        .encrypt_padded::<cbc::cipher::block_padding::NoPadding>(data, len)
        .map_err(|_| {
            tracing::debug!(target: "async_snmp::crypto", "3DES encryption failed: cipher error");
            CryptoError::CipherError
        })?;
    Ok(())
}

fn decrypt_des3_cbc(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
    type Des3Cbc = cbc::Decryptor<des::TdesEde3>;

    let cipher = Des3Cbc::new_from_slices(key, iv).map_err(|_| {
        tracing::debug!(target: "async_snmp::crypto", "3DES decryption failed: invalid key length");
        CryptoError::InvalidKeyLength
    })?;
    cipher
        .decrypt_padded::<cbc::cipher::block_padding::NoPadding>(data)
        .map_err(|_| {
            tracing::debug!(target: "async_snmp::crypto", "3DES decryption failed: cipher error");
            CryptoError::CipherError
        })?;
    Ok(())
}

fn encrypt_aes_cfb(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use aes::{Aes128, Aes192, Aes256};
    use cfb_mode::cipher::KeyIvInit;

    match key.len() {
        16 => {
            type Aes128Cfb = cfb_mode::Encryptor<Aes128>;
            let cipher = Aes128Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-128 encryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.encrypt(data);
        }
        24 => {
            type Aes192Cfb = cfb_mode::Encryptor<Aes192>;
            let cipher = Aes192Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-192 encryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.encrypt(data);
        }
        32 => {
            type Aes256Cfb = cfb_mode::Encryptor<Aes256>;
            let cipher = Aes256Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-256 encryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.encrypt(data);
        }
        key_len => {
            tracing::debug!(target: "async_snmp::crypto", { key_len }, "AES encryption failed: unsupported key length");
            return Err(CryptoError::InvalidKeyLength);
        }
    }
    Ok(())
}

fn decrypt_aes_cfb(key: &[u8], iv: &[u8], data: &mut [u8]) -> CryptoResult<()> {
    use aes::{Aes128, Aes192, Aes256};
    use cfb_mode::cipher::KeyIvInit;

    match key.len() {
        16 => {
            type Aes128Cfb = cfb_mode::Decryptor<Aes128>;
            let cipher = Aes128Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-128 decryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.decrypt(data);
        }
        24 => {
            type Aes192Cfb = cfb_mode::Decryptor<Aes192>;
            let cipher = Aes192Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-192 decryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.decrypt(data);
        }
        32 => {
            type Aes256Cfb = cfb_mode::Decryptor<Aes256>;
            let cipher = Aes256Cfb::new_from_slices(key, iv).map_err(|_| {
                tracing::debug!(target: "async_snmp::crypto", "AES-256 decryption failed: invalid key length");
                CryptoError::InvalidKeyLength
            })?;
            cipher.decrypt(data);
        }
        key_len => {
            tracing::debug!(target: "async_snmp::crypto", { key_len }, "AES decryption failed: unsupported key length");
            return Err(CryptoError::InvalidKeyLength);
        }
    }
    Ok(())
}

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

    #[test]
    fn hmac_truncation_boundaries_for_all_digests() {
        let provider = RustCryptoProvider;
        let protocols = [
            AuthProtocol::Md5,
            AuthProtocol::Sha1,
            AuthProtocol::Sha224,
            AuthProtocol::Sha256,
            AuthProtocol::Sha384,
            AuthProtocol::Sha512,
        ];

        for protocol in protocols {
            let digest_length = protocol.digest_len();
            let exact = provider
                .compute_hmac(protocol, b"key", &[b"message"], digest_length)
                .expect("exact digest-length truncation must succeed");
            assert_eq!(exact.len(), digest_length);

            assert_eq!(
                provider.compute_hmac(protocol, b"key", &[b"message"], digest_length + 1),
                Err(CryptoError::InvalidHmacTruncationLength {
                    requested: digest_length + 1,
                    digest_length,
                })
            );
        }
    }

    /// RFC 3414 ยง8.1.1.2: "if [the length] is not [a multiple of 8], the data
    /// is padded at the end as necessary." The encrypt operation must handle
    /// unaligned plaintext by padding to the next block boundary.
    #[test]
    fn des_encrypt_pads_unaligned_plaintext() {
        let provider = RustCryptoProvider;
        let key = b"\x00\x11\x22\x33\x44\x55\x66\x77";
        let iv = [0u8; 8];
        let mut data = b"Hello".to_vec(); // 5 bytes, not a multiple of 8

        let result = provider.encrypt(PrivProtocol::Des, key, &iv, &mut data);
        assert!(
            result.is_ok(),
            "DES encrypt must pad unaligned plaintext, got: {result:?}"
        );
        assert_eq!(data.len(), 8, "output must be padded to 8-byte boundary");
    }

    /// Same as DES: 3DES-CBC must pad unaligned plaintext.
    #[test]
    fn des3_encrypt_pads_unaligned_plaintext() {
        let provider = RustCryptoProvider;
        let key = [0x01u8; 24];
        let iv = [0u8; 8];
        let mut data = b"Hello".to_vec(); // 5 bytes

        let result = provider.encrypt(PrivProtocol::Des3, &key, &iv, &mut data);
        assert!(
            result.is_ok(),
            "3DES encrypt must pad unaligned plaintext, got: {result:?}"
        );
        assert_eq!(data.len(), 8, "output must be padded to 8-byte boundary");
    }

    /// DES roundtrip: unaligned plaintext should encrypt and decrypt correctly.
    #[test]
    fn des_roundtrip_unaligned() {
        let provider = RustCryptoProvider;
        let key = b"\x00\x11\x22\x33\x44\x55\x66\x77";
        let iv = [0u8; 8];
        let plaintext = b"Hello";
        let mut data = plaintext.to_vec();

        provider
            .encrypt(PrivProtocol::Des, key, &iv, &mut data)
            .unwrap();
        assert_eq!(data.len(), 8);

        provider
            .decrypt(PrivProtocol::Des, key, &iv, &mut data)
            .unwrap();
        assert_eq!(&data[..plaintext.len()], plaintext);
    }

    /// Already-aligned DES plaintext should still work (no regression).
    #[test]
    fn des_encrypt_aligned_unchanged() {
        let provider = RustCryptoProvider;
        let key = b"\x00\x11\x22\x33\x44\x55\x66\x77";
        let iv = [0u8; 8];
        let mut data = vec![0x41u8; 8]; // already 8 bytes

        let result = provider.encrypt(PrivProtocol::Des, key, &iv, &mut data);
        assert!(result.is_ok());
        assert_eq!(data.len(), 8);
    }
}