async-snmp 0.13.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! Protocol version-specific notification handlers.
//!
//! This module contains the internal handlers for processing `SNMPv1`, v2c, and v3
//! notification messages.

use std::net::SocketAddr;
use std::sync::atomic::{AtomicU32, Ordering};

use bytes::Bytes;

use crate::ber::{Decoder, tag};
use crate::error::internal::{AuthErrorKind, CryptoErrorKind, DecodeErrorKind, EncodeErrorKind};
use crate::error::{Error, Result};
use crate::message::{
    CommunityMessage, MsgFlags, MsgGlobalData, ScopedPdu, SecurityLevel, V3Message, V3MessageData,
};
use crate::oid::Oid;
use crate::pdu::{Pdu, PduType, TrapV1Pdu};
use crate::v3::auth::{authenticate_message, verify_message};
use crate::v3::{EngineState, LocalizedKey, UsmSecurityParams, in_authoritative_time_window};
use crate::value::Value;
use crate::varbind::VarBind;

use super::types::DerivedKeys;
use super::varbind::extract_notification_varbinds;
use super::{Notification, ReceiverInner};
use crate::v3::compute_engine_boots_time;

/// A USM processing failure, binding the usmStats counter to the report OID
/// sent for it (RFC 3414 Section 3.2) so the pair cannot be mismatched.
#[derive(Clone, Copy)]
enum UsmFailure {
    UnknownEngineIds,
    UnknownUserNames,
    WrongDigests,
    NotInTimeWindows,
    UnsupportedSecLevels,
    DecryptionErrors,
}

impl UsmFailure {
    fn counter(self, inner: &ReceiverInner) -> &AtomicU32 {
        match self {
            Self::UnknownEngineIds => &inner.usm_unknown_engine_ids,
            Self::UnknownUserNames => &inner.usm_unknown_usernames,
            Self::WrongDigests => &inner.usm_wrong_digests,
            Self::NotInTimeWindows => &inner.usm_not_in_time_windows,
            Self::UnsupportedSecLevels => &inner.usm_unsupported_sec_levels,
            Self::DecryptionErrors => &inner.usm_decryption_errors,
        }
    }

    fn report_oid(self) -> Oid {
        match self {
            Self::UnknownEngineIds => crate::v3::report_oids::unknown_engine_ids(),
            Self::UnknownUserNames => crate::v3::report_oids::unknown_user_names(),
            Self::WrongDigests => crate::v3::report_oids::wrong_digests(),
            Self::NotInTimeWindows => crate::v3::report_oids::not_in_time_windows(),
            Self::UnsupportedSecLevels => crate::v3::report_oids::unsupported_sec_levels(),
            Self::DecryptionErrors => crate::v3::report_oids::decryption_errors(),
        }
    }
}

impl super::NotificationReceiver {
    /// Handle `SNMPv1` message.
    pub(super) async fn handle_v1(
        &self,
        data: Bytes,
        source: SocketAddr,
    ) -> Result<Option<Notification>> {
        // For v1, we need to check if it's a Trap PDU (has different structure)
        let mut decoder = Decoder::with_target(data, source);
        let mut seq = decoder.read_sequence()?;

        let _version = seq.read_integer()?;
        let community = seq.read_octet_string()?;

        if !super::community_allowed(&self.inner.communities, &community) {
            tracing::debug!(target: "async_snmp::notification", { snmp.source = %source }, "dropped v1 notification with unaccepted community");
            return Ok(None);
        }

        // Peek at PDU tag
        let pdu_tag = seq.peek_tag().ok_or_else(|| {
            tracing::debug!(target: "async_snmp::notification", { source = %source, kind = %DecodeErrorKind::TruncatedData }, "truncated notification data");
            Error::MalformedResponse { target: source }.boxed()
        })?;

        if pdu_tag == tag::pdu::TRAP_V1 {
            let trap = TrapV1Pdu::decode(&mut seq)?;
            Ok(Some(Notification::TrapV1 { community, trap }))
        } else {
            // Not a trap, ignore (could be a v1 request which we don't handle)
            Ok(None)
        }
    }

