Skip to main content

smb_server/proto/messages/
ioctl.rs

1//! IOCTL Request/Response (MS-SMB2 §2.2.31 / §2.2.32).
2
3use binrw::{BinRead, BinWrite, binrw};
4use std::io::Cursor;
5
6use super::create::FileId;
7use crate::proto::error::ProtoResult;
8
9/// File-system control codes we recognize at the wire layer.
10///
11/// MS-FSCC lists the full set. Unknown codes round-trip via [`Fsctl::Other`].
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Fsctl {
15    /// `FSCTL_VALIDATE_NEGOTIATE_INFO`.
16    ValidateNegotiateInfo,
17    /// `FSCTL_DFS_GET_REFERRALS`.
18    DfsGetReferrals,
19    /// `FSCTL_DFS_GET_REFERRALS_EX`.
20    DfsGetReferralsEx,
21    /// `FSCTL_PIPE_TRANSCEIVE`.
22    PipeTransceive,
23    /// `FSCTL_PIPE_PEEK`.
24    PipePeek,
25    /// `FSCTL_PIPE_WAIT`.
26    PipeWait,
27    /// `FSCTL_LMR_REQUEST_RESILIENCY`.
28    LmrRequestResiliency,
29    /// `FSCTL_QUERY_NETWORK_INTERFACE_INFO`.
30    QueryNetworkInterfaceInfo,
31    /// `FSCTL_SRV_ENUMERATE_SNAPSHOTS`.
32    SrvEnumerateSnapshots,
33    /// `FSCTL_SRV_REQUEST_RESUME_KEY`.
34    SrvRequestResumeKey,
35    /// `FSCTL_SRV_COPYCHUNK`.
36    SrvCopychunk,
37    /// `FSCTL_SRV_COPYCHUNK_WRITE`.
38    SrvCopychunkWrite,
39    /// `FSCTL_SET_SPARSE`.
40    SetSparse,
41    /// `FSCTL_DUPLICATE_EXTENTS_TO_FILE`.
42    DuplicateExtentsToFile,
43    /// `FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX`.
44    DuplicateExtentsToFileEx,
45    /// Anything else.
46    Other(u32),
47}
48
49impl Fsctl {
50    pub const VALIDATE_NEGOTIATE_INFO: u32 = 0x0014_0204;
51    pub const DFS_GET_REFERRALS: u32 = 0x0006_0194;
52    pub const DFS_GET_REFERRALS_EX: u32 = 0x0006_01B0;
53    pub const PIPE_TRANSCEIVE: u32 = 0x0011_C017;
54    pub const PIPE_PEEK: u32 = 0x0011_400C;
55    pub const PIPE_WAIT: u32 = 0x0011_0018;
56    pub const LMR_REQUEST_RESILIENCY: u32 = 0x0014_01D4;
57    pub const QUERY_NETWORK_INTERFACE_INFO: u32 = 0x0014_01FC;
58    pub const SRV_ENUMERATE_SNAPSHOTS: u32 = 0x0014_4064;
59    pub const SRV_REQUEST_RESUME_KEY: u32 = 0x0014_0078;
60    pub const SRV_COPYCHUNK: u32 = 0x0014_40F2;
61    pub const SRV_COPYCHUNK_WRITE: u32 = 0x0014_80F2;
62    pub const SET_SPARSE: u32 = 0x0009_00C4;
63    pub const DUPLICATE_EXTENTS_TO_FILE: u32 = 0x0009_8344;
64    pub const DUPLICATE_EXTENTS_TO_FILE_EX: u32 = 0x0009_83E8;
65
66    pub fn from_u32(code: u32) -> Self {
67        match code {
68            Self::VALIDATE_NEGOTIATE_INFO => Self::ValidateNegotiateInfo,
69            Self::DFS_GET_REFERRALS => Self::DfsGetReferrals,
70            Self::DFS_GET_REFERRALS_EX => Self::DfsGetReferralsEx,
71            Self::PIPE_TRANSCEIVE => Self::PipeTransceive,
72            Self::PIPE_PEEK => Self::PipePeek,
73            Self::PIPE_WAIT => Self::PipeWait,
74            Self::LMR_REQUEST_RESILIENCY => Self::LmrRequestResiliency,
75            Self::QUERY_NETWORK_INTERFACE_INFO => Self::QueryNetworkInterfaceInfo,
76            Self::SRV_ENUMERATE_SNAPSHOTS => Self::SrvEnumerateSnapshots,
77            Self::SRV_REQUEST_RESUME_KEY => Self::SrvRequestResumeKey,
78            Self::SRV_COPYCHUNK => Self::SrvCopychunk,
79            Self::SRV_COPYCHUNK_WRITE => Self::SrvCopychunkWrite,
80            Self::SET_SPARSE => Self::SetSparse,
81            Self::DUPLICATE_EXTENTS_TO_FILE => Self::DuplicateExtentsToFile,
82            Self::DUPLICATE_EXTENTS_TO_FILE_EX => Self::DuplicateExtentsToFileEx,
83            other => Self::Other(other),
84        }
85    }
86
87    pub fn as_u32(self) -> u32 {
88        match self {
89            Self::ValidateNegotiateInfo => Self::VALIDATE_NEGOTIATE_INFO,
90            Self::DfsGetReferrals => Self::DFS_GET_REFERRALS,
91            Self::DfsGetReferralsEx => Self::DFS_GET_REFERRALS_EX,
92            Self::PipeTransceive => Self::PIPE_TRANSCEIVE,
93            Self::PipePeek => Self::PIPE_PEEK,
94            Self::PipeWait => Self::PIPE_WAIT,
95            Self::LmrRequestResiliency => Self::LMR_REQUEST_RESILIENCY,
96            Self::QueryNetworkInterfaceInfo => Self::QUERY_NETWORK_INTERFACE_INFO,
97            Self::SrvEnumerateSnapshots => Self::SRV_ENUMERATE_SNAPSHOTS,
98            Self::SrvRequestResumeKey => Self::SRV_REQUEST_RESUME_KEY,
99            Self::SrvCopychunk => Self::SRV_COPYCHUNK,
100            Self::SrvCopychunkWrite => Self::SRV_COPYCHUNK_WRITE,
101            Self::SetSparse => Self::SET_SPARSE,
102            Self::DuplicateExtentsToFile => Self::DUPLICATE_EXTENTS_TO_FILE,
103            Self::DuplicateExtentsToFileEx => Self::DUPLICATE_EXTENTS_TO_FILE_EX,
104            Self::Other(c) => c,
105        }
106    }
107}
108
109/// SMB2_IOCTL_REQUEST (MS-SMB2 §2.2.31).
110///
111/// `input_offset` and `output_offset` are absolute (from the start of the
112/// SMB2 header). `input` is read immediately after the fixed prefix.
113#[binrw]
114#[brw(little)]
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct IoctlRequest {
117    pub structure_size: u16,
118    pub reserved: u16,
119    pub ctl_code: u32,
120    pub file_id: FileId,
121    pub input_offset: u32,
122    pub input_count: u32,
123    pub max_input_response: u32,
124    pub output_offset: u32,
125    pub output_count: u32,
126    pub max_output_response: u32,
127    pub flags: u32,
128    pub reserved2: u32,
129    #[br(parse_with = super::read_buf, args(input_count as usize))]
130    pub input: Vec<u8>,
131}
132
133impl IoctlRequest {
134    /// Flag: SMB2_0_IOCTL_IS_FSCTL.
135    pub const FLAG_IS_FSCTL: u32 = 0x0000_0001;
136
137    pub fn fsctl(&self) -> Fsctl {
138        Fsctl::from_u32(self.ctl_code)
139    }
140
141    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
142        Ok(Self::read(&mut Cursor::new(buf))?)
143    }
144    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
145        let mut c = Cursor::new(Vec::new());
146        BinWrite::write(self, &mut c)?;
147        out.extend_from_slice(&c.into_inner());
148        Ok(())
149    }
150}
151
152/// SMB2_IOCTL_RESPONSE (MS-SMB2 §2.2.32).
153#[binrw]
154#[brw(little)]
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct IoctlResponse {
157    pub structure_size: u16,
158    pub reserved: u16,
159    pub ctl_code: u32,
160    pub file_id: FileId,
161    pub input_offset: u32,
162    pub input_count: u32,
163    pub output_offset: u32,
164    pub output_count: u32,
165    pub flags: u32,
166    pub reserved2: u32,
167    /// Output buffer immediately following the fixed prefix.
168    #[br(parse_with = super::read_buf, args(output_count as usize))]
169    pub output: Vec<u8>,
170}
171
172impl IoctlResponse {
173    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
174        Ok(Self::read(&mut Cursor::new(buf))?)
175    }
176    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
177        let mut c = Cursor::new(Vec::new());
178        BinWrite::write(self, &mut c)?;
179        out.extend_from_slice(&c.into_inner());
180        Ok(())
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn fsctl_decode_known() {
190        assert_eq!(Fsctl::from_u32(0x0014_0204), Fsctl::ValidateNegotiateInfo);
191        assert_eq!(Fsctl::from_u32(0xDEAD_BEEF), Fsctl::Other(0xDEAD_BEEF));
192        assert_eq!(Fsctl::ValidateNegotiateInfo.as_u32(), 0x0014_0204);
193        assert_eq!(Fsctl::Other(0xDEAD_BEEF).as_u32(), 0xDEAD_BEEF);
194    }
195
196    /// Codes from the MS-SMB2 2.2.31 and MS-FSCC 2.3 CtlCode tables.
197    #[test]
198    fn fsctl_codes_match_the_ctlcode_tables() {
199        for (code, fsctl) in [
200            (0x0006_0194, Fsctl::DfsGetReferrals),
201            (0x0011_0018, Fsctl::PipeWait),
202            (0x0011_C017, Fsctl::PipeTransceive),
203            (0x0014_4064, Fsctl::SrvEnumerateSnapshots),
204            (0x0014_0078, Fsctl::SrvRequestResumeKey),
205            (0x0014_40F2, Fsctl::SrvCopychunk),
206            (0x0014_80F2, Fsctl::SrvCopychunkWrite),
207            (0x0014_01D4, Fsctl::LmrRequestResiliency),
208            (0x0014_01FC, Fsctl::QueryNetworkInterfaceInfo),
209            (0x0014_0204, Fsctl::ValidateNegotiateInfo),
210            (0x0006_01B0, Fsctl::DfsGetReferralsEx),
211            (0x0009_00C4, Fsctl::SetSparse),
212            (0x0009_8344, Fsctl::DuplicateExtentsToFile),
213            (0x0009_83E8, Fsctl::DuplicateExtentsToFileEx),
214        ] {
215            assert_eq!(Fsctl::from_u32(code), fsctl, "0x{code:08X}");
216            assert_eq!(fsctl.as_u32(), code);
217        }
218    }
219
220    #[test]
221    fn request_round_trips() {
222        let r = IoctlRequest {
223            structure_size: 57,
224            reserved: 0,
225            ctl_code: Fsctl::VALIDATE_NEGOTIATE_INFO,
226            file_id: FileId::any(),
227            input_offset: 0x78,
228            input_count: 4,
229            max_input_response: 0,
230            output_offset: 0,
231            output_count: 0,
232            max_output_response: 0x1000,
233            flags: IoctlRequest::FLAG_IS_FSCTL,
234            reserved2: 0,
235            input: vec![0xCA, 0xFE, 0xBA, 0xBE],
236        };
237        let mut buf = Vec::new();
238        r.write_to(&mut buf).unwrap();
239        let decoded = IoctlRequest::parse(&buf).unwrap();
240        assert_eq!(decoded, r);
241        assert_eq!(decoded.fsctl(), Fsctl::ValidateNegotiateInfo);
242    }
243
244    #[test]
245    fn response_round_trips() {
246        let r = IoctlResponse {
247            structure_size: 49,
248            reserved: 0,
249            ctl_code: Fsctl::VALIDATE_NEGOTIATE_INFO,
250            file_id: FileId::any(),
251            input_offset: 0,
252            input_count: 0,
253            output_offset: 0x70,
254            output_count: 4,
255            flags: 0,
256            reserved2: 0,
257            output: vec![1, 2, 3, 4],
258        };
259        let mut buf = Vec::new();
260        r.write_to(&mut buf).unwrap();
261        assert_eq!(IoctlResponse::parse(&buf).unwrap(), r);
262    }
263}