coraza 0.1.0

Safe Rust bindings to OWASP Coraza WAF
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
/*
 * Copyright 2022 OWASP Coraza contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! HTTP transaction processing.

use std::cell::UnsafeCell;
use std::ffi::CString;
use std::marker::PhantomData;

use coraza_sys::*;

use crate::error::Error;
use crate::intervention::Intervention;

/// An HTTP transaction for processing through the WAF.
///
/// Transactions are created from a [`Waf`](crate::Waf) instance and follow
/// a phase-based lifecycle:
///
/// 1. **Phase 0**: Connection and URI processing
/// 2. **Phase 1**: Request header processing
/// 3. **Phase 2**: Request body processing
/// 4. **Phase 3**: Response header processing
/// 5. **Phase 4**: Response body processing
/// 6. **Phase 5**: Logging
///
/// Each phase must be processed in order. After processing, check
/// [`intervention()`](Transaction::intervention) to see if a rule matched.
///
/// # Example
///
/// ```no_run
/// use coraza::WafConfig;
///
/// let waf = WafConfig::new()
///     .unwrap()
///     .with_directives("SecRuleEngine DetectionOnly")
///     .build()
///     .unwrap();
///
/// let mut tx = waf.new_transaction();
///
/// // Phase 0
/// tx.process_connection("127.0.0.1", 8080, "localhost", 80).unwrap();
/// tx.process_uri("/path", "GET", "HTTP/1.1").unwrap();
///
/// // Phase 1
/// tx.add_request_header("Host", "localhost");
/// tx.process_request_headers().unwrap();
///
/// // Phase 2 (if body access is enabled)
/// tx.append_request_body(b"hello=world").unwrap();
/// tx.process_request_body().unwrap();
///
/// // Phase 3
/// tx.process_response_headers(200, "HTTP/1.1").unwrap();
///
/// // Phase 4
/// tx.process_response_body().unwrap();
///
/// // Phase 5
/// tx.process_logging();
///
/// // Check for rule matches
/// if let Some(intervention) = tx.intervention() {
///     eprintln!("Blocked: {}", intervention.status);
/// }
/// ```
pub struct Transaction {
    handle: coraza_transaction_t,
    closed: bool,
    _phantom: PhantomData<UnsafeCell<i32>>, // Make the struct !Sync
}

impl Transaction {
    /// Creates a new transaction from an FFI handle.
    pub(crate) fn new(handle: coraza_transaction_t) -> Self {
        Self {
            handle,
            closed: false,
            _phantom: PhantomData,
        }
    }

    /// Returns `true` if this transaction has been closed.
    pub fn is_closed(&self) -> bool {
        self.closed
    }

    // ── Phase 0: Connection & URI ─────────────────────────────────────

    /// Processes connection information (client/server addresses and ports).
    ///
    /// This is Phase 0 and must be called before any other processing.
    pub fn process_connection(
        &mut self,
        src_addr: &str,
        client_port: i32,
        server_host: &str,
        server_port: i32,
    ) -> Result<(), Error> {
        self.ensure_open()?;
        let c_src = CString::new(src_addr).map_err(|_| Error::InvalidTransaction)?;
        let c_host = CString::new(server_host).map_err(|_| Error::InvalidTransaction)?;
        let ret = unsafe {
            coraza_process_connection(
                self.handle,
                c_src.as_ptr(),
                client_port,
                c_host.as_ptr(),
                server_port,
            )
        };
        check_result(ret)
    }

    /// Processes the request URI, method, and protocol version.
    ///
    /// This is Phase 0 and must be called after [`process_connection()`](Self::process_connection).
    pub fn process_uri(&mut self, uri: &str, method: &str, proto: &str) -> Result<(), Error> {
        self.ensure_open()?;
        let c_uri = CString::new(uri).map_err(|_| Error::InvalidTransaction)?;
        let c_method = CString::new(method).map_err(|_| Error::InvalidTransaction)?;
        let c_proto = CString::new(proto).map_err(|_| Error::InvalidTransaction)?;
        let ret = unsafe {
            coraza_process_uri(
                self.handle,
                c_uri.as_ptr(),
                c_method.as_ptr(),
                c_proto.as_ptr(),
            )
        };
        check_result(ret)
    }

    // ── Phase 1: Request Headers ──────────────────────────────────────

    /// Adds a single request header.
    pub fn add_request_header(&mut self, name: &str, value: &str) {
        if self.closed {
            return;
        }
        let c_name = match CString::new(name) {
            Ok(s) => s,
            Err(_) => return,
        };
        let c_value = match CString::new(value) {
            Ok(s) => s,
            Err(_) => return,
        };
        unsafe {
            coraza_add_request_header(
                self.handle,
                c_name.as_ptr(),
                name.len() as i32,
                c_value.as_ptr(),
                value.len() as i32,
            );
        }
    }

    /// Adds multiple request headers in a single call.
    ///
    /// This is more efficient than calling [`add_request_header()`](Self::add_request_header)
    /// multiple times, as it uses a packed binary encoding.
    pub fn add_request_headers(&mut self, headers: &[(&str, &str)]) {
        if self.closed || headers.is_empty() {
            return;
        }
        let packed = pack_headers(headers);
        unsafe {
            coraza_add_request_headers(
                self.handle,
                packed.as_ptr() as *const i8,
                packed.len() as i32,
                headers.len() as i32,
            );
        }
    }

    /// Processes request headers (Phase 1).
    ///
    /// Returns `Err(Error::Intervention { .. })` if a rule fires during this phase.
    pub fn process_request_headers(&mut self) -> Result<(), Error> {
        self.ensure_open()?;
        let ret = unsafe { coraza_process_request_headers(self.handle) };
        check_result(ret)
    }

    // ── Phase 2: Request Body ─────────────────────────────────────────

    /// Adds a GET/URL query parameter.
    pub fn add_get_argument(&mut self, name: &str, value: &str) {
        if self.closed {
            return;
        }
        let c_name = match CString::new(name) {
            Ok(s) => s,
            Err(_) => return,
        };
        let c_value = match CString::new(value) {
            Ok(s) => s,
            Err(_) => return,
        };
        unsafe {
            coraza_add_get_args(self.handle, c_name.as_ptr(), c_value.as_ptr());
        }
    }

    /// Appends data to the request body buffer.
    ///
    /// Can be called multiple times to stream body data.
    pub fn append_request_body(&mut self, data: &[u8]) -> Result<(), Error> {
        self.ensure_open()?;
        if data.is_empty() {
            return Ok(());
        }
        let ret =
            unsafe { coraza_append_request_body(self.handle, data.as_ptr(), data.len() as i32) };
        if ret != 0 {
            return Err(Error::BodyOperation("failed to append request body".into()));
        }
        Ok(())
    }

    /// Processes the request body (Phase 2).
    ///
    /// Returns `Err(Error::Intervention { .. })` if a rule fires during this phase.
    pub fn process_request_body(&mut self) -> Result<(), Error> {
        self.ensure_open()?;
        let ret = unsafe { coraza_process_request_body(self.handle) };
        check_result(ret)
    }

    /// Reads the request body from a file.
    ///
    /// The file is read in chunks and appended to the request body buffer.
    pub fn request_body_from_file(&mut self, path: &str) -> Result<(), Error> {
        self.ensure_open()?;
        let c_path = CString::new(path).map_err(|_| Error::InvalidTransaction)?;
        let ret = unsafe { coraza_request_body_from_file(self.handle, c_path.as_ptr()) };
        if ret != 0 {
            return Err(Error::BodyOperation(format!(
                "failed to read body from file: {}",
                path
            )));
        }
        Ok(())
    }

    /// Sets the response status code for status-based variable inspection.
    pub fn set_status_code(&mut self, code: i32) -> Result<(), Error> {
        self.ensure_open()?;
        let ret = unsafe { coraza_update_status_code(self.handle, code) };
        if ret != 0 {
            return Err(Error::InvalidTransaction);
        }
        Ok(())
    }

    // ── Phase 3: Response Headers ─────────────────────────────────────

    /// Adds a single response header.
    pub fn add_response_header(&mut self, name: &str, value: &str) {
        if self.closed {
            return;
        }
        let c_name = match CString::new(name) {
            Ok(s) => s,
            Err(_) => return,
        };
        let c_value = match CString::new(value) {
            Ok(s) => s,
            Err(_) => return,
        };
        unsafe {
            coraza_add_response_header(
                self.handle,
                c_name.as_ptr(),
                name.len() as i32,
                c_value.as_ptr(),
                value.len() as i32,
            );
        }
    }

    /// Adds multiple response headers in a single call.
    pub fn add_response_headers(&mut self, headers: &[(&str, &str)]) {
        if self.closed || headers.is_empty() {
            return;
        }
        let packed = pack_headers(headers);
        unsafe {
            coraza_add_response_headers(
                self.handle,
                packed.as_ptr() as *const i8,
                packed.len() as i32,
                headers.len() as i32,
            );
        }
    }

    /// Processes response headers (Phase 3).
    ///
    /// Returns `Err(Error::Intervention { .. })` if a rule fires during this phase.
    pub fn process_response_headers(&mut self, status: i32, proto: &str) -> Result<(), Error> {
        self.ensure_open()?;
        let c_proto = CString::new(proto).map_err(|_| Error::InvalidTransaction)?;
        let ret = unsafe { coraza_process_response_headers(self.handle, status, c_proto.as_ptr()) };
        check_result(ret)
    }

    // ── Phase 4: Response Body ────────────────────────────────────────

    /// Appends data to the response body buffer.
    pub fn append_response_body(&mut self, data: &[u8]) -> Result<(), Error> {
        self.ensure_open()?;
        if data.is_empty() {
            return Ok(());
        }
        let ret =
            unsafe { coraza_append_response_body(self.handle, data.as_ptr(), data.len() as i32) };
        if ret != 0 {
            return Err(Error::BodyOperation(
                "failed to append response body".into(),
            ));
        }
        Ok(())
    }

    /// Returns `true` if the response body should be inspected.
    ///
    /// This depends on `SecResponseBodyAccess` and the response MIME type.
    pub fn is_response_body_processable(&self) -> bool {
        if self.closed {
            return false;
        }
        unsafe { coraza_is_response_body_processable(self.handle) != 0 }
    }

    /// Processes the response body (Phase 4).
    ///
    /// Returns `Err(Error::Intervention { .. })` if a rule fires during this phase.
    pub fn process_response_body(&mut self) -> Result<(), Error> {
        self.ensure_open()?;
        let ret = unsafe { coraza_process_response_body(self.handle) };
        check_result(ret)
    }

    // ── Phase 5: Logging ──────────────────────────────────────────────

    /// Processes logging (Phase 5).
    ///
    /// This should always be called, even if a previous phase returned an
    /// intervention. It triggers audit logging and any logging-related rules.
    pub fn process_logging(&mut self) {
        if self.closed {
            return;
        }
        unsafe {
            coraza_process_logging(self.handle);
        }
    }

    // ── Intervention Check ────────────────────────────────────────────

    /// Checks if a rule matched and produced an intervention.
    ///
    /// Returns `Some(Intervention)` if a rule fired, or `None` if no rule
    /// matched. This should be called after each phase that might trigger
    /// rules (typically after `process_request_headers` or later phases).
    pub fn intervention(&self) -> Option<Intervention> {
        if self.closed {
            return None;
        }
        let ptr = unsafe { coraza_intervention(self.handle) };
        if ptr.is_null() {
            return None;
        }
        let intervention = unsafe { &*ptr };
        let result = Intervention {
            action: if intervention.action.is_null() {
                String::new()
            } else {
                unsafe { std::ffi::CStr::from_ptr(intervention.action) }
                    .to_string_lossy()
                    .into_owned()
            },
            status: intervention.status,
            data: if intervention.data.is_null() {
                None
            } else {
                Some(
                    unsafe { std::ffi::CStr::from_ptr(intervention.data) }
                        .to_string_lossy()
                        .into_owned(),
                )
            },
            rule_id: intervention.rule_id,
        };
        unsafe {
            coraza_free_intervention(ptr);
        }
        Some(result)
    }

    // ── Lifecycle ─────────────────────────────────────────────────────

    /// Explicitly closes the transaction and releases resources.
    ///
    /// This is also called automatically by [`Drop`]. After closing,
    /// all other methods become no-ops.
    pub fn close(&mut self) -> Result<(), Error> {
        if self.closed {
            return Ok(());
        }
        self.closed = true;
        let ret = unsafe { coraza_free_transaction(self.handle) };
        if ret != 0 {
            return Err(Error::InvalidTransaction);
        }
        Ok(())
    }

    fn ensure_open(&self) -> Result<(), Error> {
        if self.closed {
            return Err(Error::InvalidTransaction);
        }
        Ok(())
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        if !self.closed {
            unsafe {
                coraza_free_transaction(self.handle);
            }
        }
    }
}

/// Maps a C result code to a Rust `Result`.
fn check_result(ret: i32) -> Result<(), Error> {
    match ret {
        coraza_result_t_CORAZA_OK => Ok(()),
        coraza_result_t_CORAZA_INTERRUPTION => Err(Error::Intervention {
            action: String::new(),
            status: 0,
            data: None,
            rule_id: 0,
        }),
        _ => Err(Error::RuleEngineError),
    }
}

/// Packs headers into the binary format expected by Coraza.
///
/// Format: `[name_len u16][name_bytes][value_len u32][value_bytes] × count`
fn pack_headers(headers: &[(&str, &str)]) -> Vec<u8> {
    let total_size: usize = headers.iter().map(|(n, v)| 2 + n.len() + 4 + v.len()).sum();
    let mut buf = Vec::with_capacity(total_size);
    for (name, value) in headers {
        let name_len = name.len() as u16;
        buf.extend_from_slice(&name_len.to_be_bytes());
        buf.extend_from_slice(name.as_bytes());
        let value_len = value.len() as u32;
        buf.extend_from_slice(&value_len.to_be_bytes());
        buf.extend_from_slice(value.as_bytes());
    }
    buf
}