    /// Handle `SNMPv2c` message.
    pub(super) async fn handle_v2c(
        &self,
        data: Bytes,
        source: SocketAddr,
    ) -> Result<Option<Notification>> {
        let msg = CommunityMessage::decode(data)?;

        if !super::community_allowed(&self.inner.communities, &msg.community) {
            tracing::debug!(target: "async_snmp::notification", { snmp.source = %source }, "dropped v2c notification with unaccepted community");
            return Ok(None);
        }

        // V2c messages carry standard PDUs; TrapV1 is only valid in V1 messages.
        let Some(pdu) = msg.pdu.standard() else {
            return Ok(None);
        };

        match pdu.pdu_type {
            PduType::TrapV2 => {
                let (uptime, trap_oid, varbinds) = extract_notification_varbinds(pdu)?;
                Ok(Some(Notification::TrapV2c {
                    community: msg.community,
                    uptime,
                    trap_oid,
                    varbinds,
                    request_id: pdu.request_id,
                }))
            }
            PduType::InformRequest => {
                let (uptime, trap_oid, varbinds) = extract_notification_varbinds(pdu)?;
                let request_id = pdu.request_id;

                // Send response
                let response = pdu.to_response();
                let response_msg = CommunityMessage::v2c(msg.community.clone(), response);
                let response_bytes = response_msg.encode();

                self.inner
                    .socket
                    .send_to(&response_bytes, source)
                    .await
                    .map_err(|e| Error::Network {
                        target: source,
                        source: e,
                    })?;

                tracing::debug!(target: "async_snmp::notification", { snmp.source = %source, snmp.request_id = request_id }, "sent Inform response");

                Ok(Some(Notification::InformV2c {
                    community: msg.community,
                    uptime,
                    trap_oid,
                    varbinds,
                    request_id,
                }))
            }
            _ => Ok(None), // Not a notification PDU
        }
    }

