rustnet-core 0.6.0

Network analysis library: packet parsing, protocol types, deep packet inspection, link-layer parsers, connection merging, and DNS/GeoIP/OUI lookups: the reusable core of rustnet
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
//! SNMP (Simple Network Management Protocol) Deep Packet Inspection
//!
//! Parses SNMP packets (v1, v2c, v3) using simplified BER decoding.
//! SNMP uses UDP ports 161 (agent) and 162 (trap).

use crate::network::types::{SnmpInfo, SnmpPduType, SnmpVersion};

/// Minimum SNMP packet size
const MIN_SNMP_SIZE: usize = 10;

/// BER tag types
const BER_SEQUENCE: u8 = 0x30;
const BER_INTEGER: u8 = 0x02;
const BER_OCTET_STRING: u8 = 0x04;

/// SNMP PDU types (context-specific tags)
const PDU_GET_REQUEST: u8 = 0xA0;
const PDU_GET_NEXT_REQUEST: u8 = 0xA1;
const PDU_GET_RESPONSE: u8 = 0xA2;
const PDU_SET_REQUEST: u8 = 0xA3;
const PDU_TRAP_V1: u8 = 0xA4;
const PDU_GET_BULK_REQUEST: u8 = 0xA5;
const PDU_INFORM_REQUEST: u8 = 0xA6;
const PDU_TRAP_V2: u8 = 0xA7;
const PDU_REPORT: u8 = 0xA8;

/// Analyze an SNMP packet and extract key information.
///
/// Returns `None` if the packet is not valid SNMP.
pub(super) fn analyze_snmp(payload: &[u8]) -> Option<SnmpInfo> {
    if payload.len() < MIN_SNMP_SIZE {
        return None;
    }

    // SNMP message is wrapped in a SEQUENCE
    if payload[0] != BER_SEQUENCE {
        return None;
    }

    let (seq_len, mut offset) = parse_ber_length(&payload[1..])?;
    offset += 1; // Account for SEQUENCE tag

    let payload = payload.get(..offset.checked_add(seq_len)?)?;

    let (version_bytes, offset) = read_tlv(payload, offset, BER_INTEGER)?;
    let version = parse_version(version_bytes)?;

    // Parse community string for v1/v2c (OCTET STRING). It is mandatory in
    // both versions (RFC 1157 ยง4, RFC 3416), so its absence means the
    // payload is not SNMP.
    let (community, pdu_type) = match version {
        SnmpVersion::V1 | SnmpVersion::V2c => {
            let (community_bytes, offset) = read_tlv(payload, offset, BER_OCTET_STRING)?;
            let community = std::str::from_utf8(community_bytes)
                .ok()
                .map(|s| s.to_string());

            // The PDU tag directly follows the community string.
            (community, pdu_type_at(payload, offset)?)
        }
        SnmpVersion::V3 => (None, v3_pdu_type(payload, offset)?),
    };

    Some(SnmpInfo {
        version,
        community,
        pdu_type,
    })
}

/// Parse BER length encoding.
/// Returns (length, bytes consumed).
fn parse_ber_length(data: &[u8]) -> Option<(usize, usize)> {
    if data.is_empty() {
        return None;
    }

    let first = data[0];

    if first < 0x80 {
        // Short form: length is in first byte
        Some((first as usize, 1))
    } else if first == 0x80 {
        // Indefinite form - not supported
        None
    } else {
        // Long form: first byte tells how many bytes encode the length
        let num_bytes = (first & 0x7F) as usize;
        if num_bytes > 4 || data.len() < 1 + num_bytes {
            return None;
        }

        let mut length: usize = 0;
        for i in 0..num_bytes {
            length = (length << 8) | (data[1 + i] as usize);
        }

        Some((length, 1 + num_bytes))
    }
}

/// Parse SNMP version from INTEGER value
fn parse_version(data: &[u8]) -> Option<SnmpVersion> {
    if data.is_empty() {
        return None;
    }

    // Version is encoded as 0=v1, 1=v2c, 3=v3
    match data[data.len() - 1] {
        0 => Some(SnmpVersion::V1),
        1 => Some(SnmpVersion::V2c),
        3 => Some(SnmpVersion::V3),
        _ => None,
    }
}

