smb-server 0.11.0

SMB2/3 file-sharing server library with pluggable storage backends.
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
//! IOCTL handler (MS-SMB2 3.3.5.15): FSCTL_VALIDATE_NEGOTIATE_INFO,
//! FSCTL_SRV_ENUMERATE_SNAPSHOTS with no snapshots, the resume key, copy and
//! duplicate extents FSCTLs, FSCTL_SET_SPARSE on shares that clone,
//! STATUS_FS_DRIVER_REQUIRED for DFS referrals and STATUS_NOT_SUPPORTED for
//! the rest.

use std::sync::Arc;

use crate::proto::header::{SMB2_HEADER_LEN, Smb2Header};
use crate::proto::messages::{Dialect, FileId, Fsctl, IoctlRequest, IoctlResponse};
use tokio::sync::RwLock;
use tracing::warn;

use crate::conn::state::{Connection, Open, TreeConnect};
use crate::dispatch::HandlerResponse;
use crate::handlers::Outcome;
use crate::handlers::copy;
use crate::handlers::negotiate::{select_dialect, server_capabilities, server_security_mode};
use crate::handlers::shared::{lookup_open, lookup_session_tree};
use crate::ntstatus;
use crate::server::ServerState;
use crate::stream::unsupported;

/// Size of the fixed part of an IOCTL request, before Buffer.
const IOCTL_FIXED_LEN: usize = 56;

/// Size of a VALIDATE_NEGOTIATE_INFO response (MS-SMB2 2.2.32.6).
const VALIDATE_NEGOTIATE_RESPONSE_LEN: u32 = 24;

/// Offset of the response Buffer from the start of the SMB2 header.
const RESPONSE_BUFFER_OFFSET: u32 = 0x70;

pub async fn handle(
    server: &Arc<ServerState>,
    conn: &Arc<Connection>,
    hdr: &Smb2Header,
    body: &[u8],
    retained: usize,
) -> Outcome {
    let (tree, req, open, input) = match check(conn, hdr, body).await {
        Ok(checked) => checked,
        Err(status) => return Outcome::Done(HandlerResponse::err(status)),
    };
    if let Some(open) = &open {
        let call = copy::Call {
            hdr,
            req: &req,
            input,
            retained,
        };
        match req.fsctl() {
            Fsctl::SrvRequestResumeKey | Fsctl::SrvCopychunk | Fsctl::SrvCopychunkWrite => {
                return copy::handle(server, conn, &call, &tree, open).await;
            }
            Fsctl::DuplicateExtentsToFile | Fsctl::DuplicateExtentsToFileEx => {
                return copy::duplicate_extents(conn, &call, &tree, open).await;
            }
            Fsctl::SetSparse => {
                return Outcome::Done(copy::set_sparse(&req, &tree, open).await);
            }
            _ => {}
        }
    }
    Outcome::Done(answer(server, conn, &req, open, input).await)
}

/// Runs the checks every IOCTL gets (MS-SMB2 3.3.5.15). Returns the tree, the
/// request, the open it names (`None` for an FSCTL that names none), and the
/// input buffer.
async fn check<'a>(
    conn: &Arc<Connection>,
    hdr: &Smb2Header,
    body: &'a [u8],
) -> Result<
    (
        Arc<RwLock<TreeConnect>>,
        IoctlRequest,
        Option<Arc<RwLock<Open>>>,
        &'a [u8],
    ),
    u32,