    /// Handle `SNMPv3` message.
    pub(super) async fn handle_v3(
        &self,
        data: Bytes,
        source: SocketAddr,
    ) -> Result<Option<Notification>> {
        let msg = V3Message::decode(data.clone())?;
        let security_level = msg.global_data.msg_flags.security_level;

        // Decode USM security parameters
        let usm_params = UsmSecurityParams::decode(msg.security_params.clone())?;

        // Check for discovery request (empty engine ID)
        if usm_params.engine_id.is_empty() {
            return self.handle_v3_discovery(&msg, &usm_params, source).await;
        }

        let username = usm_params.username.clone();
        let engine_id = usm_params.engine_id.clone();

        // RFC 3414 Section 3.2 Step 4: the user must exist in the local
        // configuration regardless of security level.
        let Some(user_config) = self.inner.usm_users.get(&username) else {
            tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.username = %String::from_utf8_lossy(&username) }, "V3 message for unknown user");
            self.send_usm_report(
                &msg,
                &usm_params,
                UsmFailure::UnknownUserNames,
                None,
                source,
            )
            .await;
            return Ok(None);
        };
        let derived_keys = user_config
            .derive_keys(&engine_id)
            .map_err(|e| Error::Config(e.to_string().into()).boxed())?;

        // RFC 3414 Section 3.2 Step 5: the user must support the requested
        // security level, checked before authentication (Step 6). The
        // missing-auth-key half of Step 5 is handled by the match below,
        // which also dispatches before any digest is verified.
        if security_level == SecurityLevel::AuthPriv && derived_keys.priv_key.is_none() {
            tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.username = %String::from_utf8_lossy(&username) }, "received encrypted V3 message but no privacy key configured for user");
            self.send_usm_report(
                &msg,
                &usm_params,
                UsmFailure::UnsupportedSecLevels,
                None,
                source,
            )
            .await;
            return Ok(None);
        }

        // Verify authentication if required
        if security_level == SecurityLevel::AuthNoPriv || security_level == SecurityLevel::AuthPriv
        {
            match derived_keys.auth_key.as_ref() {
                Some(auth_key) => {
                    let (auth_offset, auth_len) = UsmSecurityParams::find_auth_params_offset(&data)
                        .ok_or_else(|| {
                            tracing::debug!(target: "async_snmp::notification", { source = %source, kind = %AuthErrorKind::AuthParamsNotFound }, "could not find auth params in notification");
                            Error::Auth { target: source }.boxed()
                        })?;

                    if !verify_message(auth_key, &data, auth_offset, auth_len)
                        .map_err(|_| Error::Auth { target: source }.boxed())?
                    {
                        tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.username = %String::from_utf8_lossy(&username) }, "V3 authentication failed");
                        self.send_usm_report(
                            &msg,
                            &usm_params,
                            UsmFailure::WrongDigests,
                            None,
                            source,
                        )
                        .await;
                        return Err(Error::Auth { target: source }.boxed());
                    }
                    tracing::trace!(target: "async_snmp::notification", { snmp.source = %source }, "V3 authentication verified");

                    // Verify time window (RFC 3414 Section 3.2 Step 7)
                    if engine_id == self.inner.engine_id {
                        // We are the authoritative engine for this message
                        // (informs sent under our engine ID): Step 7a,
                        // checked against our own boots/time.
                        let total_secs = self.inner.engine_start.elapsed().as_secs();
                        let (our_boots, our_time) =
                            compute_engine_boots_time(self.inner.engine_boots_base, total_secs);

                        // Covers latched boots, boots mismatch, and time drift.
                        // Like the other Time Window failures, the report must
                        // be authenticated at authNoPriv (RFC 3414 Section 3.2
                        // Step 7a).
                        if !in_authoritative_time_window(
                            our_boots,
                            our_time,
                            usm_params.engine_boots,
                            usm_params.engine_time,
                        ) {
                            tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.msg_boots = usm_params.engine_boots, snmp.msg_time = usm_params.engine_time, snmp.our_boots = our_boots, snmp.our_time = our_time }, "V3 notification outside time window");
                            self.send_usm_report(
                                &msg,
                                &usm_params,
                                UsmFailure::NotInTimeWindows,
                                Some(auth_key),
                                source,
                            )
                            .await;
                            return Err(Error::Auth { target: source }.boxed());
                        }
                    } else {
                        // The sender is the authoritative engine (traps sent
                        // under the sender's engine ID): Step 7b, checked
                        // against per-engine state seeded from the first
                        // authenticated message.
                        //
                        // Copy the engine ID out of the received datagram so a
                        // stored entry does not pin the whole packet buffer.
                        let engine_key = Bytes::copy_from_slice(&engine_id);
                        // Scoped so the lock is released before any await.
                        let timely = {
                            let mut engines = self
                                .inner
                                .remote_engines
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner);
                            // Bound the table: a peer holding one credential can
                            // authenticate under arbitrarily many fabricated engine
                            // IDs, so evict the least-recently-updated engine when
                            // full before seeding a new one.
                            if !engines.contains_key(&engine_key)
                                && engines.len() >= super::MAX_REMOTE_ENGINES
                                && let Some(oldest) = engines
                                    .iter()
                                    .min_by_key(|(_, s)| s.synced_at)
                                    .map(|(k, _)| k.clone())
                            {
                                engines.remove(&oldest);
                            }
                            let state = engines.entry(engine_key).or_insert_with_key(|k| {
                                EngineState::new(
                                    k.clone(),
                                    usm_params.engine_boots,
                                    usm_params.engine_time,
                                )
                            });
                            let timely = state.check_and_update_timeliness(
                                usm_params.engine_boots,
                                usm_params.engine_time,
                            );
                            if !timely {
                                tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.msg_boots = usm_params.engine_boots, snmp.msg_time = usm_params.engine_time, snmp.our_boots = state.engine_boots, snmp.our_time = state.estimated_time() }, "V3 notification outside time window");
                            }
                            timely
                        };
                        if !timely {
                            // RFC 3414 Section 3.2 Step 7b: for a remote
                            // authoritative engine this is a bare error
                            // indication. usmStatsNotInTimeWindows and the
                            // notInTimeWindows Report apply only to the
                            // authoritative case (Step 7a); net-snmp counts
                            // the local-reference branch only.
                            return Err(Error::Auth { target: source }.boxed());
                        }
                    }
                }
                None => {
                    // RFC 3414 Section 3.2 Step 5: the user exists but cannot
                    // meet the requested security level.
                    tracing::warn!(target: "async_snmp::notification", { snmp.source = %source, snmp.username = %String::from_utf8_lossy(&username) }, "received authenticated V3 message but user has no auth key");
                    self.send_usm_report(
                        &msg,
                        &usm_params,
                        UsmFailure::UnsupportedSecLevels,
                        None,
                        source,
                    )
                    .await;
                    return Ok(None);
                }
            }
        }

        // Decrypt if needed
        let scoped_pdu = if security_level == SecurityLevel::AuthPriv {
            // Presence checked at Step 5 above.
            let priv_key = derived_keys
                .priv_key
                .as_ref()
                .expect("authPriv without a privacy key is rejected at Step 5");
            let encrypted_data = match &msg.data {
                V3MessageData::Encrypted(data) => data,
                V3MessageData::Plaintext(_) => {
                    tracing::debug!(target: "async_snmp::notification", { source = %source, kind = %DecodeErrorKind::UnexpectedEncryption }, "expected encrypted scoped PDU in notification");
                    return Err(Error::MalformedResponse { target: source }.boxed());
                }
            };

            let decrypted = priv_key.decrypt(
                encrypted_data,
                usm_params.engine_boots,
                usm_params.engine_time,
                &usm_params.priv_params,
            );
            let decrypted = match decrypted {
                Ok(data) => data,
                Err(e) => {
                    tracing::debug!(target: "async_snmp::notification", { source = %source, error = %e }, "decryption failed");
                    self.send_usm_report(
                        &msg,
                        &usm_params,
                        UsmFailure::DecryptionErrors,
                        None,
                        source,
                    )
                    .await;
                    return Err(Error::Auth { target: source }.boxed());
                }
            };

            let mut decoder = Decoder::with_target(decrypted, source);
            ScopedPdu::decode(&mut decoder)?
        } else if let Some(sp) = msg.scoped_pdu() {
            sp.clone()
        } else {
            tracing::warn!(target: "async_snmp::notification", { snmp.source = %source }, "unexpected encrypted V3 message");
            return Ok(None);
        };

        let context_engine_id = scoped_pdu.context_engine_id.clone();
        let context_name = scoped_pdu.context_name.clone();
        let pdu = &scoped_pdu.pdu;

        match pdu.pdu_type {
            PduType::TrapV2 => {
                let (uptime, trap_oid, varbinds) = extract_notification_varbinds(pdu)?;
                Ok(Some(Notification::TrapV3 {
                    username,
                    context_engine_id,
                    context_name,
                    security_level,
                    uptime,
                    trap_oid,
                    varbinds,
                    request_id: pdu.request_id,
                }))
            }
            PduType::InformRequest => {
                let (uptime, trap_oid, varbinds) = extract_notification_varbinds(pdu)?;
                let request_id = pdu.request_id;

                // Build and send response with appropriate security level
                let response_pdu = pdu.to_response();

                let response_bytes = build_v3_response(
                    &self.inner,
                    &msg,
                    &usm_params,
                    response_pdu,
                    context_engine_id.clone(),
                    context_name.clone(),
                    Some(&derived_keys),
                )?;

                self.inner
                    .socket
                    .send_to(&response_bytes, source)
                    .await
                    .map_err(|e| Error::Network {
                        target: source,
                        source: e,
                    })?;

                tracing::debug!(target: "async_snmp::notification", { snmp.source = %source, snmp.request_id = request_id, snmp.security_level = ?security_level }, "sent V3 Inform response");

                Ok(Some(Notification::InformV3 {
                    username,
                    context_engine_id,
                    context_name,
                    security_level,
                    uptime,
                    trap_oid,
                    varbinds,
                    request_id,
                }))
            }
            _ => Ok(None),
        }
    }

    /// Handle `SNMPv3` engine discovery request.
    ///
    /// Per RFC 3414 Section 4, responds with a Report PDU containing
    /// usmStatsUnknownEngineIDs and the receiver's engine ID in USM params.
    async fn handle_v3_discovery(
        &self,
        msg: &V3Message,
        usm_params: &UsmSecurityParams,
        source: SocketAddr,
    ) -> Result<Option<Notification>> {
        self.send_usm_report(msg, usm_params, UsmFailure::UnknownEngineIds, None, source)
            .await;
        Ok(None)
    }

    /// Count a USM processing failure and send its Report PDU, best-effort.
    ///
    /// The failure's usmStats counter is always incremented. Per RFC 3412
    /// Section 7.1 Step 3 a Report may only be sent when the PDU is Confirmed
    /// Class or, when the PDU class cannot be determined (the case here: the
    /// message failed USM processing), when the reportableFlag is set.
    /// Informs are sent with the flag set and traps without, so this answers
    /// USM-failed informs while staying silent for traps.
    ///
    /// With `auth_key` (localized to the receiver's engine ID) the report is
    /// sent authenticated at authNoPriv, as RFC 3414 Section 3.2 Step 7
    /// requires for notInTimeWindows reports so the sender can trust the
    /// boots/time for resynchronization. Otherwise it is sent noAuthNoPriv.
    ///
    /// Send failures are logged and swallowed: the caller is already on a
    /// failure path and the report is advisory.
    async fn send_usm_report(
        &self,
        msg: &V3Message,
        usm_params: &UsmSecurityParams,
        failure: UsmFailure,
        auth_key: Option<&LocalizedKey>,
        source: SocketAddr,
    ) {
        let count = failure.counter(&self.inner).fetch_add(1, Ordering::Relaxed) + 1;
        if !msg.global_data.msg_flags.reportable {
            return;
        }
        let report_oid = failure.report_oid();

        let total_secs = self.inner.engine_start.elapsed().as_secs();
        let (boots, time) = compute_engine_boots_time(self.inner.engine_boots_base, total_secs);

        // RFC 3412 Section 7.1 Step 3c4: request-id is the value extracted from the
        // original request PDU, or 0 when it cannot be extracted. Every USM-failure
        // path reaches here before the scopedPDU is decoded, so it cannot be extracted.
        // (msgID, which correlates the Report, is carried separately in the header.)
        let report_pdu = Pdu {
            pdu_type: PduType::Report,
            request_id: 0,
            error_status: 0,
            error_index: 0,
            varbinds: vec![VarBind::new(report_oid, Value::Counter32(count))],
        };

        let security_level = if auth_key.is_some() {
            SecurityLevel::AuthNoPriv
        } else {
            SecurityLevel::NoAuthNoPriv
        };
        let response_global = MsgGlobalData::new(
            msg.global_data.msg_id,
            msg.global_data.msg_max_size,
            MsgFlags::new(security_level, false),
        );
        let mut response_usm = UsmSecurityParams::new(
            self.inner.engine_id.clone(),
            boots,
            time,
            usm_params.username.clone(),
        );
        if let Some(key) = auth_key {
            response_usm = response_usm.with_auth_placeholder(key.mac_len());
        }
        let response_scoped =
            ScopedPdu::new(self.inner.engine_id.clone(), Bytes::new(), report_pdu);
        let response_msg = V3Message::new(response_global, response_usm.encode(), response_scoped);
        let mut response_bytes = response_msg.encode().to_vec();

        if let Some(key) = auth_key
            && sign_v3_message(key, &mut response_bytes, self.inner.local_addr).is_err()
        {
            return;
        }

        if let Err(e) = self.inner.socket.send_to(&response_bytes, source).await {
            tracing::debug!(target: "async_snmp::notification", { snmp.source = %source, error = %e }, "failed to send USM report");
        } else {
            tracing::debug!(target: "async_snmp::notification", { snmp.source = %source }, "sent USM report");
        }
    }
}