/// Read the PDU tag expected at exactly `offset`. Structural, never scans:
/// a byte in the 0xA0-0xA8 range inside a length or INTEGER value (e.g. a
/// request-id) must not be mistaken for a PDU tag.
fn pdu_type_at(payload: &[u8], offset: usize) -> Option<SnmpPduType> {
    let pdu_type = match *payload.get(offset)? {
        PDU_GET_REQUEST => SnmpPduType::GetRequest,
        PDU_GET_NEXT_REQUEST => SnmpPduType::GetNextRequest,
        PDU_GET_RESPONSE => SnmpPduType::GetResponse,
        PDU_SET_REQUEST => SnmpPduType::SetRequest,
        PDU_TRAP_V1 => SnmpPduType::Trap,
        PDU_GET_BULK_REQUEST => SnmpPduType::GetBulkRequest,
        PDU_INFORM_REQUEST => SnmpPduType::InformRequest,
        PDU_TRAP_V2 => SnmpPduType::TrapV2,
        PDU_REPORT => SnmpPduType::Report,
        _ => return None,
    };
    Some(pdu_type)
}

/// Walk the SNMPv3 message structure (RFC 3412 ยง6) to the PDU tag:
/// msgGlobalData (SEQUENCE) and msgSecurityParameters (OCTET STRING) are
/// skipped whole, then msgData is either a plaintext ScopedPDU (a SEQUENCE
/// holding contextEngineID, contextName, and the PDU) or an encrypted
/// OCTET STRING, in which case the PDU type is not visible.
fn v3_pdu_type(payload: &[u8], offset: usize) -> Option<SnmpPduType> {
    let offset = skip_tlv(payload, offset, BER_SEQUENCE)?; // msgGlobalData
    let offset = skip_tlv(payload, offset, BER_OCTET_STRING)?; // msgSecurityParameters

    match *payload.get(offset)? {
        BER_SEQUENCE => {
            // Scope nested reads to the declared SEQUENCE, including its length.
            let (scoped, _) = read_tlv(payload, offset, BER_SEQUENCE)?;
            let offset = skip_tlv(scoped, 0, BER_OCTET_STRING)?; // contextEngineID
            let offset = skip_tlv(scoped, offset, BER_OCTET_STRING)?; // contextName
            pdu_type_at(scoped, offset)
        }
        BER_OCTET_STRING => {
            read_tlv(payload, offset, BER_OCTET_STRING)?;
            Some(SnmpPduType::Encrypted)
        }
        _ => None,
    }
}

/// Read one TLV with the expected tag at exactly `offset`, returning its
/// value bytes and the offset just past it. Structural, never scans.
fn read_tlv(payload: &[u8], offset: usize, expected_tag: u8) -> Option<(&[u8], usize)> {
    if *payload.get(offset)? != expected_tag {
        return None;
    }
    let offset = offset + 1;
    let (len, len_bytes) = parse_ber_length(&payload[offset..])?;
    let start = offset.checked_add(len_bytes)?;
    let end = start.checked_add(len)?;
    (end <= payload.len()).then(|| (&payload[start..end], end))
}

