async-snmp 0.16.0

Modern async-first SNMP client library for Rust
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Authentication configuration types for the SNMP client.
//!
//! This module provides the [`Auth`] enum for specifying authentication
//! configuration, supporting SNMPv1/v2c community strings and `SNMPv3` USM.
//!
//! # Master Key Caching
//!
//! When polling many engines with shared credentials, use
//! [`MasterKeys`] to cache the expensive password-to-key
//! derivation:
//!
//! ```rust
//! use async_snmp::{Auth, AuthProtocol, PrivProtocol, MasterKeys};
//!
//! // Derive master keys once (expensive: ~850μs for SHA-256)
//! let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpassword").unwrap()
//!     .with_privacy(PrivProtocol::Aes128, b"privpassword").unwrap();
//!
//! // Use with USM builder - localization is cheap (~1μs per engine)
//! let auth: Auth = Auth::usm("admin")
//!     .with_master_keys(master_keys)
//!     .into();
//! ```

use crate::v3::{AuthProtocol, MasterKeys, PrivProtocol};

/// SNMP version for community-based authentication.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CommunityVersion {
    /// `SNMPv1`
    V1,
    /// `SNMPv2c`
    #[default]
    V2c,
}

/// Authentication configuration for SNMP clients.
///
/// The [`Debug`] implementation redacts community strings so that credentials
/// are not leaked through logs or diagnostics.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Auth {
    /// Community string authentication (`SNMPv1` or v2c).
    Community {
        /// SNMP version (V1 or V2c)
        version: CommunityVersion,
        /// Community string
        community: String,
    },
    /// User-based Security Model (`SNMPv3`).
    Usm(UsmAuth),
}

impl Default for Auth {
    /// Returns `Auth::v2c("public")`.
    fn default() -> Self {
        Auth::v2c("public")
    }
}

impl Auth {
    /// `SNMPv1` community authentication.
    ///
    /// Creates authentication configuration for `SNMPv1`, which only supports
    /// community string authentication without encryption.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::Auth;
    ///
    /// // Create SNMPv1 authentication with "private" community
    /// let auth = Auth::v1("private");
    /// ```
    pub fn v1(community: impl Into<String>) -> Self {
        Auth::Community {
            version: CommunityVersion::V1,
            community: community.into(),
        }
    }

    /// `SNMPv2c` community authentication.
    ///
    /// Creates authentication configuration for `SNMPv2c`, which supports
    /// community string authentication without encryption but adds GETBULK
    /// and improved error handling over `SNMPv1`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::Auth;
    ///
    /// // Create SNMPv2c authentication with "public" community
    /// let auth = Auth::v2c("public");
    ///
    /// // Auth::default() is equivalent to Auth::v2c("public")
    /// let auth = Auth::default();
    /// ```
    pub fn v2c(community: impl Into<String>) -> Self {
        Auth::Community {
            version: CommunityVersion::V2c,
            community: community.into(),
        }
    }

    /// Start building `SNMPv3` USM authentication.
    ///
    /// Returns a builder that allows configuring authentication and privacy
    /// protocols. `SNMPv3` supports three security levels:
    /// - noAuthNoPriv: username only (no security)
    /// - authNoPriv: username with authentication (integrity)
    /// - authPriv: username with authentication and encryption (confidentiality)
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::{Auth, AuthProtocol, PrivProtocol};
    ///
    /// // noAuthNoPriv: username only
    /// let auth: Auth = Auth::usm("readonly").into();
    ///
    /// // authNoPriv: with authentication
    /// let auth: Auth = Auth::usm("admin")
    ///     .auth(AuthProtocol::Sha256, "authpassword")
    ///     .into();
    ///
    /// // authPriv: with authentication and encryption
    /// let auth: Auth = Auth::usm("admin")
    ///     .auth(AuthProtocol::Sha256, "authpassword")
    ///     .privacy(PrivProtocol::Aes128, "privpassword")
    ///     .into();
    /// ```
    pub fn usm(username: impl Into<String>) -> UsmBuilder {
        UsmBuilder::new(username)
    }
}

