1 /* Copyright (C) 2017-2020 Open Information Security Foundation
3 * You can copy, redistribute or modify this Program under the terms of
4 * the GNU General Public License version 2 as published by the Free
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * version 2 along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 // written by Pierre Chifflier <chifflier@wzdftpd.net>
20 use crate::snmp::snmp_parser::*;
21 use crate::core::{self, *};
22 use crate::applayer::{self, *};
24 use std::ffi::CString;
26 use der_parser::ber::BerObjectContent;
27 use der_parser::der::parse_der_sequence;
28 use der_parser::oid::Oid;
31 use nom::error::ErrorKind;
33 #[derive(AppLayerEvent)]
40 pub struct SNMPState<'a> {
41 /// SNMP protocol version
44 /// List of transactions for this session
45 transactions: Vec<SNMPTransaction<'a>>,
47 /// tx counter for assigning incrementing id's to tx's
51 pub struct SNMPPduInfo<'a> {
52 pub pdu_type: PduType,
56 pub trap_type: Option<(TrapType,Oid<'a>,NetworkAddress)>,
58 pub vars: Vec<Oid<'a>>,
61 pub struct SNMPTransaction<'a> {
65 /// PDU info, if present (and cleartext)
66 pub info: Option<SNMPPduInfo<'a>>,
68 /// Community, if present (SNMPv2)
69 pub community: Option<String>,
71 /// USM info, if present (SNMPv3)
72 pub usm: Option<String>,
74 /// True if transaction was encrypted
77 /// The internal transaction id
80 tx_data: applayer::AppLayerTxData,
83 impl<'a> Transaction for SNMPTransaction<'a> {
89 impl<'a> SNMPState<'a> {
90 pub fn new() -> SNMPState<'a> {
93 transactions: Vec::new(),
99 impl<'a> Default for SNMPPduInfo<'a> {
100 fn default() -> SNMPPduInfo<'a> {
102 pdu_type: PduType(0),
103 err: ErrorStatus::NoError,
110 impl<'a> State<SNMPTransaction<'a>> for SNMPState<'a> {
111 fn get_transactions(&self) -> &[SNMPTransaction<'a>] {
116 impl<'a> SNMPState<'a> {
117 fn add_pdu_info(&mut self, pdu: &SnmpPdu<'a>, tx: &mut SNMPTransaction<'a>) {
118 let mut pdu_info = SNMPPduInfo::default();
119 pdu_info.pdu_type = pdu.pdu_type();
121 SnmpPdu::Generic(ref pdu) => {
122 pdu_info.err = pdu.err;
124 SnmpPdu::Bulk(_) => {
126 SnmpPdu::TrapV1(ref t) => {
127 pdu_info.trap_type = Some((t.generic_trap,t.enterprise.clone(),t.agent_addr));
131 for var in pdu.vars_iter() {
132 pdu_info.vars.push(var.oid.to_owned());
134 tx.info = Some(pdu_info);
137 fn handle_snmp_v12(&mut self, msg: SnmpMessage<'a>, _direction: Direction) -> i32 {
138 let mut tx = self.new_tx();
139 // in the message, version is encoded as 0 (version 1) or 1 (version 2)
140 if self.version != msg.version + 1 {
141 SCLogDebug!("SNMP version mismatch: expected {}, received {}", self.version, msg.version+1);
142 self.set_event_tx(&mut tx, SNMPEvent::VersionMismatch);
144 self.add_pdu_info(&msg.pdu, &mut tx);
145 tx.community = Some(msg.community);
146 self.transactions.push(tx);
150 fn handle_snmp_v3(&mut self, msg: SnmpV3Message<'a>, _direction: Direction) -> i32 {
151 let mut tx = self.new_tx();
152 if self.version != msg.version {
153 SCLogDebug!("SNMP version mismatch: expected {}, received {}", self.version, msg.version);
154 self.set_event_tx(&mut tx, SNMPEvent::VersionMismatch);
157 ScopedPduData::Plaintext(pdu) => {
158 self.add_pdu_info(&pdu.data, &mut tx);
164 match msg.security_params {
165 SecurityParameters::USM(usm) => {
166 tx.usm = Some(usm.msg_user_name);
169 self.set_event_tx(&mut tx, SNMPEvent::UnknownSecurityModel);
172 self.transactions.push(tx);
176 /// Parse an SNMP request message
178 /// Returns 0 if successful, or -1 on error
179 fn parse(&mut self, i: &'a [u8], direction: Direction) -> i32 {
180 if self.version == 0 {
181 match parse_pdu_enveloppe_version(i) {
182 Ok((_,x)) => self.version = x,
186 match parse_snmp_generic_message(i) {
187 Ok((_rem,SnmpGenericMessage::V1(msg))) |
188 Ok((_rem,SnmpGenericMessage::V2(msg))) => self.handle_snmp_v12(msg, direction),
189 Ok((_rem,SnmpGenericMessage::V3(msg))) => self.handle_snmp_v3(msg, direction),
191 SCLogDebug!("parse_snmp failed: {:?}", _e);
192 self.set_event(SNMPEvent::MalformedData);
199 // All transactions are freed when the `transactions` object is freed.
200 // But let's be explicit
201 self.transactions.clear();
204 fn new_tx(&mut self) -> SNMPTransaction<'a> {
206 SNMPTransaction::new(self.version, self.tx_id)
209 fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SNMPTransaction> {
210 self.transactions.iter().rev().find(|&tx| tx.id == tx_id + 1)
213 fn free_tx(&mut self, tx_id: u64) {
214 let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1);
215 debug_assert!(tx != None);
216 if let Some(idx) = tx {
217 let _ = self.transactions.remove(idx);
221 /// Set an event. The event is set on the most recent transaction.
222 fn set_event(&mut self, event: SNMPEvent) {
223 if let Some(tx) = self.transactions.last_mut() {
224 tx.tx_data.set_event(event as u8);
228 /// Set an event on a specific transaction.
229 fn set_event_tx(&self, tx: &mut SNMPTransaction, event: SNMPEvent) {
230 tx.tx_data.set_event(event as u8);
234 impl<'a> SNMPTransaction<'a> {
235 pub fn new(version: u32, id: u64) -> SNMPTransaction<'a> {
243 tx_data: applayer::AppLayerTxData::new(),
248 /// Returns *mut SNMPState
250 pub extern "C" fn rs_snmp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void {
251 let state = SNMPState::new();
252 let boxed = Box::new(state);
253 return Box::into_raw(boxed) as *mut _;
257 /// - state: *mut SNMPState as void pointer
259 pub extern "C" fn rs_snmp_state_free(state: *mut std::os::raw::c_void) {
260 let mut snmp_state = unsafe{ Box::from_raw(state as *mut SNMPState) };
265 pub unsafe extern "C" fn rs_snmp_parse_request(_flow: *const core::Flow,
266 state: *mut std::os::raw::c_void,
267 _pstate: *mut std::os::raw::c_void,
270 _data: *const std::os::raw::c_void,
271 _flags: u8) -> AppLayerResult {
272 let buf = build_slice!(input,input_len as usize);
273 let state = cast_pointer!(state,SNMPState);
274 state.parse(buf, Direction::ToServer).into()
278 pub unsafe extern "C" fn rs_snmp_parse_response(_flow: *const core::Flow,
279 state: *mut std::os::raw::c_void,
280 _pstate: *mut std::os::raw::c_void,
283 _data: *const std::os::raw::c_void,
284 _flags: u8) -> AppLayerResult {
285 let buf = build_slice!(input,input_len as usize);
286 let state = cast_pointer!(state,SNMPState);
287 state.parse(buf, Direction::ToClient).into()
291 pub unsafe extern "C" fn rs_snmp_state_get_tx(state: *mut std::os::raw::c_void,
293 -> *mut std::os::raw::c_void
295 let state = cast_pointer!(state,SNMPState);
296 match state.get_tx_by_id(tx_id) {
297 Some(tx) => tx as *const _ as *mut _,
298 None => std::ptr::null_mut(),
303 pub unsafe extern "C" fn rs_snmp_state_get_tx_count(state: *mut std::os::raw::c_void)
306 let state = cast_pointer!(state,SNMPState);
311 pub unsafe extern "C" fn rs_snmp_state_tx_free(state: *mut std::os::raw::c_void,
314 let state = cast_pointer!(state,SNMPState);
315 state.free_tx(tx_id);
319 pub extern "C" fn rs_snmp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void,
321 -> std::os::raw::c_int
326 static mut ALPROTO_SNMP : AppProto = ALPROTO_UNKNOWN;
328 // Read PDU sequence and extract version, if similar to SNMP definition
329 fn parse_pdu_enveloppe_version(i:&[u8]) -> IResult<&[u8],u32> {
330 match parse_der_sequence(i) {
333 BerObjectContent::Sequence(ref v) => {
335 match v[0].as_u32() {
336 Ok(0) => { return Ok((i,1)); }, // possibly SNMPv1
337 Ok(1) => { return Ok((i,2)); }, // possibly SNMPv2c
340 } else if v.len() == 4 && v[0].as_u32() == Ok(3) {
341 return Ok((i,3)); // possibly SNMPv3
346 Err(nom::Err::Error(error_position!(i, ErrorKind::Verify)))
348 Err(nom::Err::Incomplete(i)) => Err(nom::Err::Incomplete(i)),
349 Err(nom::Err::Failure(_)) |
350 Err(nom::Err::Error(_)) => Err(nom::Err::Error(error_position!(i,ErrorKind::Verify)))
355 pub unsafe extern "C" fn rs_snmp_probing_parser(_flow: *const Flow,
359 _rdir: *mut u8) -> AppProto {
360 let slice = build_slice!(input,input_len as usize);
361 let alproto = ALPROTO_SNMP;
362 if slice.len() < 4 { return ALPROTO_FAILED; }
363 match parse_pdu_enveloppe_version(slice) {
364 Ok((_,_)) => alproto,
365 Err(nom::Err::Incomplete(_)) => ALPROTO_UNKNOWN,
370 export_tx_data_get!(rs_snmp_get_tx_data, SNMPTransaction);
372 const PARSER_NAME : &'static [u8] = b"snmp\0";
375 pub unsafe extern "C" fn rs_register_snmp_parser() {
376 let default_port = CString::new("161").unwrap();
377 let mut parser = RustParser {
378 name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
379 default_port : default_port.as_ptr(),
380 ipproto : core::IPPROTO_UDP,
381 probe_ts : Some(rs_snmp_probing_parser),
382 probe_tc : Some(rs_snmp_probing_parser),
385 state_new : rs_snmp_state_new,
386 state_free : rs_snmp_state_free,
387 tx_free : rs_snmp_state_tx_free,
388 parse_ts : rs_snmp_parse_request,
389 parse_tc : rs_snmp_parse_response,
390 get_tx_count : rs_snmp_state_get_tx_count,
391 get_tx : rs_snmp_state_get_tx,
394 tx_get_progress : rs_snmp_tx_get_alstate_progress,
395 get_eventinfo : Some(SNMPEvent::get_event_info),
396 get_eventinfo_byid : Some(SNMPEvent::get_event_info_by_id),
397 localstorage_new : None,
398 localstorage_free : None,
400 get_tx_iterator : Some(applayer::state_get_tx_iterator::<SNMPState, SNMPTransaction>),
401 get_tx_data : rs_snmp_get_tx_data,
402 apply_tx_config : None,
403 flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
406 let ip_proto_str = CString::new("udp").unwrap();
407 if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
409 let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
410 // store the allocated ID for the probe function
411 ALPROTO_SNMP = alproto;
412 if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
413 let _ = AppLayerRegisterParser(&parser, alproto);
416 let default_port_traps = CString::new("162").unwrap();
417 parser.default_port = default_port_traps.as_ptr();
418 let _ = AppLayerRegisterProtocolDetection(&parser, 1);
419 if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
420 let _ = AppLayerRegisterParser(&parser, alproto);
423 SCLogDebug!("Protocol detector and parser disabled for SNMP.");