/// Fill in the HMAC of an encoded V3 message built with an auth placeholder.
///
/// Failures are logged at debug level; `local_addr` is only used as the
/// error's target address.
fn sign_v3_message(
    auth_key: &LocalizedKey,
    message: &mut [u8],
    local_addr: SocketAddr,
) -> Result<()> {
    let (auth_offset, auth_len) = UsmSecurityParams::find_auth_params_offset(message)
        .ok_or_else(|| {
            tracing::debug!(target: "async_snmp::notification", { kind = %EncodeErrorKind::MissingAuthParams }, "could not find auth params in outgoing V3 message");
            Error::MalformedResponse { target: local_addr }.boxed()
        })?;
    authenticate_message(auth_key, message, auth_offset, auth_len).map_err(|e| {
        tracing::debug!(target: "async_snmp::notification", { error = %e }, "failed to authenticate outgoing V3 message");
        Error::Config(e.to_string().into()).boxed()
    })
}

/// Build a V3 response message with appropriate security.
fn build_v3_response(
    inner: &ReceiverInner,
    incoming_msg: &V3Message,
    incoming_usm: &UsmSecurityParams,
    response_pdu: Pdu,
    context_engine_id: Bytes,
    context_name: Bytes,
    derived_keys: Option<&DerivedKeys>,
) -> Result<Bytes> {
    let security_level = incoming_msg.global_data.msg_flags.security_level;

    // Build response with same security level but reportable=false
    let response_global = MsgGlobalData::new(
        incoming_msg.global_data.msg_id,
        incoming_msg.global_data.msg_max_size,
        MsgFlags::new(security_level, false),
    );

    let response_scoped = ScopedPdu::new(context_engine_id, context_name, response_pdu);

    match security_level {
        SecurityLevel::NoAuthNoPriv => {
            // Simple case: no authentication or encryption
            let response_usm = UsmSecurityParams::new(
                incoming_usm.engine_id.clone(),
                incoming_usm.engine_boots,
                incoming_usm.engine_time,
                incoming_usm.username.clone(),
            );
            let response_msg =
                V3Message::new(response_global, response_usm.encode(), response_scoped);
            Ok(response_msg.encode())
        }
        SecurityLevel::AuthNoPriv => {
            // Authentication only
            let local_addr = inner.local_addr;
            let keys = derived_keys.ok_or_else(|| {
                tracing::debug!(target: "async_snmp::notification", { kind = %AuthErrorKind::NoCredentials }, "no credentials for notification response");
                Error::Auth { target: local_addr }.boxed()
            })?;
            let auth_key = keys.auth_key.as_ref().ok_or_else(|| {
                tracing::debug!(target: "async_snmp::notification", { kind = %AuthErrorKind::NoAuthKey }, "no auth key for notification response");
                Error::Auth { target: local_addr }.boxed()
            })?;

            let mac_len = auth_key.mac_len();
            let response_usm = UsmSecurityParams::new(
                incoming_usm.engine_id.clone(),
                incoming_usm.engine_boots,
                incoming_usm.engine_time,
                incoming_usm.username.clone(),
            )
            .with_auth_placeholder(mac_len);

            let response_msg =
                V3Message::new(response_global, response_usm.encode(), response_scoped);

            let mut response_bytes = response_msg.encode().to_vec();
            sign_v3_message(auth_key, &mut response_bytes, local_addr)?;

            Ok(Bytes::from(response_bytes))
        }
        SecurityLevel::AuthPriv => {
            // Authentication and encryption
            let local_addr = inner.local_addr;
            let keys = derived_keys.ok_or_else(|| {
                tracing::debug!(target: "async_snmp::notification", { kind = %AuthErrorKind::NoCredentials }, "no credentials for notification response");
                Error::Auth { target: local_addr }.boxed()
            })?;
            let auth_key = keys.auth_key.as_ref().ok_or_else(|| {
                tracing::debug!(target: "async_snmp::notification", { kind = %AuthErrorKind::NoAuthKey }, "no auth key for notification response");
                Error::Auth { target: local_addr }.boxed()
            })?;
            let priv_key = keys.priv_key.as_ref().ok_or_else(|| {
                tracing::debug!(target: "async_snmp::notification", { kind = %CryptoErrorKind::NoPrivKey }, "no privacy key for notification response");
                Error::Auth { target: local_addr }.boxed()
            })?;

            // Encrypt the scoped PDU
            let scoped_pdu_bytes = response_scoped.encode_to_bytes();
            let (encrypted, priv_params) = priv_key
                .encrypt(
                    &scoped_pdu_bytes,
                    incoming_usm.engine_boots,
                    incoming_usm.engine_time,
                    Some(&inner.salt_counter),
                )
                .map_err(|e| {
                    tracing::debug!(target: "async_snmp::notification", { error = %e }, "encryption failed for notification response");
                    Error::Auth { target: local_addr }.boxed()
                })?;

            let mac_len = auth_key.mac_len();
            let response_usm = UsmSecurityParams::new(
                incoming_usm.engine_id.clone(),
                incoming_usm.engine_boots,
                incoming_usm.engine_time,
                incoming_usm.username.clone(),
            )
            .with_auth_placeholder(mac_len)
            .with_priv_params(priv_params);

            let response_msg =
                V3Message::new_encrypted(response_global, response_usm.encode(), encrypted);

            let mut response_bytes = response_msg.encode().to_vec();
            sign_v3_message(auth_key, &mut response_bytes, local_addr)?;

            Ok(Bytes::from(response_bytes))
        }
    }
}