1 /* Copyright (C) 2018-2020 Open Information Security Foundation
2 *
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
5 * Software Foundation.
6 *
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.
11 *
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
15 * 02110-1301, USA.
16 */
17
18 use crate::applayer::{self, *};
19 use crate::core;
20 use crate::core::{ALPROTO_UNKNOWN, AppProto, Flow, IPPROTO_UDP};
21 use crate::core::{sc_detect_engine_state_free, sc_app_layer_decoder_events_free_events};
22 use crate::dhcp::parser::*;
23 use std;
24 use std::ffi::{CStr,CString};
25 use std::mem::transmute;
26
27 static mut ALPROTO_DHCP: AppProto = ALPROTO_UNKNOWN;
28
29 static DHCP_MIN_FRAME_LEN: u32 = 232;
30
31 pub const BOOTP_REQUEST: u8 = 1;
32 pub const BOOTP_REPLY: u8 = 2;
33
34 // DHCP option types. Names based on IANA naming:
35 // https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xhtml
36 pub const DHCP_OPT_SUBNET_MASK: u8 = 1;
37 pub const DHCP_OPT_ROUTERS: u8 = 3;
38 pub const DHCP_OPT_DNS_SERVER: u8 = 6;
39 pub const DHCP_OPT_HOSTNAME: u8 = 12;
40 pub const DHCP_OPT_REQUESTED_IP: u8 = 50;
41 pub const DHCP_OPT_ADDRESS_TIME: u8 = 51;
42 pub const DHCP_OPT_TYPE: u8 = 53;
43 pub const DHCP_OPT_SERVER_ID: u8 = 54;
44 pub const DHCP_OPT_PARAMETER_LIST: u8 = 55;
45 pub const DHCP_OPT_RENEWAL_TIME: u8 = 58;
46 pub const DHCP_OPT_REBINDING_TIME: u8 = 59;
47 pub const DHCP_OPT_CLIENT_ID: u8 = 61;
48 pub const DHCP_OPT_END: u8 = 255;
49
50 /// DHCP message types.
51 pub const DHCP_TYPE_DISCOVER: u8 = 1;
52 pub const DHCP_TYPE_OFFER: u8 = 2;
53 pub const DHCP_TYPE_REQUEST: u8 = 3;
54 pub const DHCP_TYPE_DECLINE: u8 = 4;
55 pub const DHCP_TYPE_ACK: u8 = 5;
56 pub const DHCP_TYPE_NAK: u8 = 6;
57 pub const DHCP_TYPE_RELEASE: u8 = 7;
58 pub const DHCP_TYPE_INFORM: u8 = 8;
59
60 /// DHCP parameter types.
61 /// https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.txt
62 pub const DHCP_PARAM_SUBNET_MASK: u8 = 1;
63 pub const DHCP_PARAM_ROUTER: u8 = 3;
64 pub const DHCP_PARAM_DNS_SERVER: u8 = 6;
65 pub const DHCP_PARAM_DOMAIN: u8 = 15;
66 pub const DHCP_PARAM_ARP_TIMEOUT: u8 = 35;
67 pub const DHCP_PARAM_NTP_SERVER: u8 = 42;
68 pub const DHCP_PARAM_TFTP_SERVER_NAME: u8 = 66;
69 pub const DHCP_PARAM_TFTP_SERVER_IP: u8 = 150;
70
71 #[repr(u32)]
72 pub enum DHCPEvent {
73 TruncatedOptions = 0,
74 MalformedOptions,
75 }
76
77 impl DHCPEvent {
from_i32(value: i32) -> Option<DHCPEvent>78 fn from_i32(value: i32) -> Option<DHCPEvent> {
79 match value {
80 0 => Some(DHCPEvent::TruncatedOptions),
81 1 => Some(DHCPEvent::MalformedOptions),
82 _ => None,
83 }
84 }
85 }
86
87 /// The concept of a transaction is more to satisfy the Suricata
88 /// app-layer. This DHCP parser is actually stateless where each
89 /// message is its own transaction.
90 pub struct DHCPTransaction {
91 tx_id: u64,
92 pub message: DHCPMessage,
93 de_state: Option<*mut core::DetectEngineState>,
94 events: *mut core::AppLayerDecoderEvents,
95 tx_data: applayer::AppLayerTxData,
96 }
97
98 impl DHCPTransaction {
new(id: u64, message: DHCPMessage) -> DHCPTransaction99 pub fn new(id: u64, message: DHCPMessage) -> DHCPTransaction {
100 DHCPTransaction {
101 tx_id: id,
102 message: message,
103 de_state: None,
104 events: std::ptr::null_mut(),
105 tx_data: applayer::AppLayerTxData::new(),
106 }
107 }
108
free(&mut self)109 pub fn free(&mut self) {
110 if self.events != std::ptr::null_mut() {
111 sc_app_layer_decoder_events_free_events(&mut self.events);
112 }
113 match self.de_state {
114 Some(state) => {
115 sc_detect_engine_state_free(state);
116 }
117 _ => {}
118 }
119 }
120
121 }
122
123 impl Drop for DHCPTransaction {
drop(&mut self)124 fn drop(&mut self) {
125 self.free();
126 }
127 }
128
129 export_tx_get_detect_state!(rs_dhcp_tx_get_detect_state, DHCPTransaction);
130 export_tx_set_detect_state!(rs_dhcp_tx_set_detect_state, DHCPTransaction);
131
132 pub struct DHCPState {
133 // Internal transaction ID.
134 tx_id: u64,
135
136 // List of transactions.
137 transactions: Vec<DHCPTransaction>,
138
139 events: u16,
140 }
141
142 impl DHCPState {
new() -> DHCPState143 pub fn new() -> DHCPState {
144 return DHCPState {
145 tx_id: 0,
146 transactions: Vec::new(),
147 events: 0,
148 };
149 }
150
parse(&mut self, input: &[u8]) -> bool151 pub fn parse(&mut self, input: &[u8]) -> bool {
152 match dhcp_parse(input) {
153 Ok((_, message)) => {
154 let malformed_options = message.malformed_options;
155 let truncated_options = message.truncated_options;
156 self.tx_id += 1;
157 let transaction = DHCPTransaction::new(self.tx_id, message);
158 self.transactions.push(transaction);
159 if malformed_options {
160 self.set_event(DHCPEvent::MalformedOptions);
161 }
162 if truncated_options {
163 self.set_event(DHCPEvent::TruncatedOptions);
164 }
165 return true;
166 }
167 _ => {
168 return false;
169 }
170 }
171 }
172
get_tx(&mut self, tx_id: u64) -> Option<&DHCPTransaction>173 pub fn get_tx(&mut self, tx_id: u64) -> Option<&DHCPTransaction> {
174 for tx in &mut self.transactions {
175 if tx.tx_id == tx_id + 1 {
176 return Some(tx);
177 }
178 }
179 return None;
180 }
181
free_tx(&mut self, tx_id: u64)182 fn free_tx(&mut self, tx_id: u64) {
183 let len = self.transactions.len();
184 let mut found = false;
185 let mut index = 0;
186 for i in 0..len {
187 let tx = &self.transactions[i];
188 if tx.tx_id == tx_id + 1 {
189 found = true;
190 index = i;
191 break;
192 }
193 }
194 if found {
195 self.transactions.remove(index);
196 }
197 }
198
set_event(&mut self, event: DHCPEvent)199 fn set_event(&mut self, event: DHCPEvent) {
200 if let Some(tx) = self.transactions.last_mut() {
201 core::sc_app_layer_decoder_events_set_event_raw(
202 &mut tx.events, event as u8);
203 self.events += 1;
204 }
205 }
206
get_tx_iterator(&mut self, min_tx_id: u64, state: &mut u64) -> Option<(&DHCPTransaction, u64, bool)>207 fn get_tx_iterator(&mut self, min_tx_id: u64, state: &mut u64) ->
208 Option<(&DHCPTransaction, u64, bool)>
209 {
210 let mut index = *state as usize;
211 let len = self.transactions.len();
212
213 while index < len {
214 let tx = &self.transactions[index];
215 if tx.tx_id < min_tx_id + 1 {
216 index += 1;
217 continue;
218 }
219 *state = index as u64;
220 return Some((tx, tx.tx_id - 1, (len - index) > 1));
221 }
222
223 return None;
224 }
225 }
226
227 #[no_mangle]
rs_dhcp_probing_parser(_flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8) -> AppProto228 pub extern "C" fn rs_dhcp_probing_parser(_flow: *const Flow,
229 _direction: u8,
230 input: *const u8,
231 input_len: u32,
232 _rdir: *mut u8) -> AppProto
233 {
234 if input_len < DHCP_MIN_FRAME_LEN {
235 return ALPROTO_UNKNOWN;
236 }
237
238 let slice = build_slice!(input, input_len as usize);
239 match parse_header(slice) {
240 Ok((_, _)) => {
241 return unsafe { ALPROTO_DHCP };
242 }
243 _ => {
244 return ALPROTO_UNKNOWN;
245 }
246 }
247 }
248
249 #[no_mangle]
rs_dhcp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void, _direction: u8) -> std::os::raw::c_int250 pub extern "C" fn rs_dhcp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void,
251 _direction: u8) -> std::os::raw::c_int {
252 // As this is a stateless parser, simply use 1.
253 return 1;
254 }
255
256 #[no_mangle]
rs_dhcp_state_progress_completion_status( _direction: u8) -> std::os::raw::c_int257 pub extern "C" fn rs_dhcp_state_progress_completion_status(
258 _direction: u8) -> std::os::raw::c_int {
259 // The presence of a transaction means we are complete.
260 return 1;
261 }
262
263 #[no_mangle]
rs_dhcp_state_get_tx(state: *mut std::os::raw::c_void, tx_id: u64) -> *mut std::os::raw::c_void264 pub extern "C" fn rs_dhcp_state_get_tx(state: *mut std::os::raw::c_void,
265 tx_id: u64) -> *mut std::os::raw::c_void {
266 let state = cast_pointer!(state, DHCPState);
267 match state.get_tx(tx_id) {
268 Some(tx) => {
269 return unsafe { transmute(tx) };
270 }
271 None => {
272 return std::ptr::null_mut();
273 }
274 }
275 }
276
277 #[no_mangle]
rs_dhcp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64278 pub extern "C" fn rs_dhcp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
279 let state = cast_pointer!(state, DHCPState);
280 return state.tx_id;
281 }
282
283 #[no_mangle]
rs_dhcp_parse(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8) -> AppLayerResult284 pub extern "C" fn rs_dhcp_parse(_flow: *const core::Flow,
285 state: *mut std::os::raw::c_void,
286 _pstate: *mut std::os::raw::c_void,
287 input: *const u8,
288 input_len: u32,
289 _data: *const std::os::raw::c_void,
290 _flags: u8) -> AppLayerResult {
291 let state = cast_pointer!(state, DHCPState);
292 let buf = build_slice!(input, input_len as usize);
293 if state.parse(buf) {
294 return AppLayerResult::ok();
295 }
296 return AppLayerResult::err();
297 }
298
299 #[no_mangle]
rs_dhcp_state_tx_free( state: *mut std::os::raw::c_void, tx_id: u64)300 pub extern "C" fn rs_dhcp_state_tx_free(
301 state: *mut std::os::raw::c_void,
302 tx_id: u64)
303 {
304 let state = cast_pointer!(state, DHCPState);
305 state.free_tx(tx_id);
306 }
307
308 #[no_mangle]
rs_dhcp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void309 pub extern "C" fn rs_dhcp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void {
310 let state = DHCPState::new();
311 let boxed = Box::new(state);
312 return unsafe {
313 transmute(boxed)
314 };
315 }
316
317 #[no_mangle]
rs_dhcp_state_free(state: *mut std::os::raw::c_void)318 pub extern "C" fn rs_dhcp_state_free(state: *mut std::os::raw::c_void) {
319 // Just unbox...
320 let _drop: Box<DHCPState> = unsafe { transmute(state) };
321 }
322
323 #[no_mangle]
rs_dhcp_state_get_event_info_by_id(event_id: std::os::raw::c_int, event_name: *mut *const std::os::raw::c_char, event_type: *mut core::AppLayerEventType) -> i8324 pub extern "C" fn rs_dhcp_state_get_event_info_by_id(event_id: std::os::raw::c_int,
325 event_name: *mut *const std::os::raw::c_char,
326 event_type: *mut core::AppLayerEventType)
327 -> i8
328 {
329 if let Some(e) = DHCPEvent::from_i32(event_id as i32) {
330 let estr = match e {
331 DHCPEvent::TruncatedOptions => { "truncated_options\0" },
332 DHCPEvent::MalformedOptions => { "malformed_options\0" },
333 };
334 unsafe{
335 *event_name = estr.as_ptr() as *const std::os::raw::c_char;
336 *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION;
337 };
338 0
339 } else {
340 -1
341 }
342 }
343 #[no_mangle]
rs_dhcp_state_get_events(tx: *mut std::os::raw::c_void) -> *mut core::AppLayerDecoderEvents344 pub extern "C" fn rs_dhcp_state_get_events(tx: *mut std::os::raw::c_void)
345 -> *mut core::AppLayerDecoderEvents
346 {
347 let tx = cast_pointer!(tx, DHCPTransaction);
348 return tx.events;
349 }
350
351 #[no_mangle]
rs_dhcp_state_get_event_info( event_name: *const std::os::raw::c_char, event_id: *mut std::os::raw::c_int, event_type: *mut core::AppLayerEventType) -> std::os::raw::c_int352 pub extern "C" fn rs_dhcp_state_get_event_info(
353 event_name: *const std::os::raw::c_char,
354 event_id: *mut std::os::raw::c_int,
355 event_type: *mut core::AppLayerEventType)
356 -> std::os::raw::c_int
357 {
358 if event_name == std::ptr::null() {
359 return -1;
360 }
361 let c_event_name: &CStr = unsafe { CStr::from_ptr(event_name) };
362 let event = match c_event_name.to_str() {
363 Ok(s) => {
364 match s {
365 "malformed_options" => DHCPEvent::MalformedOptions as i32,
366 "truncated_options" => DHCPEvent::TruncatedOptions as i32,
367 _ => -1, // unknown event
368 }
369 },
370 Err(_) => -1, // UTF-8 conversion failed
371 };
372 unsafe{
373 *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION;
374 *event_id = event as std::os::raw::c_int;
375 };
376 0
377 }
378
379 #[no_mangle]
rs_dhcp_state_get_tx_iterator( _ipproto: u8, _alproto: AppProto, state: *mut std::os::raw::c_void, min_tx_id: u64, _max_tx_id: u64, istate: &mut u64) -> applayer::AppLayerGetTxIterTuple380 pub extern "C" fn rs_dhcp_state_get_tx_iterator(
381 _ipproto: u8,
382 _alproto: AppProto,
383 state: *mut std::os::raw::c_void,
384 min_tx_id: u64,
385 _max_tx_id: u64,
386 istate: &mut u64)
387 -> applayer::AppLayerGetTxIterTuple
388 {
389 let state = cast_pointer!(state, DHCPState);
390 match state.get_tx_iterator(min_tx_id, istate) {
391 Some((tx, out_tx_id, has_next)) => {
392 let c_tx = unsafe { transmute(tx) };
393 let ires = applayer::AppLayerGetTxIterTuple::with_values(
394 c_tx, out_tx_id, has_next);
395 return ires;
396 }
397 None => {
398 return applayer::AppLayerGetTxIterTuple::not_found();
399 }
400 }
401 }
402
403 export_tx_data_get!(rs_dhcp_get_tx_data, DHCPTransaction);
404
405 const PARSER_NAME: &'static [u8] = b"dhcp\0";
406
407 #[no_mangle]
rs_dhcp_register_parser()408 pub unsafe extern "C" fn rs_dhcp_register_parser() {
409 SCLogDebug!("Registering DHCP parser.");
410 let ports = CString::new("[67,68]").unwrap();
411 let parser = RustParser {
412 name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
413 default_port : ports.as_ptr(),
414 ipproto : IPPROTO_UDP,
415 probe_ts : Some(rs_dhcp_probing_parser),
416 probe_tc : Some(rs_dhcp_probing_parser),
417 min_depth : 0,
418 max_depth : 16,
419 state_new : rs_dhcp_state_new,
420 state_free : rs_dhcp_state_free,
421 tx_free : rs_dhcp_state_tx_free,
422 parse_ts : rs_dhcp_parse,
423 parse_tc : rs_dhcp_parse,
424 get_tx_count : rs_dhcp_state_get_tx_count,
425 get_tx : rs_dhcp_state_get_tx,
426 tx_get_comp_st : rs_dhcp_state_progress_completion_status,
427 tx_get_progress : rs_dhcp_tx_get_alstate_progress,
428 get_de_state : rs_dhcp_tx_get_detect_state,
429 set_de_state : rs_dhcp_tx_set_detect_state,
430 get_events : Some(rs_dhcp_state_get_events),
431 get_eventinfo : Some(rs_dhcp_state_get_event_info),
432 get_eventinfo_byid : None,
433 localstorage_new : None,
434 localstorage_free : None,
435 get_files : None,
436 get_tx_iterator : Some(rs_dhcp_state_get_tx_iterator),
437 get_tx_data : rs_dhcp_get_tx_data,
438 apply_tx_config : None,
439 flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
440 truncate : None,
441 };
442
443 let ip_proto_str = CString::new("udp").unwrap();
444
445 if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
446 let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
447 ALPROTO_DHCP = alproto;
448 if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
449 let _ = AppLayerRegisterParser(&parser, alproto);
450 }
451 } else {
452 SCLogDebug!("Protocol detector and parser disabled for DHCP.");
453 }
454 }
455