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(count = 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 for the given NTSTATUS.
32    ///
33    /// Per MS-SMB2 §2.2.2 a zero-`byte_count` ERROR response still emits a
34    /// single byte of `error_data` (the field is mandatory, length 1 when
35    /// there is no payload).
36    pub fn status(_ntstatus: u32) -> Self {
37        Self {
38            structure_size: 9,
39            error_context_count: 0,
40            reserved: 0,
41            byte_count: 0,
42            error_data: vec![0],
43        }
44    }
45
46    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
47        let mut c = Cursor::new(buf);
48        Ok(Self::read(&mut c)?)
49    }
50
51    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
52        let mut c = Cursor::new(Vec::new());
53        BinWrite::write(self, &mut c)?;
54        out.extend_from_slice(&c.into_inner());
55        Ok(())
56    }
57}
58
59/// MS-SMB2 §2.2.2.1 ERROR Context Response (3.1.1+).
60#[binrw]
61#[brw(little)]
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct ErrorContext {
64    pub error_data_length: u32,
65    pub error_id: u32,
66    #[br(count = error_data_length as usize)]
67    pub error_context_data: Vec<u8>,
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn round_trips_status_helper() {
76        let r = ErrorResponse::status(0xC000_0022 /* STATUS_ACCESS_DENIED */);
77        let mut buf = Vec::new();
78        r.write_to(&mut buf).unwrap();
79        let decoded = ErrorResponse::parse(&buf).unwrap();
80        assert_eq!(decoded, r);
81        // structure_size, contexts, reserved, bytecount, 1 byte payload = 9 bytes
82        assert_eq!(buf.len(), 9);
83    }
84}