use crate::network::types::{SnmpInfo, SnmpPduType, SnmpVersion};
const MIN_SNMP_SIZE: usize = 10;
const BER_SEQUENCE: u8 = 0x30;
const BER_INTEGER: u8 = 0x02;
const BER_OCTET_STRING: u8 = 0x04;
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;
pub(super) fn analyze_snmp(payload: &[u8]) -> Option<SnmpInfo> {
if payload.len() < MIN_SNMP_SIZE {
return None;
}
if payload[0] != BER_SEQUENCE {
return None;
}
let (seq_len, mut offset) = parse_ber_length(&payload[1..])?;
offset += 1;
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)?;
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());
(community, pdu_type_at(payload, offset)?)
}
SnmpVersion::V3 => (None, v3_pdu_type(payload, offset)?),
};
Some(SnmpInfo {
version,
community,
pdu_type,
})
}
fn parse_ber_length(data: &[u8]) -> Option<(usize, usize)> {
if data.is_empty() {
return None;
}
let first = data[0];
if first < 0x80 {
Some((first as usize, 1))
} else if first == 0x80 {
None
} else {
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))
}
}
fn parse_version(data: &[u8]) -> Option<SnmpVersion> {
if data.is_empty() {
return None;
}
match data[data.len() - 1] {
0 => Some(SnmpVersion::V1),
1 => Some(SnmpVersion::V2c),
3 => Some(SnmpVersion::V3),
_ => None,
}
}
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)
}
fn v3_pdu_type(payload: &[u8], offset: usize) -> Option<SnmpPduType> {
let offset = skip_tlv(payload, offset, BER_SEQUENCE)?; let offset = skip_tlv(payload, offset, BER_OCTET_STRING)?;
match *payload.get(offset)? {
BER_SEQUENCE => {
let (scoped, _) = read_tlv(payload, offset, BER_SEQUENCE)?;
let offset = skip_tlv(scoped, 0, BER_OCTET_STRING)?; let offset = skip_tlv(scoped, offset, BER_OCTET_STRING)?; pdu_type_at(scoped, offset)
}
BER_OCTET_STRING => {
read_tlv(payload, offset, BER_OCTET_STRING)?;
Some(SnmpPduType::Encrypted)
}
_ => None,
}
}
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))
}
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() {
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());
}
fn build_snmp_community_msg(version: u8, pdu_tag: u8, community: &str) -> Vec<u8> {
let mut packet = Vec::new();
packet.push(BER_SEQUENCE);
let len_pos = packet.len();
packet.push(0x00);
packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(version);
packet.push(BER_OCTET_STRING);
packet.push(community.len() as u8);
packet.extend_from_slice(community.as_bytes());
packet.push(pdu_tag);
packet.push(0x10); packet.push(BER_INTEGER);
packet.push(0x04);
packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(0x00);
packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(0x00);
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]; let (len, bytes) = parse_ber_length(&data).unwrap();
assert_eq!(len, 256);
assert_eq!(bytes, 3);
}
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);
packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(0x03);
packet.push(BER_SEQUENCE);
packet.push(0x10);
packet.push(BER_INTEGER);
packet.push(0x04);
packet.extend_from_slice(&[0x12, 0xA3, 0x44, 0x56]); packet.push(BER_INTEGER);
packet.push(0x02);
packet.extend_from_slice(&[0x05, 0xDC]); packet.push(BER_OCTET_STRING);
packet.push(0x01);
packet.push(0x04); packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(0x03);
packet.push(BER_OCTET_STRING);
packet.push(0x02);
packet.extend_from_slice(&[0x30, 0x00]);
if scoped_pdu_plaintext {
packet.push(BER_SEQUENCE);
packet.push(0x0D);
packet.push(BER_OCTET_STRING);
packet.push(0x02);
packet.extend_from_slice(&[0x80, 0x01]); packet.push(BER_OCTET_STRING);
packet.push(0x00); packet.push(PDU_GET_REQUEST);
packet.push(0x05);
packet.push(BER_INTEGER);
packet.push(0x01);
packet.push(0x01); packet.push(BER_SEQUENCE);
packet.push(0x00); } else {
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() {
let mut packet = build_snmp_v1_get("public");
let pdu_pos = packet.iter().position(|&b| b == PDU_GET_REQUEST).unwrap();
packet[pdu_pos] = BER_INTEGER;
assert!(analyze_snmp(&packet).is_none());
}
}