suricata 8.0.0

Suricata Rust components
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/* Copyright (C) 2019-2022 Open Information Security Foundation
 *
 * You can copy, redistribute or modify this Program under the terms of
 * the GNU General Public License version 2 as published by the Free
 * Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

// written by Giuseppe Longo <giuseppe@glongo.it>

use crate::applayer::{self, *};
use crate::core;
use crate::core::{
    sc_app_layer_parser_trigger_raw_stream_inspection, ALPROTO_UNKNOWN, IPPROTO_TCP, IPPROTO_UDP,
};
use crate::direction::Direction;
use crate::flow::Flow;
use crate::frames::*;
use crate::sip::parser::*;
use nom7::Err;
use std;
use std::collections::VecDeque;
use std::ffi::CString;
use suricata_sys::sys::{
    AppLayerParserState, AppProto, SCAppLayerParserConfParserEnabled,
    SCAppLayerParserRegisterLogger, SCAppLayerParserStateIssetFlag,
    SCAppLayerProtoDetectConfProtoDetectionEnabled, SCAppLayerProtoDetectPMRegisterPatternCS,
};

// app-layer-frame-documentation tag start: FrameType enum
#[derive(AppLayerFrameType)]
pub enum SIPFrameType {
    Pdu,
    RequestLine,
    ResponseLine,
    RequestHeaders,
    ResponseHeaders,
    RequestBody,
    ResponseBody,
}
// app-layer-frame-documentation tag end: FrameType enum

#[derive(AppLayerEvent)]
pub enum SIPEvent {
    IncompleteData,
    InvalidData,
}

#[derive(Default)]
pub struct SIPState {
    state_data: AppLayerStateData,
    transactions: VecDeque<SIPTransaction>,
    tx_id: u64,
    request_frame: Option<Frame>,
    response_frame: Option<Frame>,
}

impl State<SIPTransaction> for SIPState {
    fn get_transaction_count(&self) -> usize {
        self.transactions.len()
    }

    fn get_transaction_by_index(&self, index: usize) -> Option<&SIPTransaction> {
        self.transactions.get(index)
    }
}

pub struct SIPTransaction {
    id: u64,
    pub request: Option<Request>,
    pub response: Option<Response>,
    pub request_line: Option<String>,
    pub response_line: Option<String>,
    tx_data: applayer::AppLayerTxData,
}

impl Transaction for SIPTransaction {
    fn id(&self) -> u64 {
        self.id
    }
}

impl SIPState {
    pub fn new() -> SIPState {
        Default::default()
    }

    pub fn free(&mut self) {
        self.transactions.clear();
    }

    fn new_tx(&mut self, direction: Direction) -> SIPTransaction {
        self.tx_id += 1;
        SIPTransaction::new(self.tx_id, direction)
    }

    fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> {
        self.transactions.iter().find(|&tx| tx.id == tx_id + 1)
    }

    fn free_tx(&mut self, tx_id: u64) {
        let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1);
        debug_assert!(tx.is_some());
        if let Some(idx) = tx {
            let _ = self.transactions.remove(idx);
        }
    }

    fn set_event(&mut self, event: SIPEvent) {
        if let Some(tx) = self.transactions.back_mut() {
            tx.tx_data.set_event(event as u8);
        }
    }

    // app-layer-frame-documentation tag start: parse_request
    fn parse_request(&mut self, flow: *const Flow, stream_slice: StreamSlice) -> bool {
        let input = stream_slice.as_slice();
        let _pdu = Frame::new(
            flow,
            &stream_slice,
            input,
            input.len() as i64,
            SIPFrameType::Pdu as u8,
            None,
        );
        SCLogDebug!("ts: pdu {:?}", _pdu);

        match parse_request(input) {
            Ok((_, request)) => {
                let mut tx = self.new_tx(Direction::ToServer);
                sip_frames_ts(flow, &stream_slice, &request, tx.id);
                tx.request = Some(request);
                if let Ok((_, req_line)) = sip_take_line(input) {
                    tx.request_line = req_line;
                }
                self.transactions.push_back(tx);
                return true;
            }
            // app-layer-frame-documentation tag end: parse_request
            Err(Err::Incomplete(_)) => {
                self.set_event(SIPEvent::IncompleteData);
                return false;
            }
            Err(_) => {
                self.set_event(SIPEvent::InvalidData);
                return false;
            }
        }
    }

    fn parse_request_tcp(
        &mut self, flow: *mut Flow, stream_slice: StreamSlice,
    ) -> AppLayerResult {
        let input = stream_slice.as_slice();
        if input.is_empty() {
            return AppLayerResult::ok();
        }

        let mut start = input;
        while !start.is_empty() {
            if self.request_frame.is_none() {
                self.request_frame = Frame::new(
                    flow,
                    &stream_slice,
                    start,
                    -1_i64,
                    SIPFrameType::Pdu as u8,
                    None,
                );
                SCLogDebug!("ts: pdu {:?}", self.request_frame);
            }
            match parse_request(start) {
                Ok((rem, request)) => {
                    let mut tx = self.new_tx(Direction::ToServer);
                    let tx_id = tx.id;
                    sip_frames_ts(flow, &stream_slice, &request, tx_id);
                    tx.request = Some(request);
                    if let Ok((_, req_line)) = sip_take_line(start) {
                        tx.request_line = req_line;
                    }
                    self.transactions.push_back(tx);
                    sc_app_layer_parser_trigger_raw_stream_inspection(
                        flow,
                        Direction::ToServer as i32,
                    );
                    let consumed = start.len() - rem.len();
                    start = rem;

                    if let Some(frame) = &self.request_frame {
                        frame.set_len(flow, consumed as i64);
                        frame.set_tx(flow, tx_id);
                        self.request_frame = None;
                    }
                }
                Err(Err::Incomplete(_needed)) => {
                    let consumed = input.len() - start.len();
                    let needed_estimation = start.len() + 1;
                    SCLogDebug!(
                        "Needed: {:?}, estimated needed: {:?}",
                        _needed,
                        needed_estimation
                    );
                    return AppLayerResult::incomplete(consumed as u32, needed_estimation as u32);
                }
                Err(_) => {
                    self.set_event(SIPEvent::InvalidData);
                    return AppLayerResult::err();
                }
            }
        }

        // input fully consumed.
        return AppLayerResult::ok();
    }

    fn parse_response(&mut self, flow: *const Flow, stream_slice: StreamSlice) -> bool {
        let input = stream_slice.as_slice();
        let _pdu = Frame::new(
            flow,
            &stream_slice,
            input,
            input.len() as i64,
            SIPFrameType::Pdu as u8,
            None,
        );
        SCLogDebug!("tc: pdu {:?}", _pdu);

        match parse_response(input) {
            Ok((_, response)) => {
                let mut tx = self.new_tx(Direction::ToClient);
                sip_frames_tc(flow, &stream_slice, &response, tx.id);
                tx.response = Some(response);
                if let Ok((_, resp_line)) = sip_take_line(input) {
                    tx.response_line = resp_line;
                }
                self.transactions.push_back(tx);
                return true;
            }
            Err(Err::Incomplete(_)) => {
                self.set_event(SIPEvent::IncompleteData);
                return false;
            }
            Err(_) => {
                self.set_event(SIPEvent::InvalidData);
                return false;
            }
        }
    }

    fn parse_response_tcp(
        &mut self, flow: *mut Flow, stream_slice: StreamSlice,
    ) -> AppLayerResult {
        let input = stream_slice.as_slice();
        if input.is_empty() {
            return AppLayerResult::ok();
        }

        let mut start = input;
        while !start.is_empty() {
            if self.response_frame.is_none() {
                self.response_frame = Frame::new(
                    flow,
                    &stream_slice,
                    start,
                    -1_i64,
                    SIPFrameType::Pdu as u8,
                    None,
                );
                SCLogDebug!("tc: pdu {:?}", self.request_frame);
            }
            match parse_response(start) {
                Ok((rem, response)) => {
                    let mut tx = self.new_tx(Direction::ToClient);
                    let tx_id = tx.id;
                    sip_frames_tc(flow, &stream_slice, &response, tx_id);
                    tx.response = Some(response);
                    if let Ok((_, resp_line)) = sip_take_line(start) {
                        tx.response_line = resp_line;
                    }
                    self.transactions.push_back(tx);
                    sc_app_layer_parser_trigger_raw_stream_inspection(
                        flow,
                        Direction::ToClient as i32,
                    );
                    let consumed = start.len() - rem.len();
                    start = rem;

                    if let Some(frame) = &self.response_frame {
                        frame.set_len(flow, consumed as i64);
                        frame.set_tx(flow, tx_id);
                        self.response_frame = None;
                    }
                }
                Err(Err::Incomplete(_needed)) => {
                    let consumed = input.len() - start.len();
                    let needed_estimation = start.len() + 1;
                    SCLogDebug!(
                        "Needed: {:?}, estimated needed: {:?}",
                        _needed,
                        needed_estimation
                    );
                    return AppLayerResult::incomplete(consumed as u32, needed_estimation as u32);
                }
                Err(_) => {
                    self.set_event(SIPEvent::InvalidData);
                    return AppLayerResult::err();
                }
            }
        }

        // input fully consumed.
        return AppLayerResult::ok();
    }
}

impl SIPTransaction {
    pub fn new(id: u64, direction: Direction) -> SIPTransaction {
        SIPTransaction {
            id,
            request: None,
            response: None,
            request_line: None,
            response_line: None,
            tx_data: applayer::AppLayerTxData::for_direction(direction),
        }
    }
}

// app-layer-frame-documentation tag start: function to add frames
fn sip_frames_ts(flow: *const Flow, stream_slice: &StreamSlice, r: &Request, tx_id: u64) {
    let oi = stream_slice.as_slice();
    let _f = Frame::new(
        flow,
        stream_slice,
        oi,
        r.request_line_len as i64,
        SIPFrameType::RequestLine as u8,
        Some(tx_id),
    );
    SCLogDebug!("ts: request_line {:?}", _f);
    let hi = &oi[r.request_line_len as usize..];
    let _f = Frame::new(
        flow,
        stream_slice,
        hi,
        r.headers_len as i64,
        SIPFrameType::RequestHeaders as u8,
        Some(tx_id),
    );
    SCLogDebug!("ts: request_headers {:?}", _f);
    if r.body_len > 0 {
        let bi = &oi[r.body_offset as usize..];
        let _f = Frame::new(
            flow,
            stream_slice,
            bi,
            r.body_len as i64,
            SIPFrameType::RequestBody as u8,
            Some(tx_id),
        );
        SCLogDebug!("ts: request_body {:?}", _f);
    }
}
// app-layer-frame-documentation tag end: function to add frames

fn sip_frames_tc(flow: *const Flow, stream_slice: &StreamSlice, r: &Response, tx_id: u64) {
    let oi = stream_slice.as_slice();
    let _f = Frame::new(
        flow,
        stream_slice,
        oi,
        r.response_line_len as i64,
        SIPFrameType::ResponseLine as u8,
        Some(tx_id),
    );
    let hi = &oi[r.response_line_len as usize..];
    SCLogDebug!("tc: response_line {:?}", _f);
    let _f = Frame::new(
        flow,
        stream_slice,
        hi,
        r.headers_len as i64,
        SIPFrameType::ResponseHeaders as u8,
        Some(tx_id),
    );
    SCLogDebug!("tc: response_headers {:?}", _f);
    if r.body_len > 0 {
        let bi = &oi[r.body_offset as usize..];
        let _f = Frame::new(
            flow,
            stream_slice,
            bi,
            r.body_len as i64,
            SIPFrameType::ResponseBody as u8,
            Some(tx_id),
        );
        SCLogDebug!("tc: response_body {:?}", _f);
    }
}

extern "C" fn sip_state_new(
    _orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
    let state = SIPState::new();
    let boxed = Box::new(state);
    return Box::into_raw(boxed) as *mut _;
}

extern "C" fn sip_state_free(state: *mut std::os::raw::c_void) {
    let mut state = unsafe { Box::from_raw(state as *mut SIPState) };
    state.free();
}

unsafe extern "C" fn sip_state_get_tx(
    state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
    let state = cast_pointer!(state, SIPState);
    match state.get_tx_by_id(tx_id) {
        Some(tx) => tx as *const _ as *mut _,
        None => std::ptr::null_mut(),
    }
}

unsafe extern "C" fn sip_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
    let state = cast_pointer!(state, SIPState);
    state.tx_id
}

unsafe extern "C" fn sip_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
    let state = cast_pointer!(state, SIPState);
    state.free_tx(tx_id);
}

extern "C" fn sip_tx_get_alstate_progress(
    _tx: *mut std::os::raw::c_void, _direction: u8,
) -> std::os::raw::c_int {
    1
}

pub static mut ALPROTO_SIP: AppProto = ALPROTO_UNKNOWN;

unsafe extern "C" fn sip_parse_request(
    flow: *mut Flow, state: *mut std::os::raw::c_void, _pstate: *mut AppLayerParserState,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    let state = cast_pointer!(state, SIPState);
    state.parse_request(flow, stream_slice).into()
}

unsafe extern "C" fn sip_parse_request_tcp(
    flow: *mut Flow, state: *mut std::os::raw::c_void, pstate: *mut AppLayerParserState,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    if stream_slice.is_empty() {
        if SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) > 0 {
            return AppLayerResult::ok();
        } else {
            return AppLayerResult::err();
        }
    }

    let state = cast_pointer!(state, SIPState);
    state.parse_request_tcp(flow, stream_slice)
}

unsafe extern "C" fn sip_parse_response(
    flow: *mut Flow, state: *mut std::os::raw::c_void, _pstate: *mut AppLayerParserState,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    let state = cast_pointer!(state, SIPState);
    state.parse_response(flow, stream_slice).into()
}

unsafe extern "C" fn sip_parse_response_tcp(
    flow: *mut Flow, state: *mut std::os::raw::c_void, pstate: *mut AppLayerParserState,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    if stream_slice.is_empty() {
        if SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC) > 0 {
            return AppLayerResult::ok();
        } else {
            return AppLayerResult::err();
        }
    }

    let state = cast_pointer!(state, SIPState);
    state.parse_response_tcp(flow, stream_slice)
}

fn register_pattern_probe(proto: u8) -> i8 {
    let methods: Vec<&str> = vec![
        "REGISTER\0",
        "INVITE\0",
        "ACK\0",
        "BYE\0",
        "CANCEL\0",
        "REFER\0",
        "PRACK\0",
        "SUBSCRIBE\0",
        "NOTIFY\0",
        "PUBLISH\0",
        "MESSAGE\0",
        "INFO\0",
    ];
    let mut r = 0;
    unsafe {
        for method in methods {
            let depth = (method.len() - 1) as u16;
            r |= SCAppLayerProtoDetectPMRegisterPatternCS(
                proto,
                ALPROTO_SIP,
                method.as_ptr() as *const std::os::raw::c_char,
                depth,
                0,
                Direction::ToServer as u8,
            );
        }
        r |= SCAppLayerProtoDetectPMRegisterPatternCS(
            proto,
            ALPROTO_SIP,
            b"SIP/2.0\0".as_ptr() as *const std::os::raw::c_char,
            8,
            0,
            Direction::ToClient as u8,
        );
        if proto == core::IPPROTO_UDP {
            r |= SCAppLayerProtoDetectPMRegisterPatternCS(
                proto,
                ALPROTO_SIP,
                "UPDATE\0".as_ptr() as *const std::os::raw::c_char,
                "UPDATE".len() as u16,
                0,
                Direction::ToServer as u8,
            );
        }
    }

    if r == 0 {
        return 0;
    } else {
        return -1;
    }
}

export_tx_data_get!(sip_get_tx_data, SIPTransaction);
export_state_data_get!(sip_get_state_data, SIPState);

const PARSER_NAME: &[u8] = b"sip\0";

#[no_mangle]
pub unsafe extern "C" fn SCRegisterSipParser() {
    let mut parser = RustParser {
        name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
        default_port: std::ptr::null(),
        ipproto: core::IPPROTO_UDP,
        probe_ts: None,
        probe_tc: None,
        min_depth: 0,
        max_depth: 16,
        state_new: sip_state_new,
        state_free: sip_state_free,
        tx_free: sip_state_tx_free,
        parse_ts: sip_parse_request,
        parse_tc: sip_parse_response,
        get_tx_count: sip_state_get_tx_count,
        get_tx: sip_state_get_tx,
        tx_comp_st_ts: 1,
        tx_comp_st_tc: 1,
        tx_get_progress: sip_tx_get_alstate_progress,
        get_eventinfo: Some(SIPEvent::get_event_info),
        get_eventinfo_byid: Some(SIPEvent::get_event_info_by_id),
        localstorage_new: None,
        localstorage_free: None,
        get_tx_files: None,
        get_tx_iterator: Some(applayer::state_get_tx_iterator::<SIPState, SIPTransaction>),
        get_tx_data: sip_get_tx_data,
        get_state_data: sip_get_state_data,
        apply_tx_config: None,
        flags: 0,
        get_frame_id_by_name: Some(SIPFrameType::ffi_id_from_name),
        get_frame_name_by_id: Some(SIPFrameType::ffi_name_from_id),
        get_state_id_by_name: None,
        get_state_name_by_id: None,
    };

    let ip_proto_str = CString::new("udp").unwrap();
    if SCAppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
        let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
        ALPROTO_SIP = alproto;
        if SCAppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
            let _ = AppLayerRegisterParser(&parser, alproto);
        }
        if register_pattern_probe(core::IPPROTO_UDP) < 0 {
            return;
        }
        SCAppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_SIP);
    } else {
        SCLogDebug!("Protocol detection and parsing disabled for UDP SIP.");
    }

    // register TCP parser
    parser.ipproto = core::IPPROTO_TCP;
    parser.probe_ts = None;
    parser.probe_tc = None;
    parser.parse_ts = sip_parse_request_tcp;
    parser.parse_tc = sip_parse_response_tcp;

    let ip_proto_str = CString::new("tcp").unwrap();
    if SCAppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
        let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
        ALPROTO_SIP = alproto;
        if SCAppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
            let _ = AppLayerRegisterParser(&parser, alproto);
        }
        if register_pattern_probe(core::IPPROTO_TCP) < 0 {
            return;
        }
        SCAppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_SIP);
    } else {
        SCLogDebug!("Protocol detection and parsing disabled for TCP SIP.");
    }
}