/// `SNMPv3` USM authentication parameters.
///
/// The [`Debug`] implementation redacts the authentication and privacy
/// passwords so that credentials are not leaked through logs or diagnostics.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UsmAuth {
    /// `SNMPv3` username
    pub username: String,
    /// Authentication protocol (None for noAuthNoPriv)
    pub auth_protocol: Option<AuthProtocol>,
    /// Authentication password
    pub auth_password: Option<String>,
    /// Privacy protocol (None for noPriv)
    pub priv_protocol: Option<PrivProtocol>,
    /// Privacy password
    pub priv_password: Option<String>,
    /// `SNMPv3` context name for VACM context selection.
    /// Most deployments use empty string (default).
    pub context_name: Option<String>,
    /// Pre-computed master keys for caching.
    /// When set, passwords are ignored and keys are derived from master keys.
    pub master_keys: Option<MasterKeys>,
}

/// Builder for `SNMPv3` USM authentication.
///
/// The [`Debug`] implementation redacts the authentication and privacy
/// passwords so that credentials are not leaked through logs or diagnostics.
pub struct UsmBuilder {
    username: String,
    auth: Option<(AuthProtocol, String)>,
    privacy: Option<(PrivProtocol, String)>,
    context_name: Option<String>,
    master_keys: Option<MasterKeys>,
}

impl UsmBuilder {
    /// Create a new USM builder with the given username.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::Auth;
    ///
    /// let builder = Auth::usm("admin");
    /// ```
    pub fn new(username: impl Into<String>) -> Self {
        Self {
            username: username.into(),
            auth: None,
            privacy: None,
            context_name: None,
            master_keys: None,
        }
    }

    /// Add authentication (authNoPriv or authPriv).
    ///
    /// This method performs the full key derivation (~850us for SHA-256) when
    /// the client connects. When polling many engines with shared credentials,
    /// consider using [`with_master_keys`](Self::with_master_keys) instead.
    ///
    /// # Supported Protocols
    ///
    /// - `AuthProtocol::Md5` - HMAC-MD5-96 (legacy)
    /// - `AuthProtocol::Sha1` - HMAC-SHA-96 (legacy)
    /// - `AuthProtocol::Sha224` - HMAC-SHA-224
    /// - `AuthProtocol::Sha256` - HMAC-SHA-256
    /// - `AuthProtocol::Sha384` - HMAC-SHA-384
    /// - `AuthProtocol::Sha512` - HMAC-SHA-512
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::{Auth, AuthProtocol};
    ///
    /// let auth: Auth = Auth::usm("admin")
    ///     .auth(AuthProtocol::Sha256, "mypassword")
    ///     .into();
    /// ```
    #[must_use]
    pub fn auth(mut self, protocol: AuthProtocol, password: impl Into<String>) -> Self {
        self.auth = Some((protocol, password.into()));
        self
    }

    /// Add privacy/encryption (authPriv).
    ///
    /// Privacy requires authentication; this is validated at connection time.
    ///
    /// # Supported Protocols
    ///
    /// - `PrivProtocol::Des` - DES-CBC (legacy, insecure)
    /// - `PrivProtocol::Aes128` - AES-128-CFB
    /// - `PrivProtocol::Aes192` - AES-192-CFB
    /// - `PrivProtocol::Aes256` - AES-256-CFB
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::{Auth, AuthProtocol, PrivProtocol};
    ///
    /// let auth: Auth = Auth::usm("admin")
    ///     .auth(AuthProtocol::Sha256, "authpassword")
    ///     .privacy(PrivProtocol::Aes128, "privpassword")
    ///     .into();
    /// ```
    #[must_use]
    pub fn privacy(mut self, protocol: PrivProtocol, password: impl Into<String>) -> Self {
        self.privacy = Some((protocol, password.into()));
        self
    }

    /// Use pre-computed master keys for authentication and privacy.
    ///
    /// This is the efficient path when polling many engines with shared
    /// credentials. The expensive password-to-key derivation
    /// (~850μs) is done once when creating the [`MasterKeys`], and only the
    /// cheap localization (~1μs) is performed per engine.
    ///
    /// When master keys are set, the [`auth`](Self::auth) and
    /// [`privacy`](Self::privacy) methods are ignored.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::{Auth, AuthProtocol, PrivProtocol, MasterKeys};
    ///
    /// // Derive master keys once
    /// let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpassword").unwrap()
    ///     .with_privacy(PrivProtocol::Aes128, b"privpassword").unwrap();
    ///
    /// // Use with multiple clients
    /// let auth: Auth = Auth::usm("admin")
    ///     .with_master_keys(master_keys)
    ///     .into();
    /// ```
    #[must_use]
    pub fn with_master_keys(mut self, master_keys: MasterKeys) -> Self {
        self.master_keys = Some(master_keys);
        self
    }