/// Skip one TLV with the expected tag, returning the offset just past it.
fn skip_tlv(payload: &[u8], offset: usize, expected_tag: u8) -> Option<usize> {
    read_tlv(payload, offset, expected_tag).map(|(_, end)| end)
}

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

    #[test]
    fn oversized_sequence_lengths_are_rejected() {
        let mut packet = vec![0x30, 0x84, 0xff, 0xff, 0xff, 0xff];
        packet.extend_from_slice(&[0x02, 1, 1, 0x04, 0, 0xa0]);
        assert!(analyze_snmp(&packet).is_none());
    }

    #[test]
    fn sequence_cannot_borrow_fields_from_trailing_bytes() {
        let packet = [0x30, 3, 0x02, 1, 1, 0x04, 0, 0xa0, 0, 0];
        assert!(analyze_snmp(&packet).is_none());
    }

    #[test]
    fn nested_v3_lengths_cannot_escape_their_container() {
        // Empty global/security fields followed by a ScopedPDU whose length
        // cannot cover the two context fields and the PDU tag after it.
        for length in [0, 1, 4, 6, 0xff] {
            let body = [0x30, 0, 0x04, 0, 0x30, length, 0x04, 0, 0x04, 0, 0xa0];
            assert!(v3_pdu_type(&body, 0).is_none());
        }
        let valid = [0x30, 0, 0x04, 0, 0x30, 5, 0x04, 0, 0x04, 0, 0xa0];
        assert_eq!(v3_pdu_type(&valid, 0), Some(SnmpPduType::GetRequest));
        for suffix in [
            &[0x04][..],
            &[0x04, 1],
            &[0x04, 0x84, 0xff, 0xff, 0xff, 0xff],
            &[0x30, 0x84, 0xff, 0xff, 0xff, 0xff],
        ] {
            let mut body = vec![0x30, 0, 0x04, 0];
            body.extend_from_slice(suffix);
            assert!(v3_pdu_type(&body, 0).is_none());
        }
    }

    #[test]
    fn ber_lengths_and_tlv_offsets_are_bounded() {
        assert_eq!(
            parse_ber_length(&[0x84, 0xff, 0xff, 0xff, 0xff]),
            Some((u32::MAX as usize, 5))
        );
        for bytes in [&[0x80][..], &[0x84, 0xff], &[0x85, 0, 0, 0, 0, 1]] {
            assert!(parse_ber_length(bytes).is_none());
        }
        assert!(read_tlv(&[BER_INTEGER, 1, 3], usize::MAX, BER_INTEGER).is_none());
    }

    /// Build a community-based (v1 / v2c) SNMP message: `version` is the
    /// INTEGER value (0 = v1, 1 = v2c), `pdu_tag` the PDU's context-specific
    /// tag. The PDU carries request-id 1, error-status 0, error-index 0 and
    /// empty variable bindings.
    fn build_snmp_community_msg(version: u8, pdu_tag: u8, community: &str) -> Vec<u8> {
        let mut packet = Vec::new();

        // SEQUENCE
        packet.push(BER_SEQUENCE);
        let len_pos = packet.len();
        packet.push(0x00); // Placeholder, patched below

        // Version: INTEGER
        packet.push(BER_INTEGER);
        packet.push(0x01);
        packet.push(version);

        // Community: OCTET STRING
        packet.push(BER_OCTET_STRING);
        packet.push(community.len() as u8);
        packet.extend_from_slice(community.as_bytes());

        // PDU
        packet.push(pdu_tag);
        packet.push(0x10); // PDU length
        // Request ID
        packet.push(BER_INTEGER);
        packet.push(0x04);
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
        // Error status
        packet.push(BER_INTEGER);
        packet.push(0x01);
        packet.push(0x00);
        // Error index
        packet.push(BER_INTEGER);
        packet.push(0x01);
        packet.push(0x00);
        // Variable bindings (empty)
        packet.push(BER_SEQUENCE);
        packet.push(0x00);

        packet[len_pos] = (packet.len() - len_pos - 1) as u8;

        packet
    }

    fn build_snmp_v1_get(community: &str) -> Vec<u8> {
        build_snmp_community_msg(0x00, PDU_GET_REQUEST, community)
    }

    fn build_snmp_v2c_response(community: &str) -> Vec<u8> {
        build_snmp_community_msg(0x01, PDU_GET_RESPONSE, community)
    }

    #[test]
    fn test_snmp_v1_get() {
        let packet = build_snmp_v1_get("public");
        let info = analyze_snmp(&packet).expect("should parse");
        assert_eq!(info.version, SnmpVersion::V1);
        assert_eq!(info.community, Some("public".to_string()));
        assert_eq!(info.pdu_type, SnmpPduType::GetRequest);
    }

    #[test]
    fn test_snmp_v2c_response() {
        let packet = build_snmp_v2c_response("private");
        let info = analyze_snmp(&packet).expect("should parse");
        assert_eq!(info.version, SnmpVersion::V2c);
        assert_eq!(info.community, Some("private".to_string()));
        assert_eq!(info.pdu_type, SnmpPduType::GetResponse);
    }

    #[test]
    fn test_snmp_too_short() {
        let packet = [0x30, 0x05, 0x02, 0x01, 0x00];
        assert!(analyze_snmp(&packet).is_none());
    }

    #[test]
    fn test_snmp_not_sequence() {
        let packet = [
            0x31, 0x10, 0x02, 0x01, 0x00, 0x04, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63,
        ];
        assert!(analyze_snmp(&packet).is_none());
    }

    #[test]
    fn test_ber_length_short() {
        let data = [0x10];
        let (len, bytes) = parse_ber_length(&data).unwrap();
        assert_eq!(len, 16);
        assert_eq!(bytes, 1);
    }

    #[test]
    fn test_ber_length_long() {
        let data = [0x82, 0x01, 0x00]; // 256
        let (len, bytes) = parse_ber_length(&data).unwrap();
        assert_eq!(len, 256);
        assert_eq!(bytes, 3);
    }

    /// Build an SNMPv3 message. `scoped_pdu_plaintext` selects between a
    /// plaintext ScopedPDU (carrying a GetRequest) and an encrypted one.
    fn build_snmp_v3(scoped_pdu_plaintext: bool) -> Vec<u8> {
        let mut packet = Vec::new();

        packet.push(BER_SEQUENCE);
        let len_pos = packet.len();
        packet.push(0x00);

        // Version: INTEGER 3 (v3)
        packet.push(BER_INTEGER);
        packet.push(0x01);
        packet.push(0x03);

        // msgGlobalData SEQUENCE: msgID, msgMaxSize, msgFlags, msgSecurityModel.
        // msgID contains a 0xA3 byte, which must not be read as a PDU tag.
        packet.push(BER_SEQUENCE);
        packet.push(0x10);
        packet.push(BER_INTEGER);
        packet.push(0x04);
        packet.extend_from_slice(&[0x12, 0xA3, 0x44, 0x56]); // msgID
        packet.push(BER_INTEGER);
        packet.push(0x02);
        packet.extend_from_slice(&[0x05, 0xDC]); // msgMaxSize 1500
        packet.push(BER_OCTET_STRING);
        packet.push(0x01);
        packet.push(0x04); // msgFlags: reportable
        packet.push(BER_INTEGER);
        packet.push(0x01);
        packet.push(0x03); // msgSecurityModel: USM

        // msgSecurityParameters: opaque OCTET STRING
        packet.push(BER_OCTET_STRING);
        packet.push(0x02);
        packet.extend_from_slice(&[0x30, 0x00]);

        if scoped_pdu_plaintext {
            // ScopedPDU SEQUENCE: contextEngineID, contextName, PDU
            packet.push(BER_SEQUENCE);
            packet.push(0x0D);
            packet.push(BER_OCTET_STRING);
            packet.push(0x02);
            packet.extend_from_slice(&[0x80, 0x01]); // contextEngineID
            packet.push(BER_OCTET_STRING);
            packet.push(0x00); // contextName (empty)
            packet.push(PDU_GET_REQUEST);
            packet.push(0x05);
            packet.push(BER_INTEGER);
            packet.push(0x01);
            packet.push(0x01); // request-id
            packet.push(BER_SEQUENCE);
            packet.push(0x00); // varbinds (empty)
        } else {
            // Encrypted ScopedPDU: opaque OCTET STRING
            packet.push(BER_OCTET_STRING);
            packet.push(0x04);
            packet.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
        }

        packet[len_pos] = (packet.len() - len_pos - 1) as u8;
        packet
    }

    #[test]
    fn test_snmp_v3_plaintext_scoped_pdu() {
        let packet = build_snmp_v3(true);
        let info = analyze_snmp(&packet).expect("should parse");
        assert_eq!(info.version, SnmpVersion::V3);
        assert_eq!(info.community, None);
        assert_eq!(info.pdu_type, SnmpPduType::GetRequest);
    }

    #[test]
    fn test_snmp_v3_encrypted_scoped_pdu() {
        let packet = build_snmp_v3(false);
        let info = analyze_snmp(&packet).expect("should parse");
        assert_eq!(info.version, SnmpVersion::V3);
        assert_eq!(info.pdu_type, SnmpPduType::Encrypted);
    }

    #[test]
    fn test_pdu_tag_not_scanned_from_value_bytes() {
        // A v1 message whose community is followed by a non-PDU byte must be
        // rejected; the detector must not scan ahead for a 0xA0-0xA8 byte.
        let mut packet = build_snmp_v1_get("public");
        // Overwrite the PDU tag with an INTEGER tag: still not SNMP.
        let pdu_pos = packet.iter().position(|&b| b == PDU_GET_REQUEST).unwrap();
        packet[pdu_pos] = BER_INTEGER;
        assert!(analyze_snmp(&packet).is_none());
    }
}