> {
    let tree = lookup_session_tree(conn, hdr).await?;
    let req = IoctlRequest::parse(body).map_err(|_| ntstatus::STATUS_INVALID_PARAMETER)?;
    if req.flags != IoctlRequest::FLAG_IS_FSCTL {
        return Err(ntstatus::STATUS_NOT_SUPPORTED);
    }

    let open = if takes_no_file(req.fsctl()) {
        if req.file_id != FileId::any() {
            return Err(ntstatus::STATUS_INVALID_PARAMETER);
        }
        None
    } else {
        match lookup_open(&tree, req.file_id).await {
            Some(open) => Some(open),
            None => return Err(ntstatus::STATUS_FILE_CLOSED),
        }
    };

    let max_transact = *conn.max_read_size.read().await;
    if req.input_count > max_transact
        || req.max_input_response > max_transact
        || req.max_output_response > max_transact
    {
        return Err(ntstatus::STATUS_INVALID_PARAMETER);
    }
    let input = input_buffer(&req, body).ok_or(ntstatus::STATUS_INVALID_PARAMETER)?;
    Ok((tree, req, open, input))
}

async fn answer(
    server: &Arc<ServerState>,
    conn: &Arc<Connection>,
    req: &IoctlRequest,
    open: Option<Arc<RwLock<Open>>>,
    input: &[u8],
) -> HandlerResponse {
    match req.fsctl() {
        Fsctl::ValidateNegotiateInfo => validate_negotiate_info(server, conn, req, input).await,
        Fsctl::SrvEnumerateSnapshots => {
            if req.max_output_response < 16 {
                return HandlerResponse::err(ntstatus::STATUS_INVALID_PARAMETER);
            }
            let file_id = match open {
                Some(open) => open.read().await.file_id,
                None => req.file_id,
            };
            // SRV_SNAPSHOT_ARRAY with no snapshots: NumberOfSnapShots,
            // NumberOfSnapShotsReturned and SnapShotArraySize all 0.
            response(req.ctl_code, file_id, vec![0u8; 12])
        }
        Fsctl::DfsGetReferrals | Fsctl::DfsGetReferralsEx => {
            HandlerResponse::err(ntstatus::STATUS_FS_DRIVER_REQUIRED)
        }
        _ => {
            let on_stream = match open {
                Some(open) => open.read().await.on_stream,
                None => false,
            };
            HandlerResponse::err(unsupported(on_stream))
        }
    }
}

/// Whether `fsctl` names no open: its FileId must be all 0xFF (MS-SMB2
/// 3.3.5.15).
pub(super) fn takes_no_file(fsctl: Fsctl) -> bool {
    matches!(
        fsctl,
        Fsctl::DfsGetReferrals
            | Fsctl::DfsGetReferralsEx
            | Fsctl::QueryNetworkInterfaceInfo
            | Fsctl::ValidateNegotiateInfo
            | Fsctl::PipeWait
    )
}

/// The request's input buffer, located by InputOffset, or `None` when the
/// offset and count break the rules of MS-SMB2 3.3.5.15.
pub(super) fn input_buffer<'a>(req: &IoctlRequest, body: &'a [u8]) -> Option<&'a [u8]> {
    if req.input_count == 0 {
        return Some(&[]);
    }
    let offset = req.input_offset as usize;
    if offset < SMB2_HEADER_LEN + IOCTL_FIXED_LEN || !offset.is_multiple_of(8) {
        return None;
    }
    let start = offset - SMB2_HEADER_LEN;
    let end = start.checked_add(req.input_count as usize)?;
    body.get(start..end)
}

/// An IOCTL response carrying `output` (MS-SMB2 2.2.32).
pub(super) fn response(ctl_code: u32, file_id: FileId, output: Vec<u8>) -> HandlerResponse {
    let resp = IoctlResponse {
        structure_size: 49,
        reserved: 0,
        ctl_code,
        file_id,
        input_offset: RESPONSE_BUFFER_OFFSET,
        input_count: 0,
        output_offset: RESPONSE_BUFFER_OFFSET,
        output_count: output.len() as u32,
        flags: 0,
        reserved2: 0,
        output,
    };
    let mut buf = Vec::new();
    resp.write_to(&mut buf).expect("IOCTL response encodes");
    HandlerResponse::ok(buf)
}