    /// Set the `SNMPv3` context name for VACM context selection.
    ///
    /// The context name allows selecting different MIB views on the same agent.
    /// Most deployments use empty string (default).
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::{Auth, AuthProtocol};
    ///
    /// let auth: Auth = Auth::usm("admin")
    ///     .auth(AuthProtocol::Sha256, "password")
    ///     .context_name("vlan100")
    ///     .into();
    /// ```
    #[must_use]
    pub fn context_name(mut self, name: impl Into<String>) -> Self {
        self.context_name = Some(name.into());
        self
    }
}

impl From<UsmBuilder> for Auth {
    fn from(b: UsmBuilder) -> Auth {
        Auth::Usm(UsmAuth {
            username: b.username,
            auth_protocol: b
                .master_keys
                .as_ref()
                .map(super::super::v3::auth::MasterKeys::auth_protocol)
                .or(b.auth.as_ref().map(|(p, _)| *p)),
            auth_password: b.auth.map(|(_, pw)| pw),
            priv_protocol: b
                .master_keys
                .as_ref()
                .and_then(super::super::v3::auth::MasterKeys::priv_protocol)
                .or(b.privacy.as_ref().map(|(p, _)| *p)),
            priv_password: b.privacy.map(|(_, pw)| pw),
            context_name: b.context_name,
            master_keys: b.master_keys,
        })
    }
}

/// Placeholder printed in place of a redacted secret value.
const REDACTED: &str = "[REDACTED]";

/// Formats an `Option<String>` secret as either `None` or a redacted marker,
/// never printing the underlying value.
fn redact_opt(value: &Option<String>) -> &'static str {
    match value {
        Some(_) => REDACTED,
        None => "None",
    }
}

impl std::fmt::Debug for Auth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Auth::Community { version, .. } => f
                .debug_struct("Auth::Community")
                .field("version", version)
                .field("community", &REDACTED)
                .finish(),
            Auth::Usm(usm) => f.debug_tuple("Auth::Usm").field(usm).finish(),
        }
    }
}

impl std::fmt::Debug for UsmAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UsmAuth")
            .field("username", &self.username)
            .field("auth_protocol", &self.auth_protocol)
            .field("auth_password", &redact_opt(&self.auth_password))
            .field("priv_protocol", &self.priv_protocol)
            .field("priv_password", &redact_opt(&self.priv_password))
            .field("context_name", &self.context_name)
            .field("master_keys", &self.master_keys)
            .finish()
    }
}

