]> git.ipfire.org Git - people/ms/suricata.git/blame - rust/src/applayer.rs
doc: update sphinx api to use add_css_file
[people/ms/suricata.git] / rust / src / applayer.rs
CommitLineData
2f5834cd 1/* Copyright (C) 2017-2020 Open Information Security Foundation
c54fc7f9
JI
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
2f5834cd
VJ
18//! Parser registration functions and common interface
19
e96d9c11 20use std;
2f5834cd
VJ
21use crate::core::{DetectEngineState,Flow,AppLayerEventType,AppLayerDecoderEvents,AppProto};
22use crate::filecontainer::FileContainer;
23use crate::applayer;
24use std::os::raw::{c_void,c_char,c_int};
3ada5e14 25use crate::core::SC;
2f5834cd 26
411f428a
VJ
27#[repr(C)]
28#[derive(Debug,PartialEq)]
29pub struct AppLayerTxConfig {
30 /// config: log flags
31 log_flags: u8,
32}
33
34impl AppLayerTxConfig {
35 pub fn new() -> Self {
36 Self {
37 log_flags: 0,
38 }
39 }
40
41 pub fn add_log_flags(&mut self, flags: u8) {
42 self.log_flags |= flags;
43 }
44 pub fn set_log_flags(&mut self, flags: u8) {
45 self.log_flags = flags;
46 }
47 pub fn get_log_flags(&self) -> u8 {
48 self.log_flags
49 }
50}
51
52#[repr(C)]
53#[derive(Debug,PartialEq)]
54pub struct AppLayerTxData {
55 /// config: log flags
56 pub config: AppLayerTxConfig,
c797c9f0
VJ
57
58 /// logger flags for tx logging api
59 logged: LoggerFlags,
e15995e2
VJ
60
61 /// detection engine flags for use by detection engine
62 detect_flags_ts: u64,
63 detect_flags_tc: u64,
411f428a
VJ
64}
65
66impl AppLayerTxData {
67 pub fn new() -> Self {
68 Self {
69 config: AppLayerTxConfig::new(),
c797c9f0 70 logged: LoggerFlags::new(),
e15995e2
VJ
71 detect_flags_ts: 0,
72 detect_flags_tc: 0,
411f428a
VJ
73 }
74 }
75}
76
77#[macro_export]
78macro_rules!export_tx_data_get {
79 ($name:ident, $type:ty) => {
80 #[no_mangle]
81 pub unsafe extern "C" fn $name(tx: *mut std::os::raw::c_void)
82 -> *mut crate::applayer::AppLayerTxData
83 {
84 let tx = &mut *(tx as *mut $type);
85 &mut tx.tx_data
86 }
87 }
88}
89
2f5834cd 90#[repr(C)]
3a2434ed 91#[derive(Debug,PartialEq,Copy,Clone)]
2f5834cd
VJ
92pub struct AppLayerResult {
93 pub status: i32,
94 pub consumed: u32,
95 pub needed: u32,
96}
97
98impl AppLayerResult {
99 /// parser has successfully processed in the input, and has consumed all of it
100 pub fn ok() -> AppLayerResult {
101 return AppLayerResult {
102 status: 0,
103 consumed: 0,
104 needed: 0,
105 };
106 }
107 /// parser has hit an unrecoverable error. Returning this to the API
108 /// leads to no further calls to the parser.
109 pub fn err() -> AppLayerResult {
110 return AppLayerResult {
111 status: -1,
112 consumed: 0,
113 needed: 0,
114 };
115 }
116 /// parser needs more data. Through 'consumed' it will indicate how many
117 /// of the input bytes it has consumed. Through 'needed' it will indicate
118 /// how many more bytes it needs before getting called again.
119 /// Note: consumed should never be more than the input len
120 /// needed + consumed should be more than the input len
121 pub fn incomplete(consumed: u32, needed: u32) -> AppLayerResult {
122 return AppLayerResult {
123 status: 1,
124 consumed: consumed,
125 needed: needed,
126 };
127 }
b0288da6
VJ
128
129 pub fn is_ok(self) -> bool {
130 self.status == 0
131 }
132 pub fn is_incomplete(self) -> bool {
133 self.status == 1
134 }
135 pub fn is_err(self) -> bool {
136 self.status == -1
137 }
2f5834cd
VJ
138}
139
acef21b7
VJ
140impl From<bool> for AppLayerResult {
141 fn from(v: bool) -> Self {
142 if v == false {
143 Self::err()
144 } else {
145 Self::ok()
146 }
147 }
148}
149
150impl From<i32> for AppLayerResult {
151 fn from(v: i32) -> Self {
152 if v < 0 {
153 Self::err()
154 } else {
155 Self::ok()
156 }
157 }
158}
159
2f5834cd
VJ
160/// Rust parser declaration
161#[repr(C)]
162pub struct RustParser {
163 /// Parser name.
164 pub name: *const c_char,
165 /// Default port
166 pub default_port: *const c_char,
167
168 /// IP Protocol (core::IPPROTO_UDP, core::IPPROTO_TCP, etc.)
169 pub ipproto: c_int,
170
171 /// Probing function, for packets going to server
172 pub probe_ts: Option<ProbeFn>,
173 /// Probing function, for packets going to client
174 pub probe_tc: Option<ProbeFn>,
175
176 /// Minimum frame depth for probing
177 pub min_depth: u16,
178 /// Maximum frame depth for probing
179 pub max_depth: u16,
180
181 /// Allocation function for a new state
182 pub state_new: StateAllocFn,
183 /// Function called to free a state
184 pub state_free: StateFreeFn,
185
186 /// Parsing function, for packets going to server
187 pub parse_ts: ParseFn,
188 /// Parsing function, for packets going to client
189 pub parse_tc: ParseFn,
190
191 /// Get the current transaction count
192 pub get_tx_count: StateGetTxCntFn,
193 /// Get a transaction
194 pub get_tx: StateGetTxFn,
195 /// Function called to free a transaction
196 pub tx_free: StateTxFreeFn,
efc9a7a3
VJ
197 /// Progress values at which the tx is considered complete in a direction
198 pub tx_comp_st_ts: c_int,
199 pub tx_comp_st_tc: c_int,
2f5834cd
VJ
200 /// Function returning the current transaction progress
201 pub tx_get_progress: StateGetProgressFn,
202
2f5834cd
VJ
203 /// Function called to get a detection state
204 pub get_de_state: GetDetectStateFn,
205 /// Function called to set a detection state
206 pub set_de_state: SetDetectStateFn,
207
208 /// Function to get events
209 pub get_events: Option<GetEventsFn>,
210 /// Function to get an event id from a description
211 pub get_eventinfo: Option<GetEventInfoFn>,
212 /// Function to get an event description from an event id
213 pub get_eventinfo_byid: Option<GetEventInfoByIdFn>,
214
215 /// Function to allocate local storage
216 pub localstorage_new: Option<LocalStorageNewFn>,
217 /// Function to free local storage
218 pub localstorage_free: Option<LocalStorageFreeFn>,
219
2f5834cd
VJ
220 /// Function to get files
221 pub get_files: Option<GetFilesFn>,
222
223 /// Function to get the TX iterator
224 pub get_tx_iterator: Option<GetTxIteratorFn>,
225
c94a5e63 226 pub get_tx_data: GetTxDataFn,
5665fc83
VJ
227
228 // Function to apply config to a TX. Optional. Normal (bidirectional)
229 // transactions don't need to set this. It is meant for cases where
230 // the requests and responses are not sharing tx. It is then up to
231 // the implementation to make sure the config is applied correctly.
232 pub apply_tx_config: Option<ApplyTxConfigFn>,
53aa967e
JI
233
234 pub flags: u32,
4da0d9bd
VJ
235
236 /// Function to handle the end of data coming on one of the sides
237 /// due to the stream reaching its 'depth' limit.
238 pub truncate: Option<TruncateFn>,
2f5834cd
VJ
239}
240
241/// Create a slice, given a buffer and a length
242///
243/// UNSAFE !
244#[macro_export]
245macro_rules! build_slice {
246 ($buf:ident, $len:expr) => ( unsafe{ std::slice::from_raw_parts($buf, $len) } );
247}
248
249/// Cast pointer to a variable, as a mutable reference to an object
250///
251/// UNSAFE !
252#[macro_export]
253macro_rules! cast_pointer {
254 ($ptr:ident, $ty:ty) => ( unsafe{ &mut *($ptr as *mut $ty) } );
255}
256
257pub type ParseFn = extern "C" fn (flow: *const Flow,
258 state: *mut c_void,
259 pstate: *mut c_void,
260 input: *const u8,
261 input_len: u32,
262 data: *const c_void,
263 flags: u8) -> AppLayerResult;
c6aadf0d 264pub type ProbeFn = extern "C" fn (flow: *const Flow, flags: u8, input:*const u8, input_len: u32, rdir: *mut u8) -> AppProto;
547d6c2d 265pub type StateAllocFn = extern "C" fn (*mut c_void, AppProto) -> *mut c_void;
2f5834cd
VJ
266pub type StateFreeFn = extern "C" fn (*mut c_void);
267pub type StateTxFreeFn = extern "C" fn (*mut c_void, u64);
268pub type StateGetTxFn = extern "C" fn (*mut c_void, u64) -> *mut c_void;
269pub type StateGetTxCntFn = extern "C" fn (*mut c_void) -> u64;
2f5834cd
VJ
270pub type StateGetProgressFn = extern "C" fn (*mut c_void, u8) -> c_int;
271pub type GetDetectStateFn = extern "C" fn (*mut c_void) -> *mut DetectEngineState;
272pub type SetDetectStateFn = extern "C" fn (*mut c_void, &mut DetectEngineState) -> c_int;
273pub type GetEventInfoFn = extern "C" fn (*const c_char, *mut c_int, *mut AppLayerEventType) -> c_int;
274pub type GetEventInfoByIdFn = extern "C" fn (c_int, *mut *const c_char, *mut AppLayerEventType) -> i8;
275pub type GetEventsFn = extern "C" fn (*mut c_void) -> *mut AppLayerDecoderEvents;
2f5834cd
VJ
276pub type LocalStorageNewFn = extern "C" fn () -> *mut c_void;
277pub type LocalStorageFreeFn = extern "C" fn (*mut c_void);
2f5834cd
VJ
278pub type GetFilesFn = extern "C" fn (*mut c_void, u8) -> *mut FileContainer;
279pub type GetTxIteratorFn = extern "C" fn (ipproto: u8, alproto: AppProto,
280 state: *mut c_void,
281 min_tx_id: u64,
282 max_tx_id: u64,
283 istate: &mut u64)
284 -> AppLayerGetTxIterTuple;
411f428a 285pub type GetTxDataFn = unsafe extern "C" fn(*mut c_void) -> *mut AppLayerTxData;
5665fc83 286pub type ApplyTxConfigFn = unsafe extern "C" fn (*mut c_void, *mut c_void, c_int, AppLayerTxConfig);
4da0d9bd
VJ
287pub type TruncateFn = unsafe extern "C" fn (*mut c_void, u8);
288
2f5834cd
VJ
289
290// Defined in app-layer-register.h
291extern {
292 pub fn AppLayerRegisterProtocolDetection(parser: *const RustParser, enable_default: c_int) -> AppProto;
ab6171c4 293 pub fn AppLayerRegisterParserAlias(parser_name: *const c_char, alias_name: *const c_char);
3ada5e14
JI
294}
295
296#[allow(non_snake_case)]
297pub unsafe fn AppLayerRegisterParser(parser: *const RustParser, alproto: AppProto) -> c_int {
298 (SC.unwrap().AppLayerRegisterParser)(parser, alproto)
2f5834cd
VJ
299}
300
301// Defined in app-layer-detect-proto.h
302extern {
d66ad96f
SB
303 pub fn AppLayerProtoDetectPMRegisterPatternCSwPP(iproto: u8, alproto: AppProto,
304 pattern: *const c_char, depth: u16,
305 offset: u16, direction: u8, ppfn: ProbeFn,
306 pp_min_depth: u16, pp_max_depth: u16) -> c_int;
2f5834cd
VJ
307 pub fn AppLayerProtoDetectConfProtoDetectionEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int;
308}
309
310// Defined in app-layer-parser.h
d7a3523b
SB
311pub const APP_LAYER_PARSER_EOF_TS : u8 = 0b0101;
312pub const APP_LAYER_PARSER_EOF_TC : u8 = 0b0110;
2f5834cd
VJ
313pub const APP_LAYER_PARSER_NO_INSPECTION : u8 = 0b1;
314pub const APP_LAYER_PARSER_NO_REASSEMBLY : u8 = 0b10;
315pub const APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD : u8 = 0b100;
316pub const APP_LAYER_PARSER_BYPASS_READY : u8 = 0b1000;
e96d9c11 317
a0e3e2d7 318pub const APP_LAYER_PARSER_OPT_ACCEPT_GAPS: u32 = BIT_U32!(0);
ac3cf6ff 319pub const APP_LAYER_PARSER_OPT_UNIDIR_TXS: u32 = BIT_U32!(1);
a0e3e2d7 320
2f5834cd
VJ
321pub type AppLayerGetTxIteratorFn = extern "C" fn (ipproto: u8,
322 alproto: AppProto,
323 alstate: *mut c_void,
324 min_tx_id: u64,
325 max_tx_id: u64,
326 istate: &mut u64) -> applayer::AppLayerGetTxIterTuple;
327
328extern {
329 pub fn AppLayerParserStateSetFlag(state: *mut c_void, flag: u8);
330 pub fn AppLayerParserStateIssetFlag(state: *mut c_void, flag: u8) -> c_int;
331 pub fn AppLayerParserConfParserEnabled(ipproto: *const c_char, proto: *const c_char) -> c_int;
332 pub fn AppLayerParserRegisterGetTxIterator(ipproto: u8, alproto: AppProto, fun: AppLayerGetTxIteratorFn);
2f5834cd
VJ
333 pub fn AppLayerParserRegisterOptionFlags(ipproto: u8, alproto: AppProto, flags: u32);
334}
335
e96d9c11
VJ
336#[repr(C)]
337pub struct AppLayerGetTxIterTuple {
3f6624bf 338 tx_ptr: *mut std::os::raw::c_void,
e96d9c11
VJ
339 tx_id: u64,
340 has_next: bool,
341}
342
343impl AppLayerGetTxIterTuple {
3f6624bf 344 pub fn with_values(tx_ptr: *mut std::os::raw::c_void, tx_id: u64, has_next: bool) -> AppLayerGetTxIterTuple {
e96d9c11
VJ
345 AppLayerGetTxIterTuple {
346 tx_ptr: tx_ptr, tx_id: tx_id, has_next: has_next,
347 }
348 }
349 pub fn not_found() -> AppLayerGetTxIterTuple {
350 AppLayerGetTxIterTuple {
351 tx_ptr: std::ptr::null_mut(), tx_id: 0, has_next: false,
352 }
353 }
354}
355
c54fc7f9 356/// LoggerFlags tracks which loggers have already been executed.
c797c9f0
VJ
357#[repr(C)]
358#[derive(Debug,PartialEq)]
c54fc7f9
JI
359pub struct LoggerFlags {
360 flags: u32,
361}
362
363impl LoggerFlags {
364
365 pub fn new() -> LoggerFlags {
366 return LoggerFlags{
367 flags: 0,
368 }
369 }
370
bca0cd71
VJ
371 pub fn get(&self) -> u32 {
372 self.flags
373 }
374
375 pub fn set(&mut self, bits: u32) {
376 self.flags = bits;
377 }
378
c54fc7f9 379}
2ec33816
JI
380
381/// Export a function to get the DetectEngineState on a struct.
382#[macro_export]
383macro_rules!export_tx_get_detect_state {
384 ($name:ident, $type:ty) => (
385 #[no_mangle]
3f6624bf 386 pub extern "C" fn $name(tx: *mut std::os::raw::c_void)
2ec33816
JI
387 -> *mut core::DetectEngineState
388 {
389 let tx = cast_pointer!(tx, $type);
390 match tx.de_state {
391 Some(ds) => {
392 return ds;
393 },
394 None => {
395 return std::ptr::null_mut();
396 }
397 }
398 }
399 )
400}
401
402/// Export a function to set the DetectEngineState on a struct.
403#[macro_export]
404macro_rules!export_tx_set_detect_state {
405 ($name:ident, $type:ty) => (
406 #[no_mangle]
3f6624bf
VJ
407 pub extern "C" fn $name(tx: *mut std::os::raw::c_void,
408 de_state: &mut core::DetectEngineState) -> std::os::raw::c_int
2ec33816
JI
409 {
410 let tx = cast_pointer!(tx, $type);
411 tx.de_state = Some(de_state);
412 0
413 }
414 )
415}