]> git.ipfire.org Git - people/ms/suricata.git/blob - rust/src/dhcp/dhcp.rs
8748b4600b2f4b4ac748ae4e765ec5cd38c9958e
[people/ms/suricata.git] / rust / src / dhcp / dhcp.rs
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::CString;
25
26 static mut ALPROTO_DHCP: AppProto = ALPROTO_UNKNOWN;
27
28 static DHCP_MIN_FRAME_LEN: u32 = 232;
29
30 pub const BOOTP_REQUEST: u8 = 1;
31 pub const BOOTP_REPLY: u8 = 2;
32
33 // DHCP option types. Names based on IANA naming:
34 // https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xhtml
35 pub const DHCP_OPT_SUBNET_MASK: u8 = 1;
36 pub const DHCP_OPT_ROUTERS: u8 = 3;
37 pub const DHCP_OPT_DNS_SERVER: u8 = 6;
38 pub const DHCP_OPT_HOSTNAME: u8 = 12;
39 pub const DHCP_OPT_REQUESTED_IP: u8 = 50;
40 pub const DHCP_OPT_ADDRESS_TIME: u8 = 51;
41 pub const DHCP_OPT_TYPE: u8 = 53;
42 pub const DHCP_OPT_SERVER_ID: u8 = 54;
43 pub const DHCP_OPT_PARAMETER_LIST: u8 = 55;
44 pub const DHCP_OPT_RENEWAL_TIME: u8 = 58;
45 pub const DHCP_OPT_REBINDING_TIME: u8 = 59;
46 pub const DHCP_OPT_CLIENT_ID: u8 = 61;
47 pub const DHCP_OPT_END: u8 = 255;
48
49 /// DHCP message types.
50 pub const DHCP_TYPE_DISCOVER: u8 = 1;
51 pub const DHCP_TYPE_OFFER: u8 = 2;
52 pub const DHCP_TYPE_REQUEST: u8 = 3;
53 pub const DHCP_TYPE_DECLINE: u8 = 4;
54 pub const DHCP_TYPE_ACK: u8 = 5;
55 pub const DHCP_TYPE_NAK: u8 = 6;
56 pub const DHCP_TYPE_RELEASE: u8 = 7;
57 pub const DHCP_TYPE_INFORM: u8 = 8;
58
59 /// DHCP parameter types.
60 /// https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.txt
61 pub const DHCP_PARAM_SUBNET_MASK: u8 = 1;
62 pub const DHCP_PARAM_ROUTER: u8 = 3;
63 pub const DHCP_PARAM_DNS_SERVER: u8 = 6;
64 pub const DHCP_PARAM_DOMAIN: u8 = 15;
65 pub const DHCP_PARAM_ARP_TIMEOUT: u8 = 35;
66 pub const DHCP_PARAM_NTP_SERVER: u8 = 42;
67 pub const DHCP_PARAM_TFTP_SERVER_NAME: u8 = 66;
68 pub const DHCP_PARAM_TFTP_SERVER_IP: u8 = 150;
69
70 #[derive(AppLayerEvent)]
71 pub enum DHCPEvent {
72 TruncatedOptions,
73 MalformedOptions,
74 }
75
76 /// The concept of a transaction is more to satisfy the Suricata
77 /// app-layer. This DHCP parser is actually stateless where each
78 /// message is its own transaction.
79 pub struct DHCPTransaction {
80 tx_id: u64,
81 pub message: DHCPMessage,
82 de_state: Option<*mut core::DetectEngineState>,
83 events: *mut core::AppLayerDecoderEvents,
84 tx_data: applayer::AppLayerTxData,
85 }
86
87 impl DHCPTransaction {
88 pub fn new(id: u64, message: DHCPMessage) -> DHCPTransaction {
89 DHCPTransaction {
90 tx_id: id,
91 message: message,
92 de_state: None,
93 events: std::ptr::null_mut(),
94 tx_data: applayer::AppLayerTxData::new(),
95 }
96 }
97
98 pub fn free(&mut self) {
99 if !self.events.is_null() {
100 sc_app_layer_decoder_events_free_events(&mut self.events);
101 }
102 match self.de_state {
103 Some(state) => {
104 sc_detect_engine_state_free(state);
105 }
106 _ => {}
107 }
108 }
109
110 }
111
112 impl Drop for DHCPTransaction {
113 fn drop(&mut self) {
114 self.free();
115 }
116 }
117
118 export_tx_get_detect_state!(rs_dhcp_tx_get_detect_state, DHCPTransaction);
119 export_tx_set_detect_state!(rs_dhcp_tx_set_detect_state, DHCPTransaction);
120
121 #[derive(Default)]
122 pub struct DHCPState {
123 // Internal transaction ID.
124 tx_id: u64,
125
126 // List of transactions.
127 transactions: Vec<DHCPTransaction>,
128
129 events: u16,
130 }
131
132 impl DHCPState {
133 pub fn new() -> Self {
134 Default::default()
135 }
136
137 pub fn parse(&mut self, input: &[u8]) -> bool {
138 match dhcp_parse(input) {
139 Ok((_, message)) => {
140 let malformed_options = message.malformed_options;
141 let truncated_options = message.truncated_options;
142 self.tx_id += 1;
143 let transaction = DHCPTransaction::new(self.tx_id, message);
144 self.transactions.push(transaction);
145 if malformed_options {
146 self.set_event(DHCPEvent::MalformedOptions);
147 }
148 if truncated_options {
149 self.set_event(DHCPEvent::TruncatedOptions);
150 }
151 return true;
152 }
153 _ => {
154 return false;
155 }
156 }
157 }
158
159 pub fn get_tx(&mut self, tx_id: u64) -> Option<&DHCPTransaction> {
160 for tx in &mut self.transactions {
161 if tx.tx_id == tx_id + 1 {
162 return Some(tx);
163 }
164 }
165 return None;
166 }
167
168 fn free_tx(&mut self, tx_id: u64) {
169 let len = self.transactions.len();
170 let mut found = false;
171 let mut index = 0;
172 for i in 0..len {
173 let tx = &self.transactions[i];
174 if tx.tx_id == tx_id + 1 {
175 found = true;
176 index = i;
177 break;
178 }
179 }
180 if found {
181 self.transactions.remove(index);
182 }
183 }
184
185 fn set_event(&mut self, event: DHCPEvent) {
186 if let Some(tx) = self.transactions.last_mut() {
187 core::sc_app_layer_decoder_events_set_event_raw(
188 &mut tx.events, event as u8);
189 self.events += 1;
190 }
191 }
192
193 fn get_tx_iterator(&mut self, min_tx_id: u64, state: &mut u64) ->
194 Option<(&DHCPTransaction, u64, bool)>
195 {
196 let mut index = *state as usize;
197 let len = self.transactions.len();
198
199 while index < len {
200 let tx = &self.transactions[index];
201 if tx.tx_id < min_tx_id + 1 {
202 index += 1;
203 continue;
204 }
205 *state = index as u64;
206 return Some((tx, tx.tx_id - 1, (len - index) > 1));
207 }
208
209 return None;
210 }
211 }
212
213 #[no_mangle]
214 pub unsafe extern "C" fn rs_dhcp_probing_parser(_flow: *const Flow,
215 _direction: u8,
216 input: *const u8,
217 input_len: u32,
218 _rdir: *mut u8) -> AppProto
219 {
220 if input_len < DHCP_MIN_FRAME_LEN {
221 return ALPROTO_UNKNOWN;
222 }
223
224 let slice = build_slice!(input, input_len as usize);
225 match parse_header(slice) {
226 Ok((_, _)) => {
227 return ALPROTO_DHCP;
228 }
229 _ => {
230 return ALPROTO_UNKNOWN;
231 }
232 }
233 }
234
235 #[no_mangle]
236 pub extern "C" fn rs_dhcp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void,
237 _direction: u8) -> std::os::raw::c_int {
238 // As this is a stateless parser, simply use 1.
239 return 1;
240 }
241
242 #[no_mangle]
243 pub unsafe extern "C" fn rs_dhcp_state_get_tx(state: *mut std::os::raw::c_void,
244 tx_id: u64) -> *mut std::os::raw::c_void {
245 let state = cast_pointer!(state, DHCPState);
246 match state.get_tx(tx_id) {
247 Some(tx) => {
248 return tx as *const _ as *mut _;
249 }
250 None => {
251 return std::ptr::null_mut();
252 }
253 }
254 }
255
256 #[no_mangle]
257 pub unsafe extern "C" fn rs_dhcp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
258 let state = cast_pointer!(state, DHCPState);
259 return state.tx_id;
260 }
261
262 #[no_mangle]
263 pub unsafe extern "C" fn rs_dhcp_parse(_flow: *const core::Flow,
264 state: *mut std::os::raw::c_void,
265 _pstate: *mut std::os::raw::c_void,
266 input: *const u8,
267 input_len: u32,
268 _data: *const std::os::raw::c_void,
269 _flags: u8) -> AppLayerResult {
270 let state = cast_pointer!(state, DHCPState);
271 let buf = build_slice!(input, input_len as usize);
272 if state.parse(buf) {
273 return AppLayerResult::ok();
274 }
275 return AppLayerResult::err();
276 }
277
278 #[no_mangle]
279 pub unsafe extern "C" fn rs_dhcp_state_tx_free(
280 state: *mut std::os::raw::c_void,
281 tx_id: u64)
282 {
283 let state = cast_pointer!(state, DHCPState);
284 state.free_tx(tx_id);
285 }
286
287 #[no_mangle]
288 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 {
289 let state = DHCPState::new();
290 let boxed = Box::new(state);
291 return Box::into_raw(boxed) as *mut _;
292 }
293
294 #[no_mangle]
295 pub unsafe extern "C" fn rs_dhcp_state_free(state: *mut std::os::raw::c_void) {
296 std::mem::drop(Box::from_raw(state as *mut DHCPState));
297 }
298
299 #[no_mangle]
300 pub unsafe extern "C" fn rs_dhcp_state_get_events(tx: *mut std::os::raw::c_void)
301 -> *mut core::AppLayerDecoderEvents
302 {
303 let tx = cast_pointer!(tx, DHCPTransaction);
304 return tx.events;
305 }
306
307 #[no_mangle]
308 pub unsafe extern "C" fn rs_dhcp_state_get_tx_iterator(
309 _ipproto: u8,
310 _alproto: AppProto,
311 state: *mut std::os::raw::c_void,
312 min_tx_id: u64,
313 _max_tx_id: u64,
314 istate: &mut u64)
315 -> applayer::AppLayerGetTxIterTuple
316 {
317 let state = cast_pointer!(state, DHCPState);
318 match state.get_tx_iterator(min_tx_id, istate) {
319 Some((tx, out_tx_id, has_next)) => {
320 let c_tx = tx as *const _ as *mut _;
321 let ires = applayer::AppLayerGetTxIterTuple::with_values(
322 c_tx, out_tx_id, has_next);
323 return ires;
324 }
325 None => {
326 return applayer::AppLayerGetTxIterTuple::not_found();
327 }
328 }
329 }
330
331 export_tx_data_get!(rs_dhcp_get_tx_data, DHCPTransaction);
332
333 const PARSER_NAME: &'static [u8] = b"dhcp\0";
334
335 #[no_mangle]
336 pub unsafe extern "C" fn rs_dhcp_register_parser() {
337 SCLogDebug!("Registering DHCP parser.");
338 let ports = CString::new("[67,68]").unwrap();
339 let parser = RustParser {
340 name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
341 default_port : ports.as_ptr(),
342 ipproto : IPPROTO_UDP,
343 probe_ts : Some(rs_dhcp_probing_parser),
344 probe_tc : Some(rs_dhcp_probing_parser),
345 min_depth : 0,
346 max_depth : 16,
347 state_new : rs_dhcp_state_new,
348 state_free : rs_dhcp_state_free,
349 tx_free : rs_dhcp_state_tx_free,
350 parse_ts : rs_dhcp_parse,
351 parse_tc : rs_dhcp_parse,
352 get_tx_count : rs_dhcp_state_get_tx_count,
353 get_tx : rs_dhcp_state_get_tx,
354 tx_comp_st_ts : 1,
355 tx_comp_st_tc : 1,
356 tx_get_progress : rs_dhcp_tx_get_alstate_progress,
357 get_de_state : rs_dhcp_tx_get_detect_state,
358 set_de_state : rs_dhcp_tx_set_detect_state,
359 get_events : Some(rs_dhcp_state_get_events),
360 get_eventinfo : Some(DHCPEvent::get_event_info),
361 get_eventinfo_byid : Some(DHCPEvent::get_event_info_by_id),
362 localstorage_new : None,
363 localstorage_free : None,
364 get_files : None,
365 get_tx_iterator : Some(rs_dhcp_state_get_tx_iterator),
366 get_tx_data : rs_dhcp_get_tx_data,
367 apply_tx_config : None,
368 flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
369 truncate : None,
370 };
371
372 let ip_proto_str = CString::new("udp").unwrap();
373
374 if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
375 let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
376 ALPROTO_DHCP = alproto;
377 if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
378 let _ = AppLayerRegisterParser(&parser, alproto);
379 }
380 } else {
381 SCLogDebug!("Protocol detector and parser disabled for DHCP.");
382 }
383 }