impl std::fmt::Debug for UsmBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UsmBuilder")
            .field("username", &self.username)
            .field(
                "auth",
                &self.auth.as_ref().map(|(protocol, _)| (protocol, REDACTED)),
            )
            .field(
                "privacy",
                &self
                    .privacy
                    .as_ref()
                    .map(|(protocol, _)| (protocol, REDACTED)),
            )
            .field("context_name", &self.context_name)
            .field("master_keys", &self.master_keys)
            .finish()
    }
}

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

    #[test]
    fn test_default_auth() {
        let auth = Auth::default();
        match auth {
            Auth::Community { version, community } => {
                assert_eq!(version, CommunityVersion::V2c);
                assert_eq!(community, "public");
            }
            Auth::Usm(_) => panic!("expected Community variant"),
        }
    }

    #[test]
    fn test_v1_auth() {
        let auth = Auth::v1("private");
        match auth {
            Auth::Community { version, community } => {
                assert_eq!(version, CommunityVersion::V1);
                assert_eq!(community, "private");
            }
            Auth::Usm(_) => panic!("expected Community variant"),
        }
    }

    #[test]
    fn test_v2c_auth() {
        let auth = Auth::v2c("secret");
        match auth {
            Auth::Community { version, community } => {
                assert_eq!(version, CommunityVersion::V2c);
                assert_eq!(community, "secret");
            }
            Auth::Usm(_) => panic!("expected Community variant"),
        }
    }

    #[test]
    fn test_community_version_default() {
        let version = CommunityVersion::default();
        assert_eq!(version, CommunityVersion::V2c);
    }

    #[test]
    fn test_usm_no_auth_no_priv() {
        let auth: Auth = Auth::usm("readonly").into();
        match auth {
            Auth::Usm(usm) => {
                assert_eq!(usm.username, "readonly");
                assert!(usm.auth_protocol.is_none());
                assert!(usm.auth_password.is_none());
                assert!(usm.priv_protocol.is_none());
                assert!(usm.priv_password.is_none());
                assert!(usm.context_name.is_none());
            }
            Auth::Community { .. } => panic!("expected Usm variant"),
        }
    }

    #[test]
    fn test_usm_auth_no_priv() {
        let auth: Auth = Auth::usm("admin")
            .auth(AuthProtocol::Sha256, "authpass123")
            .into();
        match auth {
            Auth::Usm(usm) => {
                assert_eq!(usm.username, "admin");
                assert_eq!(usm.auth_protocol, Some(AuthProtocol::Sha256));
                assert_eq!(usm.auth_password, Some("authpass123".to_string()));
                assert!(usm.priv_protocol.is_none());
                assert!(usm.priv_password.is_none());
            }
            Auth::Community { .. } => panic!("expected Usm variant"),
        }
    }

    #[test]
    fn test_usm_auth_priv() {
        let auth: Auth = Auth::usm("admin")
            .auth(AuthProtocol::Sha256, "authpass")
            .privacy(PrivProtocol::Aes128, "privpass")
            .into();
        match auth {
            Auth::Usm(usm) => {
                assert_eq!(usm.username, "admin");
                assert_eq!(usm.auth_protocol, Some(AuthProtocol::Sha256));
                assert_eq!(usm.auth_password, Some("authpass".to_string()));
                assert_eq!(usm.priv_protocol, Some(PrivProtocol::Aes128));
                assert_eq!(usm.priv_password, Some("privpass".to_string()));
            }
            Auth::Community { .. } => panic!("expected Usm variant"),
        }
    }

    #[test]
    fn test_usm_with_context_name() {
        let auth: Auth = Auth::usm("admin")
            .auth(AuthProtocol::Sha256, "authpass")
            .context_name("vlan100")
            .into();
        match auth {
            Auth::Usm(usm) => {
                assert_eq!(usm.username, "admin");
                assert_eq!(usm.context_name, Some("vlan100".to_string()));
            }
            Auth::Community { .. } => panic!("expected Usm variant"),
        }
    }

    #[test]
    fn test_usm_builder_chaining() {
        // Verify all methods can be chained
        let auth: Auth = Auth::usm("user")
            .auth(AuthProtocol::Sha512, "auth")
            .privacy(PrivProtocol::Aes256, "priv")
            .context_name("ctx")
            .into();

        match auth {
            Auth::Usm(usm) => {
                assert_eq!(usm.username, "user");
                assert_eq!(usm.auth_protocol, Some(AuthProtocol::Sha512));
                assert_eq!(usm.auth_password, Some("auth".to_string()));
                assert_eq!(usm.priv_protocol, Some(PrivProtocol::Aes256));
                assert_eq!(usm.priv_password, Some("priv".to_string()));
                assert_eq!(usm.context_name, Some("ctx".to_string()));
            }
            Auth::Community { .. } => panic!("expected Usm variant"),
        }
    }

    #[test]
    fn test_debug_redacts_secrets() {
        // Community string must not appear in Debug output.
        let community = Auth::v2c("supersecretcommunity");
        let rendered = format!("{community:?}");
        assert!(!rendered.contains("supersecretcommunity"), "{rendered}");
        assert!(rendered.contains("[REDACTED]"), "{rendered}");

        // USM auth/priv passwords must not appear in Debug output.
        let builder = Auth::usm("admin")
            .auth(AuthProtocol::Sha256, "authpassword123")
            .privacy(PrivProtocol::Aes128, "privpassword456")
            .context_name("vlan100");
        let builder_rendered = format!("{builder:?}");
        assert!(
            !builder_rendered.contains("authpassword123"),
            "{builder_rendered}"
        );
        assert!(
            !builder_rendered.contains("privpassword456"),
            "{builder_rendered}"
        );
        // Non-secret fields remain visible.
        assert!(builder_rendered.contains("admin"), "{builder_rendered}");
        assert!(builder_rendered.contains("vlan100"), "{builder_rendered}");

        let usm: Auth = builder.into();
        let usm_rendered = format!("{usm:?}");
        assert!(!usm_rendered.contains("authpassword123"), "{usm_rendered}");
        assert!(!usm_rendered.contains("privpassword456"), "{usm_rendered}");
        assert!(usm_rendered.contains("[REDACTED]"), "{usm_rendered}");
        assert!(usm_rendered.contains("admin"), "{usm_rendered}");
    }
}