/// MS-SMB2 3.3.5.15.12. Every mismatch with the NEGOTIATE the client sent
/// closes the connection: it means the negotiation was tampered with.
async fn validate_negotiate_info(
    server: &Arc<ServerState>,
    conn: &Arc<Connection>,
    req: &IoctlRequest,
    input: &[u8],
) -> HandlerResponse {
    let dialect = *conn.dialect.read().await;
    let client = conn
        .client_negotiate
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .clone();
    let terminate = |reason: &str| {
        warn!(
            reason,
            "VALIDATE_NEGOTIATE_INFO failed; closing the connection"
        );
        conn.request_disconnect();
        HandlerResponse::err(ntstatus::STATUS_ACCESS_DENIED)
    };

    let (Some(dialect), Some(client)) = (dialect, client) else {
        return terminate("no negotiated dialect");
    };
    if dialect == Dialect::Smb311 {
        return terminate("not used with SMB 3.1.1");
    }
    if req.max_output_response < VALIDATE_NEGOTIATE_RESPONSE_LEN {
        return terminate("MaxOutputResponse too small");
    }
    let Some(request) = ValidateNegotiateRequest::parse(input) else {
        return HandlerResponse::err(ntstatus::STATUS_INVALID_PARAMETER);
    };
    if request.dialects != client.dialects {
        return terminate("dialects differ");
    }
    if select_dialect(&request.dialects) != Some(dialect) {
        return terminate("dialect differs");
    }
    if request.guid != client.guid {
        return terminate("client GUID differs");
    }
    if request.security_mode != client.security_mode {
        return terminate("security mode differs");
    }
    if request.capabilities != client.capabilities {
        return terminate("capabilities differ");
    }

    let mut out = Vec::with_capacity(VALIDATE_NEGOTIATE_RESPONSE_LEN as usize);
    out.extend_from_slice(&server_capabilities(dialect, client.capabilities).to_le_bytes());
    out.extend_from_slice(conn.server_guid.as_bytes());
    out.extend_from_slice(&server_security_mode(server).to_le_bytes());
    out.extend_from_slice(&dialect.as_u16().to_le_bytes());
    response(Fsctl::VALIDATE_NEGOTIATE_INFO, FileId::any(), out)
}

/// VALIDATE_NEGOTIATE_INFO request (MS-SMB2 2.2.31.4).
struct ValidateNegotiateRequest {
    capabilities: u32,
    guid: [u8; 16],
    security_mode: u16,
    dialects: Vec<u16>,
}

