Skip to main content

smb_server/proto/messages/
error_response.rs

1//! SMB2 ERROR Response (MS-SMB2 §2.2.2).
2//!
3//! Sent in place of any normal response when the server returns a non-zero
4//! NTSTATUS. The SMB2 header carries the NTSTATUS in `channel_sequence_status`;
5//! this body provides extended error context if any.
6
7use binrw::{BinRead, BinWrite, binrw};
8use std::io::Cursor;
9
10use crate::proto::error::ProtoResult;
11
12/// MS-SMB2 §2.2.2 ERROR Response.
13///
14/// `structure_size` is always 9; `byte_count` is the length of `error_data`
15/// when there is no structured error context (the common case). When
16/// `error_context_count > 0`, `error_data` holds a sequence of
17/// [`ErrorContext`] entries (SMB 3.1.1+).
18#[binrw]
19#[brw(little)]
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ErrorResponse {
22    pub structure_size: u16,
23    pub error_context_count: u8,
24    pub reserved: u8,
25    pub byte_count: u32,
26    #[br(parse_with = super::read_buf, args(if byte_count == 0 { 1 } else { byte_count as usize }))]
27    pub error_data: Vec<u8>,
28}
29
30impl ErrorResponse {
31    /// Build a minimal ERROR response body. The NTSTATUS itself goes in the
32    /// SMB2 header.
33    ///
34    /// Per MS-SMB2 §2.2.2 a zero-`byte_count` ERROR response still emits a
35    /// single byte of `error_data` (the field is mandatory, length 1 when
36    /// there is no payload).
37    pub fn status(_ntstatus: u32) -> Self {
38        Self {
39            structure_size: 9,
40            error_context_count: 0,
41            reserved: 0,
42            byte_count: 0,
43            error_data: vec![0],
44        }
45    }
46
47    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
48        let mut c = Cursor::new(buf);
49        Ok(Self::read(&mut c)?)
50    }
51
52    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
53        let mut c = Cursor::new(Vec::new());
54        BinWrite::write(self, &mut c)?;
55        out.extend_from_slice(&c.into_inner());
56        Ok(())
57    }
58}
59
60/// MS-SMB2 §2.2.2.1 ERROR Context Response (3.1.1+).
61#[binrw]
62#[brw(little)]
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct ErrorContext {
65    pub error_data_length: u32,
66    pub error_id: u32,
67    #[br(parse_with = super::read_buf, args(error_data_length as usize))]
68    pub error_context_data: Vec<u8>,
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn round_trips_status_helper() {
77        let r = ErrorResponse::status(0xC000_0022 /* STATUS_ACCESS_DENIED */);
78        let mut buf = Vec::new();
79        r.write_to(&mut buf).unwrap();
80        let decoded = ErrorResponse::parse(&buf).unwrap();
81        assert_eq!(decoded, r);
82        // structure_size, contexts, reserved, bytecount, 1 byte payload = 9 bytes
83        assert_eq!(buf.len(), 9);
84    }
85}