impl ValidateNegotiateRequest {
    fn parse(input: &[u8]) -> Option<Self> {
        let fixed = input.get(..24)?;
        let count = u16::from_le_bytes([fixed[22], fixed[23]]) as usize;
        let list = input.get(24..24 + 2 * count)?;
        Some(Self {
            capabilities: u32::from_le_bytes(fixed[0..4].try_into().ok()?),
            guid: fixed[4..20].try_into().ok()?,
            security_mode: u16::from_le_bytes([fixed[20], fixed[21]]),
            dialects: list
                .chunks_exact(2)
                .map(|d| u16::from_le_bytes([d[0], d[1]]))
                .collect(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::Access;
    use crate::conn::state::Session;
    use crate::handlers::negotiate::ClientNegotiate;
    use crate::proto::auth::ntlm::Identity;
    use crate::proto::header::{Command, HeaderTail};
    use crate::server::ShareBindings;

    const GUID: [u8; 16] = [0xCD; 16];
    const DIALECTS: [u16; 2] = [0x0300, 0x0302];

    async fn connection(dialect: Dialect) -> (Arc<ServerState>, Arc<Connection>) {
        let server = crate::SmbServer::builder()
            .listen("127.0.0.1:0".parse().unwrap())
            .build()
            .expect("build")
            .state();
        let conn = Arc::new(Connection::new(server.config.server_guid, 65536, 65536));
        *conn.dialect.write().await = Some(dialect);
        *conn.client_negotiate.lock().unwrap() = Some(ClientNegotiate {
            capabilities: 0x44,
            security_mode: 0x0001,
            guid: GUID,
            dialects: DIALECTS.to_vec(),
        });
        let session = Session::new(Identity::Anonymous, [0; 16], [0; 16], false, None);
        let tree = TreeConnect::new(1, ShareBindings::ipc(), Access::Read);
        session
            .trees
            .write()
            .await
            .insert(1, Arc::new(RwLock::new(tree)));
        conn.sessions
            .write()
            .await
            .insert(7, Arc::new(RwLock::new(session)));
        (server, conn)
    }

    async fn answer_of(
        server: &Arc<ServerState>,
        conn: &Arc<Connection>,
        body: &[u8],
    ) -> HandlerResponse {
        match handle(server, conn, &header(), body, 0).await {
            Outcome::Done(response) => response,
            Outcome::Pending(_) => panic!("the request waits"),
        }
    }

    fn header() -> Smb2Header {
        Smb2Header {
            credit_charge: 1,
            channel_sequence_status: 0,
            command: Command::Ioctl,
            credit_request_response: 1,
            flags: 0,
            next_command: 0,
            message_id: 5,
            tail: HeaderTail::sync(1),
            session_id: 7,
            signature: [0; 16],
        }
    }

    fn validate_body(caps: u32, guid: [u8; 16], mode: u16, dialects: &[u16], max: u32) -> Vec<u8> {
        let mut input = caps.to_le_bytes().to_vec();
        input.extend_from_slice(&guid);
        input.extend_from_slice(&mode.to_le_bytes());
        input.extend_from_slice(&(dialects.len() as u16).to_le_bytes());
        for d in dialects {
            input.extend_from_slice(&d.to_le_bytes());
        }
        let mut body = Vec::new();
        IoctlRequest {
            structure_size: 57,
            reserved: 0,
            ctl_code: Fsctl::VALIDATE_NEGOTIATE_INFO,
            file_id: FileId::any(),
            input_offset: 0x78,
            input_count: input.len() as u32,
            max_input_response: 0,
            output_offset: 0,
            output_count: 0,
            max_output_response: max,
            flags: IoctlRequest::FLAG_IS_FSCTL,
            reserved2: 0,
            input,
        }
        .write_to(&mut body)
        .unwrap();
        body
    }

    #[tokio::test]
    async fn validate_negotiate_info_mismatch_requests_a_disconnect() {
        let cases = [
            (0x7F, GUID, 0x0001, &DIALECTS[..], 24),
            (0x44, [0xEE; 16], 0x0001, &DIALECTS[..], 24),
            (0x44, GUID, 0x0003, &DIALECTS[..], 24),
            (0x44, GUID, 0x0001, &[0x0300][..], 24),
            (0x44, GUID, 0x0001, &DIALECTS[..], 23),
        ];
        for (caps, guid, mode, dialects, max) in cases {
            let (server, conn) = connection(Dialect::Smb302).await;
            let body = validate_body(caps, guid, mode, dialects, max);
            let resp = answer_of(&server, &conn, &body).await;
            assert_ne!(resp.status, ntstatus::STATUS_SUCCESS);
            assert!(conn.disconnect_requested(), "{caps:x} {mode} {dialects:?}");
        }

        let (server, conn) = connection(Dialect::Smb302).await;
        let body = validate_body(0x44, GUID, 0x0001, &DIALECTS, 24);
        let resp = answer_of(&server, &conn, &body).await;
        assert_eq!(resp.status, ntstatus::STATUS_SUCCESS);
        assert!(!conn.disconnect_requested());
    }

    #[tokio::test]
    async fn validate_negotiate_info_on_smb311_requests_a_disconnect() {
        let (server, conn) = connection(Dialect::Smb311).await;
        let dialects = [0x0300, 0x0302, 0x0311];
        conn.client_negotiate
            .lock()
            .unwrap()
            .as_mut()
            .unwrap()
            .dialects = dialects.to_vec();
        let body = validate_body(0x44, GUID, 0x0001, &dialects, 24);
        answer_of(&server, &conn, &body).await;
        assert!(conn.disconnect_requested());
    }
}