1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
5 */
6
7 #include <crypto/utils.h>
8 #include <linux/inetdevice.h>
9 #include <net/addrconf.h>
10 #include <linux/syscalls.h>
11 #include <linux/namei.h>
12 #include <linux/fs_struct.h>
13 #include <linux/statfs.h>
14 #include <linux/ethtool.h>
15 #include <linux/falloc.h>
16 #include <linux/mount.h>
17 #include <linux/filelock.h>
18 #include <linux/fileattr.h>
19 #include <linux/timekeeping.h>
20 #include <linux/unaligned.h>
21
22 #include "glob.h"
23 #include "../common/smbfsctl.h"
24 #include "oplock.h"
25 #include "smbacl.h"
26
27 #include "auth.h"
28 #include "asn1.h"
29 #include "connection.h"
30 #include "transport_ipc.h"
31 #include "transport_rdma.h"
32 #include "vfs.h"
33 #include "vfs_cache.h"
34 #include "misc.h"
35
36 #include "server.h"
37 #include "smb_common.h"
38 #include "../common/smb2status.h"
39 #include "ksmbd_work.h"
40 #include "mgmt/user_config.h"
41 #include "mgmt/share_config.h"
42 #include "mgmt/tree_connect.h"
43 #include "mgmt/user_session.h"
44 #include "mgmt/ksmbd_ida.h"
45 #include "ndr.h"
46 #include "stats.h"
47 #include "transport_tcp.h"
48 #include "compress.h"
49
__wbuf(struct ksmbd_work * work,void ** req,void ** rsp)50 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
51 {
52 if (work->next_smb2_rcv_hdr_off) {
53 *req = ksmbd_req_buf_next(work);
54 *rsp = ksmbd_resp_buf_next(work);
55 } else {
56 *req = smb_get_msg(work->request_buf);
57 *rsp = smb_get_msg(work->response_buf);
58 }
59 }
60
61 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv);
62 static void smb2_notify_cancel_fn(void **argv);
63 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work);
64
65 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
66
67 #define SMB2_CREATE_FILE_ATTRIBUTE_MASK \
68 (FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \
69 FILE_ATTRIBUTE_NO_SCRUB_DATA))
70
71 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */
72 #define KSMBD_WRITE_TIME_RESOLUTION (15ULL * 10000)
73
74 /* MAXFILESIZE in [MS-FSA] 2.1.5.3 Server Requests a Write. */
75 #define SMB2_MAX_FILE_SIZE 0xfffffff0000ULL
76
lookup_chann_list(struct ksmbd_session * sess,struct ksmbd_conn * conn)77 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 {
79 struct channel *chann;
80
81 down_read(&sess->chann_lock);
82 chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
83 up_read(&sess->chann_lock);
84
85 return chann;
86 }
87
88 #define KSMBD_MAX_CHANNELS 32
89
register_session_channel(struct ksmbd_session * sess,struct ksmbd_conn * conn,const char * sess_key)90 static int register_session_channel(struct ksmbd_session *sess,
91 struct ksmbd_conn *conn,
92 const char *sess_key)
93 {
94 struct channel *chann, *old;
95 unsigned long index;
96 unsigned int count = 0;
97 int rc = 0;
98
99 down_write(&sess->chann_lock);
100 if (xa_load(&sess->ksmbd_chann_list, (long)conn))
101 goto out;
102
103 xa_for_each(&sess->ksmbd_chann_list, index, chann)
104 count++;
105 if (count >= KSMBD_MAX_CHANNELS) {
106 rc = -ENOSPC;
107 goto out;
108 }
109
110 chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
111 if (!chann) {
112 rc = -ENOMEM;
113 goto out;
114 }
115
116 chann->conn = conn;
117 memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
118 old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
119 KSMBD_DEFAULT_GFP);
120 if (xa_is_err(old)) {
121 kfree_sensitive(chann);
122 rc = xa_err(old);
123 }
124 out:
125 up_write(&sess->chann_lock);
126 return rc;
127 }
128
129 /**
130 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
131 * @work: smb work
132 *
133 * Return: 0 if there is a tree connection matched or these are
134 * skipable commands, otherwise error
135 */
smb2_get_ksmbd_tcon(struct ksmbd_work * work)136 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
137 {
138 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
139 unsigned int cmd = le16_to_cpu(req_hdr->Command);
140 unsigned int tree_id;
141
142 if (cmd == SMB2_TREE_CONNECT_HE ||
143 cmd == SMB2_CANCEL_HE ||
144 cmd == SMB2_LOGOFF_HE) {
145 ksmbd_debug(SMB, "skip to check tree connect request\n");
146 return 0;
147 }
148
149 if (xa_empty(&work->sess->tree_conns)) {
150 ksmbd_debug(SMB, "NO tree connected\n");
151 return -ENOENT;
152 }
153
154 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
155
156 /*
157 * If request is not the first in Compound request,
158 * Just validate tree id in header with work->tcon->id.
159 */
160 if (work->next_smb2_rcv_hdr_off) {
161 if (!work->tcon) {
162 pr_err("The first operation in the compound does not have tcon\n");
163 return -EINVAL;
164 }
165 if (work->tcon->t_state != TREE_CONNECTED)
166 return -ENOENT;
167 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
168 pr_err("tree id(%u) is different with id(%u) in first operation\n",
169 tree_id, work->tcon->id);
170 return -EINVAL;
171 }
172 return 1;
173 }
174
175 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
176 if (!work->tcon) {
177 pr_err("Invalid tid %d\n", tree_id);
178 return -ENOENT;
179 }
180
181 return 1;
182 }
183
184 /**
185 * smb2_set_err_rsp() - set error response code on smb response
186 * @work: smb work containing response buffer
187 */
smb2_set_err_rsp(struct ksmbd_work * work)188 void smb2_set_err_rsp(struct ksmbd_work *work)
189 {
190 struct smb2_err_rsp *err_rsp;
191
192 if (work->next_smb2_rcv_hdr_off)
193 err_rsp = ksmbd_resp_buf_next(work);
194 else
195 err_rsp = smb_get_msg(work->response_buf);
196
197 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
198 int err;
199
200 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
201 err_rsp->ErrorContextCount = 0;
202 err_rsp->Reserved = 0;
203 err_rsp->ByteCount = 0;
204 err_rsp->ErrorData[0] = 0;
205 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
206 __SMB2_HEADER_STRUCTURE_SIZE +
207 SMB2_ERROR_STRUCTURE_SIZE2);
208 if (err)
209 work->send_no_response = 1;
210 }
211 }
212
213 /**
214 * is_smb2_neg_cmd() - is it smb2 negotiation command
215 * @work: smb work containing smb header
216 *
217 * Return: true if smb2 negotiation command, otherwise false
218 */
is_smb2_neg_cmd(struct ksmbd_work * work)219 bool is_smb2_neg_cmd(struct ksmbd_work *work)
220 {
221 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
222
223 /* is it SMB2 header ? */
224 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
225 return false;
226
227 /* make sure it is request not response message */
228 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
229 return false;
230
231 if (hdr->Command != SMB2_NEGOTIATE)
232 return false;
233
234 return true;
235 }
236
237 /**
238 * is_smb2_rsp() - is it smb2 response
239 * @work: smb work containing smb response buffer
240 *
241 * Return: true if smb2 response, otherwise false
242 */
is_smb2_rsp(struct ksmbd_work * work)243 bool is_smb2_rsp(struct ksmbd_work *work)
244 {
245 struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
246
247 /* is it SMB2 header ? */
248 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
249 return false;
250
251 /* make sure it is response not request message */
252 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
253 return false;
254
255 return true;
256 }
257
258 /**
259 * get_smb2_cmd_val() - get smb command code from smb header
260 * @work: smb work containing smb request buffer
261 *
262 * Return: smb2 request command value
263 */
get_smb2_cmd_val(struct ksmbd_work * work)264 u16 get_smb2_cmd_val(struct ksmbd_work *work)
265 {
266 struct smb2_hdr *rcv_hdr;
267
268 if (work->next_smb2_rcv_hdr_off)
269 rcv_hdr = ksmbd_req_buf_next(work);
270 else
271 rcv_hdr = smb_get_msg(work->request_buf);
272 return le16_to_cpu(rcv_hdr->Command);
273 }
274
275 /**
276 * set_smb2_rsp_status() - set error response code on smb2 header
277 * @work: smb work containing response buffer
278 * @err: error response code
279 */
set_smb2_rsp_status(struct ksmbd_work * work,__le32 err)280 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
281 {
282 struct smb2_hdr *rsp_hdr;
283
284 if (work->next_smb2_rcv_hdr_off) {
285 rsp_hdr = ksmbd_resp_buf_next(work);
286 rsp_hdr->Status = err;
287 smb2_set_err_rsp(work);
288 return;
289 }
290
291 rsp_hdr = smb_get_msg(work->response_buf);
292 rsp_hdr->Status = err;
293
294 work->iov_idx = 0;
295 work->iov_cnt = 0;
296 work->next_smb2_rcv_hdr_off = 0;
297 smb2_set_err_rsp(work);
298 }
299
300 /**
301 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
302 * @work: smb work containing smb request buffer
303 *
304 * smb2 negotiate response is sent in reply of smb1 negotiate command for
305 * dialect auto-negotiation.
306 */
init_smb2_neg_rsp(struct ksmbd_work * work)307 int init_smb2_neg_rsp(struct ksmbd_work *work)
308 {
309 struct smb2_hdr *rsp_hdr;
310 struct smb2_negotiate_rsp *rsp;
311 struct ksmbd_conn *conn = work->conn;
312 int err;
313
314 rsp_hdr = smb_get_msg(work->response_buf);
315 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
316 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
317 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
318 rsp_hdr->CreditRequest = cpu_to_le16(2);
319 rsp_hdr->Command = SMB2_NEGOTIATE;
320 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
321 rsp_hdr->NextCommand = 0;
322 rsp_hdr->MessageId = 0;
323 rsp_hdr->Id.SyncId.ProcessId = 0;
324 rsp_hdr->Id.SyncId.TreeId = 0;
325 rsp_hdr->SessionId = 0;
326 memset(rsp_hdr->Signature, 0, 16);
327
328 rsp = smb_get_msg(work->response_buf);
329
330 WARN_ON(ksmbd_conn_good(conn));
331
332 rsp->StructureSize = cpu_to_le16(65);
333 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
334 rsp->DialectRevision = cpu_to_le16(conn->dialect);
335 /* Not setting conn guid rsp->ServerGUID, as it
336 * not used by client for identifying connection
337 */
338 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
339 /* Default Max Message Size till SMB2.0, 64K*/
340 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
341 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
342 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
343
344 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
345 rsp->ServerStartTime = 0;
346
347 rsp->SecurityBufferOffset = cpu_to_le16(128);
348 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
349 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
350 le16_to_cpu(rsp->SecurityBufferOffset));
351 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
352 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
353 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
354 err = ksmbd_iov_pin_rsp(work, rsp,
355 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
356 if (err)
357 return err;
358 conn->use_spnego = true;
359
360 ksmbd_conn_set_need_negotiate(conn);
361 return 0;
362 }
363
364 /**
365 * smb2_set_rsp_credits() - set number of credits in response buffer
366 * @work: smb work containing smb response buffer
367 */
smb2_set_rsp_credits(struct ksmbd_work * work)368 int smb2_set_rsp_credits(struct ksmbd_work *work)
369 {
370 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
371 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
372 struct ksmbd_conn *conn = work->conn;
373 unsigned short credits_requested, aux_max;
374 unsigned short credit_charge, credits_granted = 0;
375 u64 window_room, i;
376
377 if (work->send_no_response)
378 return 0;
379
380 hdr->CreditCharge = req_hdr->CreditCharge;
381
382 if (conn->total_credits > conn->vals->max_credits) {
383 hdr->CreditRequest = 0;
384 pr_err("Total credits overflow: %d\n", conn->total_credits);
385 return -EINVAL;
386 }
387
388 credit_charge = max_t(unsigned short,
389 le16_to_cpu(req_hdr->CreditCharge), 1);
390 if (credit_charge > conn->total_credits) {
391 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
392 credit_charge, conn->total_credits);
393 return -EINVAL;
394 }
395
396 conn->total_credits -= credit_charge;
397 conn->outstanding_credits -= credit_charge;
398 work->credit_charge = 0;
399 credits_requested = max_t(unsigned short,
400 le16_to_cpu(req_hdr->CreditRequest), 1);
401
402 /* according to smb2.credits smbtorture, Windows server
403 * 2016 or later grant up to 8192 credits at once.
404 *
405 * TODO: Need to adjuct CreditRequest value according to
406 * current cpu load
407 */
408 if (hdr->Command == SMB2_NEGOTIATE)
409 aux_max = 1;
410 else
411 aux_max = conn->vals->max_credits - conn->total_credits;
412
413 /*
414 * The command sequence window must not grow beyond
415 * KSMBD_CMD_SEQ_WINDOW sequence numbers ahead of the oldest one still
416 * outstanding. Cap the grant by the room left in the window so that
417 * credits are withheld until the client consumes the low end (and so
418 * that seq_bitmap stays usable as a ring).
419 */
420 window_room = conn->seq_low + KSMBD_CMD_SEQ_WINDOW - conn->seq_high;
421 aux_max = min_t(unsigned short, aux_max, window_room);
422 credits_granted = min_t(unsigned short, credits_requested, aux_max);
423
424 conn->total_credits += credits_granted;
425 work->credits_granted += credits_granted;
426
427 /* Extend the sequence window to cover the newly granted credits. */
428 for (i = conn->seq_high; i < conn->seq_high + credits_granted; i++)
429 __set_bit(i & (KSMBD_CMD_SEQ_WINDOW - 1), conn->seq_bitmap);
430 conn->seq_high += credits_granted;
431
432 if (!req_hdr->NextCommand) {
433 /* Update CreditRequest in last request */
434 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
435 }
436 ksmbd_debug(SMB,
437 "credits: requested[%d] granted[%d] total_granted[%d]\n",
438 credits_requested, credits_granted,
439 conn->total_credits);
440 return 0;
441 }
442
443 /**
444 * init_chained_smb2_rsp() - initialize smb2 chained response
445 * @work: smb work containing smb response buffer
446 */
init_chained_smb2_rsp(struct ksmbd_work * work)447 static void init_chained_smb2_rsp(struct ksmbd_work *work)
448 {
449 struct smb2_hdr *req = ksmbd_req_buf_next(work);
450 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
451 struct smb2_hdr *rsp_hdr;
452 struct smb2_hdr *rcv_hdr;
453 int next_hdr_offset = 0;
454 int len, new_len;
455
456 /* Len of this response = updated RFC len - offset of previous cmd
457 * in the compound rsp
458 */
459
460 /* Storing the current local FID which may be needed by subsequent
461 * command in the compound request
462 */
463 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
464 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
465 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
466 work->compound_sid = le64_to_cpu(rsp->SessionId);
467 work->compound_status = STATUS_SUCCESS;
468 } else if ((req->Command == SMB2_FLUSH ||
469 req->Command == SMB2_READ ||
470 req->Command == SMB2_WRITE) &&
471 rsp->Status == STATUS_SUCCESS) {
472 u64 volatile_id = KSMBD_NO_FID;
473 u64 persistent_id = KSMBD_NO_FID;
474
475 if (req->Command == SMB2_FLUSH) {
476 struct smb2_flush_req *flush_req =
477 (struct smb2_flush_req *)req;
478
479 volatile_id = flush_req->VolatileFileId;
480 persistent_id = flush_req->PersistentFileId;
481 } else if (req->Command == SMB2_READ) {
482 struct smb2_read_req *read_req =
483 (struct smb2_read_req *)req;
484
485 volatile_id = read_req->VolatileFileId;
486 persistent_id = read_req->PersistentFileId;
487 } else {
488 struct smb2_write_req *write_req =
489 (struct smb2_write_req *)req;
490
491 volatile_id = write_req->VolatileFileId;
492 persistent_id = write_req->PersistentFileId;
493 }
494
495 if (has_file_id(volatile_id)) {
496 work->compound_fid = volatile_id;
497 work->compound_pfid = persistent_id;
498 work->compound_sid = le64_to_cpu(rsp->SessionId);
499 work->compound_status = STATUS_SUCCESS;
500 }
501 } else if (req->Command == SMB2_CREATE) {
502 work->compound_fid = KSMBD_NO_FID;
503 work->compound_pfid = KSMBD_NO_FID;
504 work->compound_sid = le64_to_cpu(rsp->SessionId);
505 work->compound_status = rsp->Status;
506 } else if (rsp->Status != STATUS_SUCCESS) {
507 work->compound_sid = le64_to_cpu(rsp->SessionId);
508 /*
509 * Only carry the failed status forward when the failing command
510 * was itself part of the related chain. An unrelated command
511 * that fails (e.g. a standalone request with a bad session id)
512 * must not seed the status for a following related command,
513 * which has to be evaluated on its own (and may legitimately
514 * fail with a different status such as INVALID_PARAMETER). The
515 * compound session id is still tracked so a following related
516 * command can validate it.
517 */
518 if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)
519 work->compound_status = rsp->Status;
520 }
521
522 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
523 next_hdr_offset = le32_to_cpu(req->NextCommand);
524
525 new_len = ALIGN(len, 8);
526 work->iov[work->iov_idx].iov_len += (new_len - len);
527 inc_rfc1001_len(work->response_buf, new_len - len);
528 rsp->NextCommand = cpu_to_le32(new_len);
529
530 work->next_smb2_rcv_hdr_off += next_hdr_offset;
531 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
532 work->next_smb2_rsp_hdr_off += new_len;
533 ksmbd_debug(SMB,
534 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
535 new_len, work->next_smb2_rcv_hdr_off,
536 work->next_smb2_rsp_hdr_off);
537
538 rsp_hdr = ksmbd_resp_buf_next(work);
539 rcv_hdr = ksmbd_req_buf_next(work);
540
541 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
542 ksmbd_debug(SMB, "related flag should be set\n");
543 work->compound_fid = KSMBD_NO_FID;
544 work->compound_pfid = KSMBD_NO_FID;
545 work->compound_status = STATUS_SUCCESS;
546 }
547 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
548 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
549 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
550 rsp_hdr->Command = rcv_hdr->Command;
551
552 /*
553 * Message is response. We don't grant oplock yet.
554 */
555 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
556 SMB2_FLAGS_RELATED_OPERATIONS);
557 if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
558 rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
559 rsp_hdr->NextCommand = 0;
560 rsp_hdr->MessageId = rcv_hdr->MessageId;
561 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
562 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
563 rsp_hdr->SessionId = rcv_hdr->SessionId;
564 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
565 }
566
smb2_compound_has_failed(struct ksmbd_work * work,struct smb2_hdr * rsp)567 static bool smb2_compound_has_failed(struct ksmbd_work *work,
568 struct smb2_hdr *rsp)
569 {
570 if (!work->next_smb2_rcv_hdr_off ||
571 has_file_id(work->compound_fid) ||
572 work->compound_status == STATUS_SUCCESS)
573 return false;
574
575 rsp->Status = work->compound_status;
576 smb2_set_err_rsp(work);
577 return true;
578 }
579
580 /**
581 * is_chained_smb2_message() - check for chained command
582 * @work: smb work containing smb request buffer
583 *
584 * Return: true if chained request, otherwise false
585 */
is_chained_smb2_message(struct ksmbd_work * work)586 bool is_chained_smb2_message(struct ksmbd_work *work)
587 {
588 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
589 unsigned int len, next_cmd;
590
591 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
592 return false;
593
594 hdr = ksmbd_req_buf_next(work);
595 next_cmd = le32_to_cpu(hdr->NextCommand);
596 if (next_cmd > 0) {
597 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
598 __SMB2_HEADER_STRUCTURE_SIZE >
599 get_rfc1002_len(work->request_buf)) {
600 pr_err("next command(%u) offset exceeds smb msg size\n",
601 next_cmd);
602 return false;
603 }
604
605 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
606 work->response_sz) {
607 pr_err("next response offset exceeds response buffer size\n");
608 return false;
609 }
610
611 ksmbd_debug(SMB, "got SMB2 chained command\n");
612 init_chained_smb2_rsp(work);
613 return true;
614 } else if (work->next_smb2_rcv_hdr_off) {
615 /*
616 * This is last request in chained command,
617 * align response to 8 byte
618 */
619 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
620 len = len - get_rfc1002_len(work->response_buf);
621 if (len) {
622 ksmbd_debug(SMB, "padding len %u\n", len);
623 work->iov[work->iov_idx].iov_len += len;
624 inc_rfc1001_len(work->response_buf, len);
625 }
626 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
627 }
628 return false;
629 }
630
631 /**
632 * init_smb2_rsp_hdr() - initialize smb2 response
633 * @work: smb work containing smb request buffer
634 *
635 * Return: 0
636 */
init_smb2_rsp_hdr(struct ksmbd_work * work)637 int init_smb2_rsp_hdr(struct ksmbd_work *work)
638 {
639 struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
640 struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
641
642 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
643 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
644 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
645 rsp_hdr->Command = rcv_hdr->Command;
646
647 /*
648 * Message is response. We don't grant oplock yet.
649 */
650 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
651 if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
652 rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
653 rsp_hdr->NextCommand = 0;
654 rsp_hdr->MessageId = rcv_hdr->MessageId;
655 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
656 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
657 rsp_hdr->SessionId = rcv_hdr->SessionId;
658 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
659
660 return 0;
661 }
662
smb3_hdr_channel_sequence(struct smb2_hdr * hdr)663 static __le16 smb3_hdr_channel_sequence(struct smb2_hdr *hdr)
664 {
665 return ((struct smb3_hdr_req *)hdr)->ChannelSequence;
666 }
667
smb3_hdr_replay(struct smb2_hdr * hdr)668 static bool smb3_hdr_replay(struct smb2_hdr *hdr)
669 {
670 return hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION;
671 }
672
smb3_verify_channel_sequence(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_hdr * hdr,bool allow_stale)673 static int smb3_verify_channel_sequence(struct ksmbd_work *work,
674 struct ksmbd_file *fp,
675 struct smb2_hdr *hdr,
676 bool allow_stale)
677 {
678 __le16 chseq_le;
679 u16 chseq, old_chseq;
680 int ret = 0;
681
682 if (work->conn->dialect < SMB30_PROT_ID)
683 return 0;
684
685 chseq_le = smb3_hdr_channel_sequence(hdr);
686 chseq = le16_to_cpu(chseq_le);
687
688 spin_lock(&fp->f_lock);
689 old_chseq = le16_to_cpu(fp->channel_sequence);
690 if (smb3_hdr_replay(hdr)) {
691 if (chseq == old_chseq && fp->outstanding_pre_requests == 0) {
692 fp->outstanding_requests++;
693 } else if ((u16)(chseq - old_chseq) <= 0x7fff &&
694 fp->outstanding_pre_requests == 0) {
695 fp->outstanding_pre_requests += fp->outstanding_requests;
696 fp->outstanding_requests = 1;
697 fp->channel_sequence = chseq_le;
698 } else if (allow_stale) {
699 fp->outstanding_pre_requests++;
700 } else {
701 ret = -EAGAIN;
702 }
703 } else {
704 if (chseq == old_chseq) {
705 fp->outstanding_requests++;
706 } else if ((u16)(chseq - old_chseq) <= 0x7fff) {
707 fp->outstanding_pre_requests += fp->outstanding_requests;
708 fp->outstanding_requests = 1;
709 fp->channel_sequence = chseq_le;
710 } else if (allow_stale) {
711 fp->outstanding_pre_requests++;
712 } else {
713 ret = -EAGAIN;
714 }
715 }
716 spin_unlock(&fp->f_lock);
717
718 return ret;
719 }
720
smb3_complete_channel_sequence(struct ksmbd_work * work,struct ksmbd_file * fp,__le16 chseq_le)721 static void smb3_complete_channel_sequence(struct ksmbd_work *work,
722 struct ksmbd_file *fp,
723 __le16 chseq_le)
724 {
725 u16 chseq;
726
727 if (work->conn->dialect < SMB30_PROT_ID)
728 return;
729
730 chseq = le16_to_cpu(chseq_le);
731
732 spin_lock(&fp->f_lock);
733 if (chseq == le16_to_cpu(fp->channel_sequence)) {
734 if (fp->outstanding_requests)
735 fp->outstanding_requests--;
736 } else {
737 if (fp->outstanding_pre_requests)
738 fp->outstanding_pre_requests--;
739 }
740 spin_unlock(&fp->f_lock);
741 }
742
smb2_set_request_open(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_hdr * hdr,bool verify_chseq,bool allow_stale_chseq)743 static int smb2_set_request_open(struct ksmbd_work *work, struct ksmbd_file *fp,
744 struct smb2_hdr *hdr, bool verify_chseq,
745 bool allow_stale_chseq)
746 {
747 struct ksmbd_file *open;
748 int ret;
749
750 smb2_complete_request_open(work);
751
752 open = ksmbd_file_get(fp);
753 if (!open)
754 return -ESTALE;
755
756 if (verify_chseq) {
757 ret = smb3_verify_channel_sequence(work, fp, hdr,
758 allow_stale_chseq);
759 if (ret) {
760 ksmbd_fd_put(work, open);
761 return ret;
762 }
763 work->request_open_chseq_tracked = true;
764 }
765
766 work->request_open = open;
767 work->request_open_chseq = smb3_hdr_channel_sequence(hdr);
768 return 0;
769 }
770
smb2_complete_request_open(struct ksmbd_work * work)771 void smb2_complete_request_open(struct ksmbd_work *work)
772 {
773 struct ksmbd_file *open = work->request_open;
774
775 if (!open)
776 return;
777
778 if (work->request_open_chseq_tracked)
779 smb3_complete_channel_sequence(work, open,
780 work->request_open_chseq);
781
782 work->request_open = NULL;
783 work->request_open_chseq_tracked = false;
784 ksmbd_fd_put(work, open);
785 }
786
smb2_lock_sequence_applicable(struct ksmbd_work * work,struct ksmbd_file * fp)787 static bool smb2_lock_sequence_applicable(struct ksmbd_work *work,
788 struct ksmbd_file *fp)
789 {
790 return fp->is_resilient || fp->is_durable || fp->is_persistent ||
791 (work->conn->dialect >= SMB30_PROT_ID &&
792 (work->conn->vals->req_capabilities &
793 SMB2_GLOBAL_CAP_MULTI_CHANNEL));
794 }
795
smb2_verify_lock_sequence(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_lock_req * req)796 static bool smb2_verify_lock_sequence(struct ksmbd_work *work,
797 struct ksmbd_file *fp,
798 struct smb2_lock_req *req)
799 {
800 u32 val, index;
801 u8 sequence;
802 bool replay = false;
803
804 if (work->conn->dialect == SMB20_PROT_ID ||
805 !smb2_lock_sequence_applicable(work, fp))
806 return false;
807
808 val = le32_to_cpu(req->LockSequenceNumber);
809 sequence = val & 0xf;
810 index = val >> 4;
811 if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
812 return false;
813
814 spin_lock(&fp->f_lock);
815 if (fp->lock_seq[index - 1].valid) {
816 if (fp->lock_seq[index - 1].sequence == sequence)
817 replay = true;
818 else
819 fp->lock_seq[index - 1].valid = false;
820 }
821 spin_unlock(&fp->f_lock);
822
823 return replay;
824 }
825
smb2_update_lock_sequence(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_lock_req * req)826 static void smb2_update_lock_sequence(struct ksmbd_work *work,
827 struct ksmbd_file *fp,
828 struct smb2_lock_req *req)
829 {
830 u32 val, index;
831 u8 sequence;
832
833 if (work->conn->dialect == SMB20_PROT_ID ||
834 !smb2_lock_sequence_applicable(work, fp))
835 return;
836
837 val = le32_to_cpu(req->LockSequenceNumber);
838 sequence = val & 0xf;
839 index = val >> 4;
840 if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
841 return;
842
843 spin_lock(&fp->f_lock);
844 fp->lock_seq[index - 1].valid = true;
845 fp->lock_seq[index - 1].sequence = sequence;
846 spin_unlock(&fp->f_lock);
847 }
848
849 /**
850 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
851 * @work: smb work containing smb request buffer
852 *
853 * Return: 0 on success, otherwise error
854 */
smb2_allocate_rsp_buf(struct ksmbd_work * work)855 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
856 {
857 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
858 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
859 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
860 size_t sz = small_sz;
861 int cmd = le16_to_cpu(hdr->Command);
862
863 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
864 sz = large_sz;
865
866 if (cmd == SMB2_QUERY_INFO_HE) {
867 struct smb2_query_info_req *req;
868
869 if (get_rfc1002_len(work->request_buf) <
870 offsetof(struct smb2_query_info_req, OutputBufferLength))
871 return -EINVAL;
872
873 req = smb_get_msg(work->request_buf);
874 if ((req->InfoType == SMB2_O_INFO_FILE &&
875 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
876 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
877 req->InfoType == SMB2_O_INFO_SECURITY)
878 sz = large_sz;
879 }
880
881 /* allocate large response buf for chained commands */
882 if (le32_to_cpu(hdr->NextCommand) > 0)
883 sz = large_sz;
884
885 work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
886 if (!work->response_buf)
887 return -ENOMEM;
888
889 work->response_sz = sz;
890 return 0;
891 }
892
smb2_session_expired_cmd_allowed(struct ksmbd_work * work,unsigned int cmd)893 static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work,
894 unsigned int cmd)
895 {
896 struct smb2_lock_req *req;
897 unsigned int len, lock_count, i;
898
899 if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE ||
900 cmd == SMB2_LOGOFF_HE)
901 return true;
902 if (cmd != SMB2_LOCK_HE)
903 return false;
904
905 req = ksmbd_req_buf_next(work);
906 if (req->hdr.NextCommand)
907 len = le32_to_cpu(req->hdr.NextCommand);
908 else {
909 len = get_rfc1002_len(work->request_buf);
910 if (len < work->next_smb2_rcv_hdr_off)
911 return false;
912 len -= work->next_smb2_rcv_hdr_off;
913 }
914
915 lock_count = le16_to_cpu(req->LockCount);
916 if (!lock_count || len < offsetof(struct smb2_lock_req, locks) ||
917 lock_count > (len - offsetof(struct smb2_lock_req, locks)) /
918 sizeof(struct smb2_lock_element))
919 return false;
920
921 for (i = 0; i < lock_count; i++) {
922 if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK)
923 return false;
924 }
925 return true;
926 }
927
smb2_session_kerberos_expired(struct ksmbd_session * sess)928 static bool smb2_session_kerberos_expired(struct ksmbd_session *sess)
929 {
930 return sess->kerberos_expiry &&
931 ktime_get_real_seconds() >= sess->kerberos_expiry;
932 }
933
934 /**
935 * smb2_check_user_session() - check for valid session for a user
936 * @work: smb work containing smb request buffer
937 *
938 * Return: 0 on success, otherwise error
939 */
smb2_check_user_session(struct ksmbd_work * work)940 int smb2_check_user_session(struct ksmbd_work *work)
941 {
942 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
943 struct ksmbd_conn *conn = work->conn;
944 unsigned int cmd = le16_to_cpu(req_hdr->Command);
945 unsigned long long sess_id;
946
947 /*
948 * SMB2_NEGOTIATE and SMB2_SESSION_SETUP do not require a session id.
949 * SMB2_ECHO may omit it, but an echo carrying a session id still needs
950 * the session attached to work so that its signature can be checked and
951 * the response can be signed, including after Kerberos expiry.
952 */
953 if (cmd == SMB2_NEGOTIATE_HE || cmd == SMB2_SESSION_SETUP_HE)
954 return 0;
955
956 sess_id = le64_to_cpu(req_hdr->SessionId);
957 if (cmd == SMB2_ECHO_HE) {
958 /*
959 * ECHO remains valid without a live session, including after
960 * LOGOFF. Attach an existing session only to authenticate a signed
961 * ECHO and sign its response; a stale SessionId is not an error.
962 */
963 if (!work->next_smb2_rcv_hdr_off && sess_id)
964 work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
965 if (work->sess) {
966 if (smb2_session_kerberos_expired(work->sess)) {
967 work->sess->state = SMB2_SESSION_EXPIRED;
968 } else if (work->sess->state != SMB2_SESSION_VALID) {
969 ksmbd_user_session_put(work->sess);
970 work->sess = NULL;
971 }
972 }
973 return 0;
974 }
975
976 if (!ksmbd_conn_good(conn))
977 return -EIO;
978
979 /*
980 * If request is not the first in Compound request,
981 * Just validate session id in header with work->sess->id.
982 */
983 if (work->next_smb2_rcv_hdr_off) {
984 if (!work->sess) {
985 pr_err("The first operation in the compound does not have sess\n");
986 return -EINVAL;
987 }
988 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
989 pr_err("session id(%llu) is different with the first operation(%lld)\n",
990 sess_id, work->sess->id);
991 return -EINVAL;
992 }
993 if (smb2_session_kerberos_expired(work->sess))
994 work->sess->state = SMB2_SESSION_EXPIRED;
995 if (work->sess->state != SMB2_SESSION_VALID) {
996 pr_err("compound request on a non-valid session (state %d)\n",
997 work->sess->state);
998 if (smb2_session_kerberos_expired(work->sess) &&
999 smb2_session_expired_cmd_allowed(work, cmd))
1000 return 1;
1001 return smb2_session_kerberos_expired(work->sess) ?
1002 -EKEYEXPIRED : -EINVAL;
1003 }
1004 return 1;
1005 }
1006
1007 /* Check for validity of user session */
1008 work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
1009 if (work->sess) {
1010 if (smb2_session_kerberos_expired(work->sess)) {
1011 work->sess->state = SMB2_SESSION_EXPIRED;
1012 return smb2_session_expired_cmd_allowed(work, cmd) ?
1013 1 : -EKEYEXPIRED;
1014 }
1015 if (work->sess->state != SMB2_SESSION_VALID) {
1016 /*
1017 * Keep the reference for an encrypted request so the caller can
1018 * return STATUS_USER_SESSION_DELETED encrypted with the old key.
1019 */
1020 if (work->encrypted &&
1021 work->sess->state == SMB2_SESSION_EXPIRED &&
1022 work->sess->enc)
1023 return -ENOENT;
1024 ksmbd_user_session_put(work->sess);
1025 work->sess = NULL;
1026 return -ENOENT;
1027 }
1028 return 1;
1029 }
1030 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
1031 return -ENOENT;
1032 }
1033
1034 /**
1035 * smb2_get_name() - get filename string from on the wire smb format
1036 * @src: source buffer
1037 * @maxlen: maxlen of source string
1038 * @local_nls: nls_table pointer
1039 *
1040 * Return: matching converted filename on success, otherwise error ptr
1041 */
1042 static char *
smb2_get_name(const char * src,const int maxlen,struct nls_table * local_nls)1043 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
1044 {
1045 char *name;
1046
1047 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
1048 if (IS_ERR(name)) {
1049 pr_err("failed to get name %ld\n", PTR_ERR(name));
1050 return name;
1051 }
1052
1053 if (*name == '\0') {
1054 kfree(name);
1055 return ERR_PTR(-EINVAL);
1056 }
1057
1058 if (*name == '\\') {
1059 pr_err("not allow directory name included leading slash\n");
1060 kfree(name);
1061 return ERR_PTR(-EINVAL);
1062 }
1063
1064 ksmbd_conv_path_to_unix(name);
1065 ksmbd_strip_last_slash(name);
1066 return name;
1067 }
1068
1069 /* Link a fully initialized async work item unless the connection is closing. */
ksmbd_conn_link_async_request(struct ksmbd_conn * conn,struct ksmbd_work * work)1070 static bool ksmbd_conn_link_async_request(struct ksmbd_conn *conn,
1071 struct ksmbd_work *work)
1072 {
1073 bool linked = false;
1074
1075 spin_lock(&conn->request_lock);
1076 if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) {
1077 if (list_empty(&work->async_request_entry))
1078 list_add_tail(&work->async_request_entry,
1079 &conn->async_requests);
1080 linked = true;
1081 }
1082 spin_unlock(&conn->request_lock);
1083
1084 return linked;
1085 }
1086
setup_async_work(struct ksmbd_work * work,void (* fn)(void **),void ** arg)1087 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
1088 {
1089 struct ksmbd_conn *conn = work->conn;
1090 int id;
1091
1092 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
1093 if (id < 0) {
1094 pr_err("Failed to alloc async message id\n");
1095 return id;
1096 }
1097 work->asynchronous = true;
1098 work->async_id = id;
1099 work->cancel_fn = fn;
1100 work->cancel_argv = arg;
1101
1102 if (!ksmbd_conn_link_async_request(conn, work)) {
1103 work->asynchronous = false;
1104 work->async_id = 0;
1105 work->cancel_fn = NULL;
1106 work->cancel_argv = NULL;
1107 ksmbd_release_id(&conn->async_ida, id);
1108 return -ESHUTDOWN;
1109 }
1110
1111 ksmbd_debug(SMB,
1112 "Send interim Response to inform async request id : %d\n",
1113 work->async_id);
1114
1115 return 0;
1116 }
1117
release_async_work(struct ksmbd_work * work)1118 void release_async_work(struct ksmbd_work *work)
1119 {
1120 struct ksmbd_conn *conn = work->conn;
1121
1122 spin_lock(&conn->request_lock);
1123 list_del_init(&work->async_request_entry);
1124 spin_unlock(&conn->request_lock);
1125
1126 work->asynchronous = 0;
1127 work->cancel_fn = NULL;
1128 kfree(work->cancel_argv);
1129 work->cancel_argv = NULL;
1130 if (work->async_id) {
1131 ksmbd_release_id(&conn->async_ida, work->async_id);
1132 work->async_id = 0;
1133 }
1134 }
1135
smb2_send_interim_work(struct ksmbd_work * in_work,struct ksmbd_work * work,bool eor)1136 static int smb2_send_interim_work(struct ksmbd_work *in_work,
1137 struct ksmbd_work *work, bool eor)
1138 {
1139 int err = 0;
1140
1141 in_work->encrypted = work->encrypted;
1142 if (work->encrypted && work->sess && work->sess->enc &&
1143 work->conn->ops->encrypt_resp) {
1144 in_work->sess = work->sess;
1145 err = work->conn->ops->encrypt_resp(in_work);
1146 in_work->sess = NULL;
1147 }
1148 if (err)
1149 return err;
1150
1151 return eor ? ksmbd_conn_write_eor(in_work) :
1152 ksmbd_conn_write(in_work);
1153 }
1154
smb2_send_interim_prefix_work(struct ksmbd_work * work)1155 static int smb2_send_interim_prefix_work(struct ksmbd_work *work)
1156 {
1157 struct ksmbd_work *in_work;
1158 unsigned int len, copied = 0;
1159 char *dst;
1160 int err = -ENOMEM;
1161 int i;
1162
1163 len = get_rfc1002_len(work->iov[0].iov_base);
1164 in_work = ksmbd_alloc_work_struct();
1165 if (!in_work)
1166 return err;
1167
1168 in_work->response_buf = kvzalloc(len + 4, KSMBD_DEFAULT_GFP);
1169 if (!in_work->response_buf)
1170 goto out;
1171 in_work->response_sz = len + 4;
1172 in_work->conn = work->conn;
1173 dst = in_work->response_buf + 4;
1174 for (i = 1; i <= work->iov_idx; i++) {
1175 if (work->iov[i].iov_len > len - copied) {
1176 err = -EINVAL;
1177 goto out;
1178 }
1179 memcpy(dst + copied, work->iov[i].iov_base,
1180 work->iov[i].iov_len);
1181 copied += work->iov[i].iov_len;
1182 }
1183 if (copied != len) {
1184 err = -EINVAL;
1185 goto out;
1186 }
1187
1188 err = ksmbd_iov_pin_rsp(in_work, dst, len);
1189 if (!err)
1190 err = smb2_send_interim_work(in_work, work, true);
1191 out:
1192 ksmbd_free_work_struct(in_work);
1193 return err;
1194 }
1195
smb2_send_interim_compound_prefix(struct ksmbd_work * work)1196 static void smb2_send_interim_compound_prefix(struct ksmbd_work *work)
1197 {
1198 struct smb2_hdr *req_hdr;
1199 struct smb2_hdr *rsp_hdr;
1200 int err;
1201
1202 if (!work->next_smb2_rcv_hdr_off ||
1203 !work->next_smb2_rsp_hdr_off ||
1204 work->curr_smb2_rsp_hdr_off == work->next_smb2_rsp_hdr_off ||
1205 !work->iov_idx)
1206 return;
1207
1208 req_hdr = ksmbd_req_buf_next(work);
1209 /* Detach only the final async command from the completed prefix. */
1210 if (req_hdr->NextCommand)
1211 return;
1212
1213 /*
1214 * The responses before the async command are sent as a standalone
1215 * compound response. The last response in this prefix must terminate
1216 * the chain.
1217 */
1218 rsp_hdr = ksmbd_resp_buf_curr(work);
1219 rsp_hdr->NextCommand = 0;
1220 if ((rsp_hdr->Flags & SMB2_FLAGS_SIGNED) && work->sess &&
1221 work->conn->ops->set_sign_rsp)
1222 work->conn->ops->set_sign_rsp(work);
1223
1224 err = smb2_send_interim_prefix_work(work);
1225 if (err)
1226 ksmbd_debug(SMB, "failed to send compound interim prefix: %d\n",
1227 err);
1228
1229 work->iov_idx = 0;
1230 work->iov_cnt = 0;
1231 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
1232 *(__be32 *)work->response_buf = 0;
1233
1234 rsp_hdr = ksmbd_resp_buf_next(work);
1235 rsp_hdr->Flags &= ~SMB2_FLAGS_RELATED_OPERATIONS;
1236 }
1237
smb2_send_interim_resp(struct ksmbd_work * work,__le32 status)1238 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
1239 {
1240 struct smb2_hdr *rsp_hdr;
1241 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
1242
1243 if (!in_work)
1244 return;
1245
1246 if (allocate_interim_rsp_buf(in_work)) {
1247 pr_err("smb_allocate_rsp_buf failed!\n");
1248 ksmbd_free_work_struct(in_work);
1249 return;
1250 }
1251
1252 if (status == STATUS_PENDING)
1253 smb2_send_interim_compound_prefix(work);
1254
1255 in_work->conn = work->conn;
1256 memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
1257 __SMB2_HEADER_STRUCTURE_SIZE);
1258
1259 rsp_hdr = smb_get_msg(in_work->response_buf);
1260 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
1261 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
1262 smb2_set_err_rsp(in_work);
1263 rsp_hdr->Status = status;
1264
1265 if (smb2_send_interim_work(in_work, work, true))
1266 ksmbd_debug(SMB, "failed to send interim response\n");
1267 ksmbd_free_work_struct(in_work);
1268 }
1269
smb2_get_reparse_tag_special_file(umode_t mode)1270 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
1271 {
1272 if (S_ISDIR(mode) || S_ISREG(mode))
1273 return 0;
1274
1275 if (S_ISLNK(mode))
1276 return IO_REPARSE_TAG_LX_SYMLINK_LE;
1277 else if (S_ISFIFO(mode))
1278 return IO_REPARSE_TAG_LX_FIFO_LE;
1279 else if (S_ISSOCK(mode))
1280 return IO_REPARSE_TAG_AF_UNIX_LE;
1281 else if (S_ISCHR(mode))
1282 return IO_REPARSE_TAG_LX_CHR_LE;
1283 else if (S_ISBLK(mode))
1284 return IO_REPARSE_TAG_LX_BLK_LE;
1285
1286 return 0;
1287 }
1288
1289 /**
1290 * smb2_get_dos_mode() - get file mode in dos format from unix mode
1291 * @stat: kstat containing file mode
1292 * @attribute: attribute flags
1293 *
1294 * Return: converted dos mode
1295 */
smb2_get_dos_mode(struct kstat * stat,int attribute)1296 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
1297 {
1298 int attr = 0;
1299
1300 if (S_ISDIR(stat->mode)) {
1301 attr = FILE_ATTRIBUTE_DIRECTORY |
1302 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
1303 } else {
1304 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
1305 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
1306
1307 if (smb2_get_reparse_tag_special_file(stat->mode))
1308 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
1309 }
1310
1311 return attr;
1312 }
1313
build_preauth_ctxt(struct smb2_preauth_neg_context * pneg_ctxt,__le16 hash_id)1314 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
1315 __le16 hash_id)
1316 {
1317 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
1318 pneg_ctxt->DataLength = cpu_to_le16(38);
1319 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
1320 pneg_ctxt->Reserved = cpu_to_le32(0);
1321 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
1322 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
1323 pneg_ctxt->HashAlgorithms = hash_id;
1324 }
1325
build_encrypt_ctxt(struct smb2_encryption_neg_context * pneg_ctxt,__le16 cipher_type)1326 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
1327 __le16 cipher_type)
1328 {
1329 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
1330 pneg_ctxt->DataLength = cpu_to_le16(4);
1331 pneg_ctxt->Reserved = cpu_to_le32(0);
1332 pneg_ctxt->CipherCount = cpu_to_le16(1);
1333 pneg_ctxt->Ciphers[0] = cipher_type;
1334 }
1335
build_compress_ctxt(struct smb2_compression_capabilities_context * pneg_ctxt,__le16 compress_algorithm,bool compress_chained,bool compress_pattern)1336 static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
1337 __le16 compress_algorithm, bool compress_chained,
1338 bool compress_pattern)
1339 {
1340 /*
1341 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised
1342 * as a second ID when the client also enabled chained transforms.
1343 */
1344 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
1345 pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10);
1346 pneg_ctxt->Reserved = cpu_to_le32(0);
1347 pneg_ctxt->CompressionAlgorithmCount =
1348 cpu_to_le16(compress_pattern ? 2 : 1);
1349 pneg_ctxt->Padding = cpu_to_le16(0);
1350 pneg_ctxt->Flags = compress_chained ?
1351 SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED :
1352 SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE;
1353 pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm;
1354 pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ?
1355 SMB3_COMPRESS_PATTERN : 0;
1356 pneg_ctxt->CompressionAlgorithms[2] = 0;
1357 pneg_ctxt->CompressionAlgorithms[3] = 0;
1358 }
1359
1360 /**
1361 * build_rdma_ctx() - build an RDMA transform negotiate response context
1362 * @ctxt: response context header to populate
1363 * @transform_ids: bitmap of transforms common to the client and server
1364 *
1365 * Return: encoded negotiate context length
1366 */
build_rdma_ctx(struct smb2_neg_context * ctxt,unsigned long transform_ids)1367 static int build_rdma_ctx(struct smb2_neg_context *ctxt,
1368 unsigned long transform_ids)
1369 {
1370 struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
1371 int count = 0;
1372
1373 pneg_ctxt = (void *)ctxt;
1374 pneg_ctxt->ContextType = SMB2_RDMA_TRANSFORM_CAPABILITIES;
1375 pneg_ctxt->Reserved = 0;
1376 pneg_ctxt->Reserved1 = 0;
1377 pneg_ctxt->Reserved2 = 0;
1378 if (transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION))
1379 pneg_ctxt->RDMATransformIds[count++] =
1380 cpu_to_le16(SMB2_RDMA_TRANSFORM_ENCRYPTION);
1381 if (!count)
1382 pneg_ctxt->RDMATransformIds[count++] =
1383 cpu_to_le16(SMB2_RDMA_TRANSFORM_NONE);
1384
1385 pneg_ctxt->TransformCount = cpu_to_le16(count);
1386 pneg_ctxt->DataLength = cpu_to_le16(8 + count * sizeof(__le16));
1387 return sizeof(struct smb2_neg_context) +
1388 le16_to_cpu(pneg_ctxt->DataLength);
1389 }
1390
build_sign_cap_ctxt(struct smb2_signing_capabilities * pneg_ctxt,__le16 sign_algo)1391 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
1392 __le16 sign_algo)
1393 {
1394 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
1395 pneg_ctxt->DataLength =
1396 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
1397 - sizeof(struct smb2_neg_context));
1398 pneg_ctxt->Reserved = cpu_to_le32(0);
1399 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
1400 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
1401 }
1402
build_posix_ctxt(struct smb2_posix_neg_context * pneg_ctxt)1403 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
1404 {
1405 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
1406 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
1407 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
1408 pneg_ctxt->Name[0] = 0x93;
1409 pneg_ctxt->Name[1] = 0xAD;
1410 pneg_ctxt->Name[2] = 0x25;
1411 pneg_ctxt->Name[3] = 0x50;
1412 pneg_ctxt->Name[4] = 0x9C;
1413 pneg_ctxt->Name[5] = 0xB4;
1414 pneg_ctxt->Name[6] = 0x11;
1415 pneg_ctxt->Name[7] = 0xE7;
1416 pneg_ctxt->Name[8] = 0xB4;
1417 pneg_ctxt->Name[9] = 0x23;
1418 pneg_ctxt->Name[10] = 0x83;
1419 pneg_ctxt->Name[11] = 0xDE;
1420 pneg_ctxt->Name[12] = 0x96;
1421 pneg_ctxt->Name[13] = 0x8B;
1422 pneg_ctxt->Name[14] = 0xCD;
1423 pneg_ctxt->Name[15] = 0x7C;
1424 }
1425
assemble_neg_contexts(struct ksmbd_conn * conn,struct smb2_negotiate_rsp * rsp)1426 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
1427 struct smb2_negotiate_rsp *rsp)
1428 {
1429 char * const pneg_ctxt = (char *)rsp +
1430 le32_to_cpu(rsp->NegotiateContextOffset);
1431 int neg_ctxt_cnt = 1;
1432 int ctxt_size;
1433
1434 ksmbd_debug(SMB,
1435 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1436 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
1437 conn->preauth_info->Preauth_HashId);
1438 ctxt_size = sizeof(struct smb2_preauth_neg_context);
1439
1440 if (conn->cipher_type) {
1441 /* Round to 8 byte boundary */
1442 ctxt_size = round_up(ctxt_size, 8);
1443 ksmbd_debug(SMB,
1444 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1445 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
1446 (pneg_ctxt + ctxt_size),
1447 conn->cipher_type);
1448 neg_ctxt_cnt++;
1449 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
1450 }
1451
1452 if (conn->compress_algorithm != SMB3_COMPRESS_NONE) {
1453 ctxt_size = round_up(ctxt_size, 8);
1454 ksmbd_debug(SMB,
1455 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
1456 build_compress_ctxt((struct smb2_compression_capabilities_context *)
1457 (pneg_ctxt + ctxt_size),
1458 conn->compress_algorithm,
1459 conn->compress_chained,
1460 conn->compress_pattern);
1461 neg_ctxt_cnt++;
1462 ctxt_size += sizeof(struct smb2_neg_context) +
1463 (conn->compress_pattern ? 12 : 10);
1464 }
1465
1466 if (conn->rdma_transform_negotiated) {
1467 struct smb2_neg_context *rdma_ctxt;
1468
1469 ctxt_size = round_up(ctxt_size, 8);
1470 ksmbd_debug(SMB,
1471 "assemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
1472 rdma_ctxt = (void *)(pneg_ctxt + ctxt_size);
1473 ctxt_size += build_rdma_ctx(rdma_ctxt,
1474 conn->rdma_transform_ids);
1475 neg_ctxt_cnt++;
1476 }
1477
1478 if (conn->posix_ext_supported) {
1479 ctxt_size = round_up(ctxt_size, 8);
1480 ksmbd_debug(SMB,
1481 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1482 build_posix_ctxt((struct smb2_posix_neg_context *)
1483 (pneg_ctxt + ctxt_size));
1484 neg_ctxt_cnt++;
1485 ctxt_size += sizeof(struct smb2_posix_neg_context);
1486 }
1487
1488 if (conn->signing_negotiated) {
1489 ctxt_size = round_up(ctxt_size, 8);
1490 ksmbd_debug(SMB,
1491 "assemble SMB2_SIGNING_CAPABILITIES context\n");
1492 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
1493 (pneg_ctxt + ctxt_size),
1494 conn->signing_algorithm);
1495 neg_ctxt_cnt++;
1496 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
1497 }
1498
1499 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
1500 return ctxt_size + AUTH_GSS_PADDING;
1501 }
1502
decode_preauth_ctxt(struct ksmbd_conn * conn,struct smb2_preauth_neg_context * pneg_ctxt,int ctxt_len)1503 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
1504 struct smb2_preauth_neg_context *pneg_ctxt,
1505 int ctxt_len)
1506 {
1507 /*
1508 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
1509 * which may not be present. Only check for used HashAlgorithms[1].
1510 */
1511 if (ctxt_len <
1512 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
1513 return STATUS_INVALID_PARAMETER;
1514
1515 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
1516 return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
1517
1518 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
1519 return STATUS_SUCCESS;
1520 }
1521
decode_encrypt_ctxt(struct ksmbd_conn * conn,struct smb2_encryption_neg_context * pneg_ctxt,int ctxt_len)1522 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
1523 struct smb2_encryption_neg_context *pneg_ctxt,
1524 int ctxt_len)
1525 {
1526 int cph_cnt;
1527 int i, cphs_size;
1528
1529 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
1530 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
1531 return;
1532 }
1533
1534 conn->cipher_type = 0;
1535
1536 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
1537 cphs_size = cph_cnt * sizeof(__le16);
1538
1539 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
1540 ctxt_len) {
1541 pr_err("Invalid cipher count(%d)\n", cph_cnt);
1542 return;
1543 }
1544
1545 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
1546 return;
1547
1548 for (i = 0; i < cph_cnt; i++) {
1549 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
1550 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
1551 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
1552 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
1553 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
1554 pneg_ctxt->Ciphers[i]);
1555 conn->cipher_type = pneg_ctxt->Ciphers[i];
1556 break;
1557 }
1558 }
1559 }
1560
1561 /**
1562 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
1563 * @conn: smb connection
1564 *
1565 * Return: true if connection should be encrypted, else false
1566 */
smb3_encryption_negotiated(struct ksmbd_conn * conn)1567 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
1568 {
1569 if (!conn->ops->generate_encryptionkey)
1570 return false;
1571
1572 /*
1573 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
1574 * SMB 3.1.1 uses the cipher_type field.
1575 */
1576 return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
1577 conn->cipher_type;
1578 }
1579
decode_compress_ctxt(struct ksmbd_conn * conn,struct smb2_compression_capabilities_context * pneg_ctxt,int ctxt_len)1580 static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
1581 struct smb2_compression_capabilities_context *pneg_ctxt,
1582 int ctxt_len)
1583 {
1584 int alg_cnt, algs_size, i;
1585 __le16 *algs;
1586
1587 if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) {
1588 pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n");
1589 return STATUS_INVALID_PARAMETER;
1590 }
1591
1592 conn->compress_algorithm = SMB3_COMPRESS_NONE;
1593 conn->compress_chained = false;
1594 conn->compress_pattern = false;
1595
1596 alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount);
1597 if (!alg_cnt)
1598 return STATUS_INVALID_PARAMETER;
1599
1600 if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE &&
1601 pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED)
1602 return STATUS_INVALID_PARAMETER;
1603
1604 algs_size = alg_cnt * sizeof(__le16);
1605 if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) {
1606 pr_err("Invalid compression algorithm count(%d)\n", alg_cnt);
1607 return STATUS_INVALID_PARAMETER;
1608 }
1609
1610 /*
1611 * CompressionAlgorithms[] is declared as a fixed 4-element array, but
1612 * the actual element count is variable (clients such as Windows may
1613 * advertise more). The on-wire length was validated above, so walk the
1614 * algorithms through a pointer to avoid a fixed-array bounds check.
1615 */
1616 algs = pneg_ctxt->CompressionAlgorithms;
1617 for (i = 0; i < alg_cnt; i++) {
1618 __le16 alg = algs[i];
1619
1620 /*
1621 * LZ77 is the required general-purpose codec. Pattern_V1 is an
1622 * optional chained payload type and cannot stand alone.
1623 */
1624 if (alg == SMB3_COMPRESS_LZ77) {
1625 conn->compress_algorithm = alg;
1626 conn->compress_chained =
1627 pneg_ctxt->Flags ==
1628 SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
1629 ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
1630 le16_to_cpu(alg));
1631 } else if (alg == SMB3_COMPRESS_PATTERN) {
1632 conn->compress_pattern = true;
1633 }
1634 }
1635
1636 if (conn->compress_algorithm == SMB3_COMPRESS_NONE ||
1637 !conn->compress_chained)
1638 conn->compress_pattern = false;
1639
1640 return STATUS_SUCCESS;
1641 }
1642
decode_sign_cap_ctxt(struct ksmbd_conn * conn,struct smb2_signing_capabilities * pneg_ctxt,int ctxt_len)1643 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
1644 struct smb2_signing_capabilities *pneg_ctxt,
1645 int ctxt_len)
1646 {
1647 int sign_algo_cnt;
1648 int i, sign_alos_size;
1649
1650 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
1651 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
1652 return;
1653 }
1654
1655 conn->signing_negotiated = false;
1656 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
1657 sign_alos_size = sign_algo_cnt * sizeof(__le16);
1658
1659 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
1660 ctxt_len) {
1661 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
1662 return;
1663 }
1664
1665 for (i = 0; i < sign_algo_cnt; i++) {
1666 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1667 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1668 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1669 pneg_ctxt->SigningAlgorithms[i]);
1670 conn->signing_negotiated = true;
1671 conn->signing_algorithm =
1672 pneg_ctxt->SigningAlgorithms[i];
1673 break;
1674 }
1675 }
1676 }
1677
1678 /**
1679 * decode_rdma_ctx() - decode an RDMA transform negotiate request context
1680 * @conn: connection being negotiated
1681 * @ctxt: request context header to decode
1682 * @ctxt_len: total context length, including the negotiate context header
1683 *
1684 * Record transforms supported by both peers only for SMB Direct connections.
1685 *
1686 * Return: NT status describing the decode result
1687 */
decode_rdma_ctx(struct ksmbd_conn * conn,struct smb2_neg_context * ctxt,int ctxt_len)1688 static __le32 decode_rdma_ctx(struct ksmbd_conn *conn,
1689 struct smb2_neg_context *ctxt, int ctxt_len)
1690 {
1691 struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
1692 unsigned int count, i;
1693
1694 pneg_ctxt = (void *)ctxt;
1695 /* RDMA transforms are a node capability, not just a transport capability. */
1696 if (!ksmbd_rdma_enabled())
1697 return STATUS_SUCCESS;
1698
1699 if (ctxt_len < sizeof(*pneg_ctxt))
1700 return STATUS_INVALID_PARAMETER;
1701
1702 count = le16_to_cpu(pneg_ctxt->TransformCount);
1703 if (!count || count >
1704 (ctxt_len - sizeof(*pneg_ctxt)) / sizeof(__le16))
1705 return STATUS_INVALID_PARAMETER;
1706
1707 conn->rdma_transform_negotiated = true;
1708 conn->rdma_transform_ids = 0;
1709 for (i = 0; i < count; i++) {
1710 u16 id = le16_to_cpu(pneg_ctxt->RDMATransformIds[i]);
1711
1712 if (id == SMB2_RDMA_TRANSFORM_ENCRYPTION)
1713 conn->rdma_transform_ids |= BIT(id);
1714 }
1715 return STATUS_SUCCESS;
1716 }
1717
deassemble_neg_contexts(struct ksmbd_conn * conn,struct smb2_negotiate_req * req,unsigned int len_of_smb)1718 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1719 struct smb2_negotiate_req *req,
1720 unsigned int len_of_smb)
1721 {
1722 /* +4 is to account for the RFC1001 len field */
1723 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1724 int i = 0, len_of_ctxts;
1725 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1726 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1727 __le32 status = STATUS_INVALID_PARAMETER;
1728 int compress_ctxt_cnt = 0, rdma_transform_ctxt_cnt = 0;
1729
1730 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1731 if (len_of_smb <= offset) {
1732 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1733 return status;
1734 }
1735
1736 len_of_ctxts = len_of_smb - offset;
1737
1738 while (i++ < neg_ctxt_cnt) {
1739 int clen, ctxt_len;
1740
1741 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1742 break;
1743
1744 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1745 clen = le16_to_cpu(pctx->DataLength);
1746 ctxt_len = clen + sizeof(struct smb2_neg_context);
1747
1748 if (ctxt_len > len_of_ctxts)
1749 break;
1750
1751 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1752 ksmbd_debug(SMB,
1753 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1754 if (conn->preauth_info->Preauth_HashId)
1755 break;
1756
1757 status = decode_preauth_ctxt(conn,
1758 (struct smb2_preauth_neg_context *)pctx,
1759 ctxt_len);
1760 if (status != STATUS_SUCCESS)
1761 break;
1762 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1763 ksmbd_debug(SMB,
1764 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1765 if (conn->cipher_type)
1766 break;
1767
1768 decode_encrypt_ctxt(conn,
1769 (struct smb2_encryption_neg_context *)pctx,
1770 ctxt_len);
1771 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1772 ksmbd_debug(SMB,
1773 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1774 if (compress_ctxt_cnt++) {
1775 status = STATUS_INVALID_PARAMETER;
1776 break;
1777 }
1778
1779 status = decode_compress_ctxt(conn,
1780 (struct smb2_compression_capabilities_context *)
1781 pctx, ctxt_len);
1782 if (status != STATUS_SUCCESS)
1783 break;
1784 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1785 ksmbd_debug(SMB,
1786 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1787 } else if (pctx->ContextType == SMB2_RDMA_TRANSFORM_CAPABILITIES) {
1788 ksmbd_debug(SMB,
1789 "deassemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
1790 if (ksmbd_rdma_enabled() &&
1791 rdma_transform_ctxt_cnt++) {
1792 status = STATUS_INVALID_PARAMETER;
1793 break;
1794 }
1795 status = decode_rdma_ctx(conn, pctx, ctxt_len);
1796 if (status != STATUS_SUCCESS)
1797 break;
1798 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1799 ksmbd_debug(SMB,
1800 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1801 conn->posix_ext_supported = true;
1802 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1803 ksmbd_debug(SMB,
1804 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1805
1806 decode_sign_cap_ctxt(conn,
1807 (struct smb2_signing_capabilities *)pctx,
1808 ctxt_len);
1809 }
1810
1811 /* offsets must be 8 byte aligned */
1812 offset = (ctxt_len + 7) & ~0x7;
1813 len_of_ctxts -= offset;
1814 }
1815 return status;
1816 }
1817
1818 /**
1819 * smb2_handle_negotiate() - handler for smb2 negotiate command
1820 * @work: smb work containing smb request buffer
1821 *
1822 * The caller holds conn->srv_mutex.
1823 *
1824 * Return: 0
1825 */
smb2_handle_negotiate(struct ksmbd_work * work)1826 int smb2_handle_negotiate(struct ksmbd_work *work)
1827 {
1828 struct ksmbd_conn *conn = work->conn;
1829 struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1830 struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1831 int rc = 0;
1832 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1833 __le32 status;
1834
1835 ksmbd_debug(SMB, "Received negotiate request\n");
1836 conn->need_neg = false;
1837 smb2_buf_len = get_rfc1002_len(work->request_buf);
1838 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1839 if (smb2_neg_size > smb2_buf_len) {
1840 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1841 rc = -EINVAL;
1842 goto err_out;
1843 }
1844
1845 if (req->DialectCount == 0) {
1846 pr_err("malformed packet\n");
1847 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1848 rc = -EINVAL;
1849 goto err_out;
1850 }
1851
1852 if (conn->dialect == SMB311_PROT_ID) {
1853 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1854
1855 if (smb2_buf_len < nego_ctxt_off) {
1856 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1857 rc = -EINVAL;
1858 goto err_out;
1859 }
1860
1861 if (smb2_neg_size > nego_ctxt_off) {
1862 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1863 rc = -EINVAL;
1864 goto err_out;
1865 }
1866
1867 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1868 nego_ctxt_off) {
1869 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1870 rc = -EINVAL;
1871 goto err_out;
1872 }
1873 } else {
1874 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1875 smb2_buf_len) {
1876 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1877 rc = -EINVAL;
1878 goto err_out;
1879 }
1880 }
1881
1882 conn->cli_cap = le32_to_cpu(req->Capabilities);
1883 switch (conn->dialect) {
1884 case SMB311_PROT_ID:
1885 conn->preauth_info =
1886 kzalloc_obj(struct preauth_integrity_info,
1887 KSMBD_DEFAULT_GFP);
1888 if (!conn->preauth_info) {
1889 rc = -ENOMEM;
1890 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1891 goto err_out;
1892 }
1893
1894 status = deassemble_neg_contexts(conn, req,
1895 get_rfc1002_len(work->request_buf));
1896 if (status != STATUS_SUCCESS) {
1897 pr_err("deassemble_neg_contexts error(0x%x)\n",
1898 status);
1899 rsp->hdr.Status = status;
1900 rc = -EINVAL;
1901 kfree(conn->preauth_info);
1902 conn->preauth_info = NULL;
1903 goto err_out;
1904 }
1905 if (!conn->cipher_type)
1906 conn->rdma_transform_ids &=
1907 ~BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION);
1908 ksmbd_debug(RDMA,
1909 "RDMA transform negotiation: transport=%s context=%s encryption=%s cipher=0x%04x\n",
1910 conn->transport->ops->rdma_read ? "rdma" : "tcp",
1911 conn->rdma_transform_negotiated ? "present" : "absent",
1912 conn->rdma_transform_ids &
1913 BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION) ? "enabled" : "disabled",
1914 le16_to_cpu(conn->cipher_type));
1915
1916 rc = init_smb3_11_server(conn);
1917 if (rc < 0) {
1918 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1919 kfree(conn->preauth_info);
1920 conn->preauth_info = NULL;
1921 goto err_out;
1922 }
1923
1924 ksmbd_gen_preauth_integrity_hash(conn,
1925 work->request_buf,
1926 conn->preauth_info->Preauth_HashValue);
1927 rsp->NegotiateContextOffset =
1928 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1929 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1930 break;
1931 case SMB302_PROT_ID:
1932 init_smb3_02_server(conn);
1933 break;
1934 case SMB30_PROT_ID:
1935 init_smb3_0_server(conn);
1936 break;
1937 case SMB21_PROT_ID:
1938 init_smb2_1_server(conn);
1939 break;
1940 case SMB2X_PROT_ID:
1941 case BAD_PROT_ID:
1942 default:
1943 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1944 conn->dialect);
1945 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1946 rc = -EINVAL;
1947 goto err_out;
1948 }
1949 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1950
1951 /* For stats */
1952 conn->connection_type = conn->dialect;
1953
1954 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1955 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1956 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1957
1958 memcpy(conn->ClientGUID, req->ClientGUID,
1959 SMB2_CLIENT_GUID_SIZE);
1960 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1961
1962 rsp->StructureSize = cpu_to_le16(65);
1963 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1964 /* Not setting conn guid rsp->ServerGUID, as it
1965 * not used by client for identifying server
1966 */
1967 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1968
1969 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1970 rsp->ServerStartTime = 0;
1971 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1972 le32_to_cpu(rsp->NegotiateContextOffset),
1973 le16_to_cpu(rsp->NegotiateContextCount));
1974
1975 rsp->SecurityBufferOffset = cpu_to_le16(128);
1976 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1977 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1978 le16_to_cpu(rsp->SecurityBufferOffset));
1979
1980 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1981 conn->use_spnego = true;
1982
1983 if (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1984 conn->sign = true;
1985 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1986 server_conf.enforced_signing = true;
1987 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1988 conn->sign = true;
1989 }
1990
1991 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1992 ksmbd_conn_set_need_setup(conn);
1993
1994 err_out:
1995 if (rc && rsp->hdr.Status == STATUS_SUCCESS)
1996 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1997
1998 if (!rc)
1999 rc = ksmbd_iov_pin_rsp(work, rsp,
2000 sizeof(struct smb2_negotiate_rsp) +
2001 AUTH_GSS_LENGTH + neg_ctxt_len);
2002 if (rc < 0)
2003 smb2_set_err_rsp(work);
2004 return rc;
2005 }
2006
alloc_preauth_hash(struct ksmbd_session * sess,struct ksmbd_conn * conn)2007 static int alloc_preauth_hash(struct ksmbd_session *sess,
2008 struct ksmbd_conn *conn)
2009 {
2010 if (sess->Preauth_HashValue)
2011 return 0;
2012
2013 if (!conn->preauth_info)
2014 return -ENOMEM;
2015
2016 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
2017 PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
2018 if (!sess->Preauth_HashValue)
2019 return -ENOMEM;
2020
2021 return 0;
2022 }
2023
generate_preauth_hash(struct ksmbd_work * work)2024 static int generate_preauth_hash(struct ksmbd_work *work)
2025 {
2026 struct ksmbd_conn *conn = work->conn;
2027 struct ksmbd_session *sess = work->sess;
2028 u8 *preauth_hash;
2029
2030 if (conn->dialect != SMB311_PROT_ID)
2031 return 0;
2032
2033 if (conn->binding) {
2034 struct preauth_session *preauth_sess;
2035
2036 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2037 if (!preauth_sess) {
2038 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
2039 if (!preauth_sess)
2040 return -ENOMEM;
2041 }
2042
2043 preauth_hash = preauth_sess->Preauth_HashValue;
2044 } else {
2045 if (!sess->Preauth_HashValue)
2046 if (alloc_preauth_hash(sess, conn))
2047 return -ENOMEM;
2048 preauth_hash = sess->Preauth_HashValue;
2049 }
2050
2051 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
2052 return 0;
2053 }
2054
decode_negotiation_token(struct ksmbd_conn * conn,struct negotiate_message * negblob,size_t sz)2055 static int decode_negotiation_token(struct ksmbd_conn *conn,
2056 struct negotiate_message *negblob,
2057 size_t sz)
2058 {
2059 if (!conn->use_spnego)
2060 return -EINVAL;
2061
2062 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
2063 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
2064 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
2065 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
2066 conn->use_spnego = false;
2067 }
2068 }
2069 return 0;
2070 }
2071
ntlm_negotiate(struct ksmbd_work * work,struct negotiate_message * negblob,size_t negblob_len,struct smb2_sess_setup_rsp * rsp)2072 static int ntlm_negotiate(struct ksmbd_work *work,
2073 struct negotiate_message *negblob,
2074 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
2075 {
2076 struct challenge_message *chgblob;
2077 unsigned char *spnego_blob = NULL;
2078 u16 spnego_blob_len;
2079 char *neg_blob;
2080 int sz, rc;
2081
2082 ksmbd_debug(SMB, "negotiate phase\n");
2083 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
2084 if (rc)
2085 return rc;
2086
2087 sz = le16_to_cpu(rsp->SecurityBufferOffset);
2088 chgblob = (struct challenge_message *)rsp->Buffer;
2089 memset(chgblob, 0, sizeof(struct challenge_message));
2090
2091 if (!work->conn->use_spnego) {
2092 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
2093 if (sz < 0)
2094 return -ENOMEM;
2095
2096 rsp->SecurityBufferLength = cpu_to_le16(sz);
2097 return 0;
2098 }
2099
2100 sz = sizeof(struct challenge_message);
2101 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
2102
2103 neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
2104 if (!neg_blob)
2105 return -ENOMEM;
2106
2107 chgblob = (struct challenge_message *)neg_blob;
2108 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
2109 if (sz < 0) {
2110 rc = -ENOMEM;
2111 goto out;
2112 }
2113
2114 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
2115 neg_blob, sz);
2116 if (rc) {
2117 rc = -ENOMEM;
2118 goto out;
2119 }
2120
2121 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
2122 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
2123
2124 out:
2125 kfree(spnego_blob);
2126 kfree(neg_blob);
2127 return rc;
2128 }
2129
user_authblob(struct ksmbd_conn * conn,struct smb2_sess_setup_req * req)2130 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
2131 struct smb2_sess_setup_req *req)
2132 {
2133 int sz;
2134
2135 if (conn->use_spnego && conn->mechToken)
2136 return (struct authenticate_message *)conn->mechToken;
2137
2138 sz = le16_to_cpu(req->SecurityBufferOffset);
2139 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
2140 + sz);
2141 }
2142
session_user(struct ksmbd_conn * conn,struct smb2_sess_setup_req * req)2143 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
2144 struct smb2_sess_setup_req *req)
2145 {
2146 struct authenticate_message *authblob;
2147 struct ksmbd_user *user;
2148 char *name;
2149 unsigned int name_off, name_len, secbuf_len;
2150
2151 if (conn->use_spnego && conn->mechToken)
2152 secbuf_len = conn->mechTokenLen;
2153 else
2154 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
2155 if (secbuf_len < sizeof(struct authenticate_message)) {
2156 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
2157 return NULL;
2158 }
2159 authblob = user_authblob(conn, req);
2160 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
2161 name_len = le16_to_cpu(authblob->UserName.Length);
2162
2163 if (secbuf_len < (u64)name_off + name_len)
2164 return NULL;
2165
2166 name = smb_strndup_from_utf16((const char *)authblob + name_off,
2167 name_len,
2168 true,
2169 conn->local_nls);
2170 if (IS_ERR(name)) {
2171 pr_err("cannot allocate memory\n");
2172 return NULL;
2173 }
2174
2175 ksmbd_debug(SMB, "session setup request for user %s\n", name);
2176 user = ksmbd_login_user(name);
2177 kfree(name);
2178 return user;
2179 }
2180
ntlm_authenticate(struct ksmbd_work * work,struct smb2_sess_setup_req * req,struct smb2_sess_setup_rsp * rsp)2181 static int ntlm_authenticate(struct ksmbd_work *work,
2182 struct smb2_sess_setup_req *req,
2183 struct smb2_sess_setup_rsp *rsp)
2184 {
2185 struct ksmbd_conn *conn = work->conn;
2186 struct ksmbd_session *sess = work->sess;
2187 struct ksmbd_user *user;
2188 char channel_key[CIFS_KEY_SIZE] = {};
2189 char *auth_key = conn->binding ? channel_key : sess->sess_key;
2190 u64 prev_id;
2191 bool binding = conn->binding;
2192 int sz, rc;
2193
2194 ksmbd_debug(SMB, "authenticate phase\n");
2195 if (conn->use_spnego) {
2196 unsigned char *spnego_blob;
2197 u16 spnego_blob_len;
2198
2199 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
2200 &spnego_blob_len,
2201 0);
2202 if (rc)
2203 return -ENOMEM;
2204
2205 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
2206 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
2207 kfree(spnego_blob);
2208 }
2209
2210 user = session_user(conn, req);
2211 if (!user) {
2212 ksmbd_debug(SMB, "Unknown user name or an error\n");
2213 return -EPERM;
2214 }
2215
2216 if (sess->state == SMB2_SESSION_VALID) {
2217 /*
2218 * Reuse session if anonymous try to connect
2219 * on reauthetication.
2220 */
2221 if (conn->binding == false && ksmbd_anonymous_user(user)) {
2222 ksmbd_free_user(user);
2223 return 0;
2224 }
2225
2226 if (!ksmbd_compare_user(sess->user, user)) {
2227 ksmbd_free_user(user);
2228 return -EKEYREJECTED;
2229 }
2230 ksmbd_free_user(user);
2231 } else {
2232 sess->user = user;
2233 }
2234
2235 if (conn->binding == false && user_guest(sess->user)) {
2236 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
2237 } else {
2238 struct authenticate_message *authblob;
2239
2240 authblob = user_authblob(conn, req);
2241 if (conn->use_spnego && conn->mechToken)
2242 sz = conn->mechTokenLen;
2243 else
2244 sz = le16_to_cpu(req->SecurityBufferLength);
2245 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess,
2246 auth_key);
2247 if (rc) {
2248 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
2249 ksmbd_debug(SMB, "authentication failed\n");
2250 rc = -EPERM;
2251 goto out;
2252 }
2253 }
2254
2255 prev_id = le64_to_cpu(req->PreviousSessionId);
2256 if (prev_id && prev_id != sess->id)
2257 destroy_previous_session(conn, sess->user, prev_id);
2258
2259 /*
2260 * If session state is SMB2_SESSION_VALID, We can assume
2261 * that it is reauthentication. And the user/password
2262 * has been verified, so return it here.
2263 */
2264 if (sess->state == SMB2_SESSION_VALID) {
2265 if (conn->binding)
2266 goto binding_session;
2267 return 0;
2268 }
2269
2270 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
2271 (conn->sign || server_conf.enforced_signing)) ||
2272 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
2273 sess->sign = true;
2274
2275 if (smb3_encryption_negotiated(conn) &&
2276 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2277 conn->ops->generate_encryptionkey(conn, sess);
2278 sess->enc = true;
2279 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
2280 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
2281 /*
2282 * signing is disable if encryption is enable
2283 * on this session
2284 */
2285 sess->sign = false;
2286 }
2287
2288 binding_session:
2289 if (conn->dialect >= SMB30_PROT_ID) {
2290 rc = register_session_channel(sess, conn, auth_key);
2291 if (rc)
2292 goto out;
2293 }
2294
2295 if (conn->ops->generate_signingkey) {
2296 rc = conn->ops->generate_signingkey(sess, conn);
2297 if (rc) {
2298 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
2299 rc = -EINVAL;
2300 goto out;
2301 }
2302 }
2303
2304 if (!ksmbd_conn_lookup_dialect(conn)) {
2305 pr_err("fail to verify the dialect\n");
2306 rc = -ENOENT;
2307 goto out;
2308 }
2309 rc = 0;
2310 out:
2311 if (binding)
2312 memzero_explicit(channel_key, sizeof(channel_key));
2313 return rc;
2314 }
2315
2316 #ifdef CONFIG_SMB_SERVER_KERBEROS5
krb5_authenticate(struct ksmbd_work * work,struct smb2_sess_setup_req * req,struct smb2_sess_setup_rsp * rsp)2317 static int krb5_authenticate(struct ksmbd_work *work,
2318 struct smb2_sess_setup_req *req,
2319 struct smb2_sess_setup_rsp *rsp)
2320 {
2321 struct ksmbd_conn *conn = work->conn;
2322 struct ksmbd_session *sess = work->sess;
2323 char *in_blob, *out_blob;
2324 char channel_key[CIFS_KEY_SIZE] = {};
2325 char reauth_key[CIFS_KEY_SIZE] = {};
2326 char *auth_key = conn->binding ? channel_key :
2327 (work->session_setup_reauth ? reauth_key : sess->sess_key);
2328 u64 prev_sess_id;
2329 bool binding = conn->binding;
2330 int in_len, out_len;
2331 int retval;
2332
2333 in_blob = (char *)&req->hdr.ProtocolId +
2334 le16_to_cpu(req->SecurityBufferOffset);
2335 in_len = le16_to_cpu(req->SecurityBufferLength);
2336 out_blob = (char *)&rsp->hdr.ProtocolId +
2337 le16_to_cpu(rsp->SecurityBufferOffset);
2338 out_len = work->response_sz - work->next_smb2_rsp_hdr_off -
2339 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
2340
2341 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
2342 out_blob, &out_len, auth_key);
2343 if (retval) {
2344 ksmbd_debug(SMB, "krb5 authentication failed\n");
2345 if (retval != -EKEYREJECTED)
2346 retval = -EPERM;
2347 goto out;
2348 }
2349
2350 /* Check previous session */
2351 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
2352 if (prev_sess_id && prev_sess_id != sess->id)
2353 destroy_previous_session(conn, sess->user, prev_sess_id);
2354
2355 rsp->SecurityBufferLength = cpu_to_le16(out_len);
2356
2357 /*
2358 * If session state is SMB2_SESSION_VALID, We can assume
2359 * that it is reauthentication. And the user/password
2360 * has been verified, so return it here.
2361 */
2362 if (sess->state == SMB2_SESSION_VALID && !work->session_setup_reauth) {
2363 if (conn->binding)
2364 goto binding_session;
2365 return 0;
2366 }
2367
2368 /*
2369 * Reauthentication verifies the new Kerberos credentials but keeps
2370 * the established SMB session keys.
2371 */
2372 if (work->session_setup_reauth) {
2373 retval = 0;
2374 goto out;
2375 }
2376
2377 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
2378 (conn->sign || server_conf.enforced_signing)) ||
2379 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
2380 sess->sign = true;
2381
2382 if (smb3_encryption_negotiated(conn) &&
2383 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2384 conn->ops->generate_encryptionkey(conn, sess);
2385 sess->enc = true;
2386 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
2387 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
2388 sess->sign = false;
2389 }
2390
2391 binding_session:
2392 if (conn->dialect >= SMB30_PROT_ID) {
2393 retval = register_session_channel(sess, conn, auth_key);
2394 if (retval)
2395 goto out;
2396 }
2397
2398 if (conn->ops->generate_signingkey) {
2399 retval = conn->ops->generate_signingkey(sess, conn);
2400 if (retval) {
2401 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
2402 retval = -EINVAL;
2403 goto out;
2404 }
2405 }
2406
2407 if (!ksmbd_conn_lookup_dialect(conn)) {
2408 pr_err("fail to verify the dialect\n");
2409 retval = -ENOENT;
2410 goto out;
2411 }
2412 retval = 0;
2413 out:
2414 memzero_explicit(reauth_key, sizeof(reauth_key));
2415 if (binding)
2416 memzero_explicit(channel_key, sizeof(channel_key));
2417 return retval;
2418 }
2419 #else
krb5_authenticate(struct ksmbd_work * work,struct smb2_sess_setup_req * req,struct smb2_sess_setup_rsp * rsp)2420 static int krb5_authenticate(struct ksmbd_work *work,
2421 struct smb2_sess_setup_req *req,
2422 struct smb2_sess_setup_rsp *rsp)
2423 {
2424 return -EOPNOTSUPP;
2425 }
2426 #endif
2427
smb2_sess_setup(struct ksmbd_work * work)2428 int smb2_sess_setup(struct ksmbd_work *work)
2429 {
2430 struct ksmbd_conn *conn = work->conn;
2431 struct smb2_sess_setup_req *req;
2432 struct smb2_sess_setup_rsp *rsp;
2433 struct ksmbd_session *sess;
2434 struct negotiate_message *negblob;
2435 unsigned int negblob_len, negblob_off;
2436 int rc = 0;
2437
2438 ksmbd_debug(SMB, "Received smb2 session setup request\n");
2439
2440 if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
2441 work->send_no_response = 1;
2442 return rc;
2443 }
2444
2445 WORK_BUFFERS(work, req, rsp);
2446
2447 rsp->StructureSize = cpu_to_le16(9);
2448 rsp->SessionFlags = 0;
2449 rsp->SecurityBufferOffset = cpu_to_le16(72);
2450 rsp->SecurityBufferLength = 0;
2451
2452 ksmbd_conn_lock(conn);
2453 if (!req->hdr.SessionId) {
2454 sess = ksmbd_smb2_session_create();
2455 if (!sess) {
2456 rc = -ENOMEM;
2457 goto out_err;
2458 }
2459 rsp->hdr.SessionId = cpu_to_le64(sess->id);
2460 rc = ksmbd_session_register(conn, sess);
2461 if (rc)
2462 goto out_err;
2463
2464 conn->binding = false;
2465 } else if (conn->dialect >= SMB30_PROT_ID &&
2466 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2467 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
2468 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
2469
2470 sess = ksmbd_session_lookup_slowpath(sess_id);
2471 if (!sess) {
2472 rc = -ENOENT;
2473 goto out_err;
2474 }
2475
2476 if (conn->dialect != sess->dialect) {
2477 rc = -EINVAL;
2478 goto out_err;
2479 }
2480
2481 if (conn->dialect == SMB311_PROT_ID) {
2482 struct channel *chann;
2483 unsigned long index;
2484
2485 down_read(&sess->chann_lock);
2486 xa_for_each(&sess->ksmbd_chann_list, index, chann) {
2487 if (conn->cipher_type != chann->conn->cipher_type)
2488 rc = -EINVAL;
2489 break;
2490 }
2491 up_read(&sess->chann_lock);
2492 if (rc)
2493 goto out_err;
2494 }
2495
2496 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
2497 rc = -EINVAL;
2498 goto out_err;
2499 }
2500
2501 if (memcmp(conn->ClientGUID, sess->ClientGUID,
2502 SMB2_CLIENT_GUID_SIZE)) {
2503 rc = -ENOENT;
2504 goto out_err;
2505 }
2506
2507 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
2508 rc = -EACCES;
2509 goto out_err;
2510 }
2511
2512 if (sess->state == SMB2_SESSION_EXPIRED) {
2513 rc = -EFAULT;
2514 goto out_err;
2515 }
2516
2517 if (ksmbd_conn_need_reconnect(conn)) {
2518 rc = -EFAULT;
2519 ksmbd_user_session_put(sess);
2520 sess = NULL;
2521 goto out_err;
2522 }
2523
2524 if (is_ksmbd_session_in_connection(conn, sess_id)) {
2525 rc = -EACCES;
2526 goto out_err;
2527 }
2528
2529 if (user_guest(sess->user)) {
2530 rc = -EOPNOTSUPP;
2531 goto out_err;
2532 }
2533
2534 conn->binding = true;
2535 } else if ((conn->dialect < SMB30_PROT_ID ||
2536 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2537 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2538 sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2539 if (sess) {
2540 int sign_ret;
2541
2542 work->sess = sess;
2543 if (sess->dialect >= SMB30_PROT_ID)
2544 sign_ret = smb3_check_sign_req(work);
2545 else
2546 sign_ret = smb2_check_sign_req(work);
2547 if (sess->state != SMB2_SESSION_VALID ||
2548 !(req->hdr.Flags & SMB2_FLAGS_SIGNED) ||
2549 !sign_ret) {
2550 ksmbd_user_session_put(sess);
2551 work->sess = NULL;
2552 sess = NULL;
2553 }
2554 }
2555 rc = -EACCES;
2556 goto out_err;
2557 } else {
2558 sess = ksmbd_session_lookup(conn,
2559 le64_to_cpu(req->hdr.SessionId));
2560 if (!sess) {
2561 sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2562 if (sess && !lookup_chann_list(sess, conn)) {
2563 ksmbd_user_session_put(sess);
2564 sess = NULL;
2565 }
2566 }
2567 if (!sess) {
2568 rc = -ENOENT;
2569 goto out_err;
2570 }
2571
2572 if (sess->state == SMB2_SESSION_EXPIRED) {
2573 if (sess->kerberos_expiry &&
2574 ktime_get_real_seconds() >= sess->kerberos_expiry) {
2575 work->session_setup_reauth = true;
2576 } else {
2577 rc = -EFAULT;
2578 goto out_err;
2579 }
2580 }
2581
2582 if (ksmbd_conn_need_reconnect(conn)) {
2583 rc = -EFAULT;
2584 ksmbd_user_session_put(sess);
2585 sess = NULL;
2586 goto out_err;
2587 }
2588
2589 conn->binding = false;
2590 }
2591 work->sess = sess;
2592
2593 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
2594 negblob_len = le16_to_cpu(req->SecurityBufferLength);
2595 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
2596 rc = -EINVAL;
2597 goto out_err;
2598 }
2599
2600 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
2601 negblob_off);
2602
2603 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
2604 if (conn->mechToken) {
2605 negblob = (struct negotiate_message *)conn->mechToken;
2606 negblob_len = conn->mechTokenLen;
2607 }
2608 }
2609
2610 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
2611 rc = -EINVAL;
2612 goto out_err;
2613 }
2614
2615 if (server_conf.auth_mechs & conn->auth_mechs) {
2616 rc = generate_preauth_hash(work);
2617 if (rc)
2618 goto out_err;
2619
2620 if (conn->preferred_auth_mech &
2621 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
2622 rc = krb5_authenticate(work, req, rsp);
2623 if (rc)
2624 goto out_err;
2625
2626 if (!ksmbd_conn_need_reconnect(conn)) {
2627 ksmbd_conn_set_good(conn);
2628 sess->state = SMB2_SESSION_VALID;
2629 }
2630 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
2631 if (negblob->MessageType == NtLmNegotiate) {
2632 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
2633 if (rc)
2634 goto out_err;
2635 rsp->hdr.Status =
2636 STATUS_MORE_PROCESSING_REQUIRED;
2637 } else if (negblob->MessageType == NtLmAuthenticate) {
2638 rc = ntlm_authenticate(work, req, rsp);
2639 if (rc)
2640 goto out_err;
2641
2642 if (!ksmbd_conn_need_reconnect(conn)) {
2643 ksmbd_conn_set_good(conn);
2644 sess->state = SMB2_SESSION_VALID;
2645 }
2646 if (conn->binding) {
2647 struct preauth_session *preauth_sess;
2648
2649 preauth_sess =
2650 ksmbd_preauth_session_lookup(conn, sess->id);
2651 if (preauth_sess) {
2652 list_del(&preauth_sess->preauth_entry);
2653 kfree_sensitive(preauth_sess);
2654 }
2655 }
2656 } else {
2657 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
2658 le32_to_cpu(negblob->MessageType));
2659 rc = -EINVAL;
2660 }
2661 } else {
2662 /* TODO: need one more negotiation */
2663 pr_err("Not support the preferred authentication\n");
2664 rc = -EINVAL;
2665 }
2666 } else {
2667 pr_err("Not support authentication\n");
2668 rc = -EINVAL;
2669 }
2670
2671 out_err:
2672 if (rc == -EINVAL)
2673 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2674 else if (rc == -ENOENT)
2675 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
2676 else if (rc == -EACCES)
2677 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
2678 else if (rc == -EFAULT)
2679 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
2680 else if (rc == -ENOMEM || rc == -ENOSPC)
2681 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2682 else if (rc == -EOPNOTSUPP)
2683 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
2684 else if (rc == -EKEYREJECTED)
2685 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2686 else if (rc)
2687 rsp->hdr.Status = STATUS_LOGON_FAILURE;
2688 if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED ||
2689 (rsp->hdr.Status == STATUS_INVALID_PARAMETER &&
2690 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) &&
2691 (req->hdr.Flags & SMB2_FLAGS_SIGNED))
2692 rsp->hdr.Flags |= SMB2_FLAGS_SIGNED;
2693
2694 if (conn->mechToken) {
2695 kfree(conn->mechToken);
2696 conn->mechToken = NULL;
2697 }
2698
2699 if (rc < 0) {
2700 if (sess && conn->dialect == SMB311_PROT_ID &&
2701 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2702 struct preauth_session *preauth_sess;
2703
2704 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2705 if (preauth_sess) {
2706 list_del(&preauth_sess->preauth_entry);
2707 kfree_sensitive(preauth_sess);
2708 }
2709 }
2710
2711 /*
2712 * SecurityBufferOffset should be set to zero
2713 * in session setup error response.
2714 */
2715 rsp->SecurityBufferOffset = 0;
2716
2717 if (sess) {
2718 bool try_delay = false;
2719
2720 /*
2721 * To avoid dictionary attacks (repeated session setups rapidly sent) to
2722 * connect to server, ksmbd make a delay of a 5 seconds on session setup
2723 * failure to make it harder to send enough random connection requests
2724 * to break into a server.
2725 */
2726 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
2727 try_delay = true;
2728
2729 /*
2730 * For binding requests, session belongs to another
2731 * connection. Do not expire it.
2732 */
2733 if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2734 sess->last_active = jiffies;
2735 sess->kerberos_expiry = 0;
2736 sess->state = SMB2_SESSION_EXPIRED;
2737 }
2738 /*
2739 * Keep the binding session reference until the response is
2740 * signed and sent. Error responses for a signed binding
2741 * request are signed with the existing session signing key.
2742 */
2743 if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) ||
2744 work->sess != sess) {
2745 ksmbd_user_session_put(sess);
2746 work->sess = NULL;
2747 }
2748 if (try_delay) {
2749 ksmbd_conn_set_need_reconnect(conn);
2750 ssleep(5);
2751 ksmbd_conn_set_need_setup(conn);
2752 }
2753 }
2754 smb2_set_err_rsp(work);
2755 conn->binding = false;
2756 } else {
2757 unsigned int iov_len;
2758
2759 if (rsp->SecurityBufferLength)
2760 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
2761 le16_to_cpu(rsp->SecurityBufferLength);
2762 else
2763 iov_len = sizeof(struct smb2_sess_setup_rsp);
2764 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
2765 if (rc)
2766 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2767 }
2768
2769 ksmbd_conn_unlock(conn);
2770 return rc;
2771 }
2772
2773 /**
2774 * smb2_tree_connect() - handler for smb2 tree connect command
2775 * @work: smb work containing smb request buffer
2776 *
2777 * Return: 0 on success, otherwise error
2778 */
smb2_tree_connect(struct ksmbd_work * work)2779 int smb2_tree_connect(struct ksmbd_work *work)
2780 {
2781 struct ksmbd_conn *conn = work->conn;
2782 struct smb2_tree_connect_req *req;
2783 struct smb2_tree_connect_rsp *rsp;
2784 struct ksmbd_session *sess = work->sess;
2785 char *treename = NULL, *name = NULL;
2786 struct ksmbd_tree_conn_status status;
2787 struct ksmbd_share_config *share = NULL;
2788 int rc = -EINVAL;
2789
2790 ksmbd_debug(SMB, "Received smb2 tree connect request\n");
2791
2792 WORK_BUFFERS(work, req, rsp);
2793
2794 treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
2795 le16_to_cpu(req->PathLength), true,
2796 conn->local_nls);
2797 if (IS_ERR(treename)) {
2798 pr_err("treename is NULL\n");
2799 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2800 goto out_err1;
2801 }
2802
2803 name = ksmbd_extract_sharename(conn->um, treename);
2804 if (IS_ERR(name)) {
2805 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2806 goto out_err1;
2807 }
2808
2809 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
2810 name, treename);
2811
2812 status = ksmbd_tree_conn_connect(work, name);
2813 if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
2814 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
2815 share = status.tree_conn->share_conf;
2816
2817 /* A share that requires encryption needs a negotiated SMB3 cipher. */
2818 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_ENCRYPT_DATA) &&
2819 !smb3_encryption_negotiated(conn)) {
2820 ksmbd_tree_conn_disconnect(sess, status.tree_conn);
2821 status.tree_conn = NULL;
2822 share = NULL;
2823 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2824 goto out_err1;
2825 }
2826 } else
2827 goto out_err1;
2828
2829 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2830 ksmbd_debug(SMB, "IPC share path request\n");
2831 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2832 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2833 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2834 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2835 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2836 FILE_SYNCHRONIZE_LE;
2837 } else {
2838 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2839 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2840 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2841 if (test_tree_conn_flag(status.tree_conn,
2842 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2843 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2844 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2845 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2846 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2847 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2848 FILE_SYNCHRONIZE_LE;
2849 }
2850 }
2851
2852 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2853 if (conn->posix_ext_supported)
2854 status.tree_conn->posix_extensions = true;
2855
2856 down_write(&sess->tree_conns_lock);
2857 status.tree_conn->t_state = TREE_CONNECTED;
2858 up_write(&sess->tree_conns_lock);
2859 rsp->StructureSize = cpu_to_le16(16);
2860 out_err1:
2861 /*
2862 * A configured CA share is not continuously available until persistent
2863 * open recovery, ownership fencing, and failover are implemented.
2864 */
2865 rsp->Capabilities = 0;
2866 rsp->Reserved = 0;
2867 /* default manual caching */
2868 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2869 /* Tell the client that READ requests may request compressed responses. */
2870 if (conn->dialect == SMB311_PROT_ID &&
2871 conn->compress_algorithm != SMB3_COMPRESS_NONE)
2872 rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
2873 if (share && test_share_config_flag(share,
2874 KSMBD_SHARE_FLAG_HIDE_UNREADABLE))
2875 rsp->ShareFlags |=
2876 cpu_to_le32(SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM);
2877 if (share && test_share_config_flag(share,
2878 KSMBD_SHARE_FLAG_ENCRYPT_DATA))
2879 rsp->ShareFlags |=
2880 cpu_to_le32(SMB2_SHAREFLAG_ENCRYPT_DATA);
2881
2882 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2883 if (rc) {
2884 if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
2885 down_write(&sess->tree_conns_lock);
2886 status.tree_conn->t_state = TREE_DISCONNECTED;
2887 up_write(&sess->tree_conns_lock);
2888 ksmbd_tree_conn_disconnect(sess, status.tree_conn);
2889 status.tree_conn = NULL;
2890 }
2891 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2892 }
2893
2894 if (!IS_ERR(treename))
2895 kfree(treename);
2896 if (!IS_ERR(name))
2897 kfree(name);
2898
2899 switch (status.ret) {
2900 case KSMBD_TREE_CONN_STATUS_OK:
2901 rsp->hdr.Status = STATUS_SUCCESS;
2902 rc = 0;
2903 break;
2904 case -ESTALE:
2905 case -ENOENT:
2906 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2907 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2908 break;
2909 case -ENOMEM:
2910 case KSMBD_TREE_CONN_STATUS_NOMEM:
2911 rsp->hdr.Status = STATUS_NO_MEMORY;
2912 break;
2913 case KSMBD_TREE_CONN_STATUS_ERROR:
2914 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2915 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2916 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2917 break;
2918 case -EINVAL:
2919 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2920 break;
2921 default:
2922 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2923 }
2924
2925 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2926 smb2_set_err_rsp(work);
2927
2928 return rc;
2929 }
2930
2931 /**
2932 * smb2_create_open_flags() - convert smb open flags to unix open flags
2933 * @file_present: is file already present
2934 * @access: file access flags
2935 * @disposition: file disposition flags
2936 * @may_flags: set with MAY_ flags
2937 * @coptions: file creation options
2938 * @mode: file mode
2939 *
2940 * Return: file open flags
2941 */
smb2_create_open_flags(bool file_present,__le32 access,__le32 disposition,int * may_flags,__le32 coptions,umode_t mode)2942 static int smb2_create_open_flags(bool file_present, __le32 access,
2943 __le32 disposition,
2944 int *may_flags,
2945 __le32 coptions,
2946 umode_t mode)
2947 {
2948 int oflags = O_NONBLOCK | O_LARGEFILE;
2949
2950 if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2951 access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2952 ksmbd_debug(SMB, "Discard write access to a directory\n");
2953 }
2954
2955 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2956 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2957 oflags |= O_RDWR;
2958 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2959 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2960 oflags |= O_WRONLY;
2961 *may_flags = MAY_OPEN | MAY_WRITE;
2962 } else {
2963 oflags |= O_RDONLY;
2964 *may_flags = MAY_OPEN | MAY_READ;
2965 }
2966
2967 if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2968 oflags |= O_PATH;
2969
2970 if (file_present) {
2971 switch (disposition & FILE_CREATE_MASK_LE) {
2972 case FILE_OPEN_LE:
2973 case FILE_CREATE_LE:
2974 break;
2975 case FILE_SUPERSEDE_LE:
2976 case FILE_OVERWRITE_LE:
2977 case FILE_OVERWRITE_IF_LE:
2978 oflags |= O_TRUNC;
2979 break;
2980 default:
2981 break;
2982 }
2983 } else {
2984 switch (disposition & FILE_CREATE_MASK_LE) {
2985 case FILE_SUPERSEDE_LE:
2986 case FILE_CREATE_LE:
2987 case FILE_OPEN_IF_LE:
2988 case FILE_OVERWRITE_IF_LE:
2989 oflags |= O_CREAT;
2990 break;
2991 case FILE_OPEN_LE:
2992 case FILE_OVERWRITE_LE:
2993 oflags &= ~O_CREAT;
2994 break;
2995 default:
2996 break;
2997 }
2998 }
2999
3000 return oflags;
3001 }
3002
3003 /**
3004 * smb2_tree_disconnect() - handler for smb tree connect request
3005 * @work: smb work containing request buffer
3006 *
3007 * Return: 0 on success, otherwise error
3008 */
smb2_tree_disconnect(struct ksmbd_work * work)3009 int smb2_tree_disconnect(struct ksmbd_work *work)
3010 {
3011 struct smb2_tree_disconnect_rsp *rsp;
3012 struct smb2_tree_disconnect_req *req;
3013 struct ksmbd_session *sess = work->sess;
3014 struct ksmbd_tree_connect *tcon = work->tcon;
3015 int err;
3016
3017 ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
3018
3019 WORK_BUFFERS(work, req, rsp);
3020
3021 if (!tcon) {
3022 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
3023
3024 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3025 err = -ENOENT;
3026 goto err_out;
3027 }
3028
3029 ksmbd_close_tree_conn_fds(work);
3030
3031 down_write(&sess->tree_conns_lock);
3032 if (tcon->t_state == TREE_DISCONNECTED) {
3033 up_write(&sess->tree_conns_lock);
3034 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3035 err = -ENOENT;
3036 goto err_out;
3037 }
3038
3039 tcon->t_state = TREE_DISCONNECTED;
3040 up_write(&sess->tree_conns_lock);
3041
3042 err = ksmbd_tree_conn_disconnect(sess, tcon);
3043 if (err) {
3044 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3045 goto err_out;
3046 }
3047
3048 rsp->StructureSize = cpu_to_le16(4);
3049 err = ksmbd_iov_pin_rsp(work, rsp,
3050 sizeof(struct smb2_tree_disconnect_rsp));
3051 if (err) {
3052 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3053 goto err_out;
3054 }
3055
3056 return 0;
3057
3058 err_out:
3059 smb2_set_err_rsp(work);
3060 return err;
3061
3062 }
3063
3064 /**
3065 * smb2_session_logoff() - handler for session log off request
3066 * @work: smb work containing request buffer
3067 *
3068 * Return: 0 on success, otherwise error
3069 */
smb2_session_logoff(struct ksmbd_work * work)3070 int smb2_session_logoff(struct ksmbd_work *work)
3071 {
3072 struct ksmbd_conn *conn = work->conn;
3073 struct ksmbd_session *sess = work->sess;
3074 struct smb2_logoff_req *req;
3075 struct smb2_logoff_rsp *rsp;
3076 int err;
3077
3078 WORK_BUFFERS(work, req, rsp);
3079
3080 ksmbd_debug(SMB, "Received smb2 session logoff request\n");
3081
3082 ksmbd_conn_lock(conn);
3083 if (!ksmbd_conn_good(conn)) {
3084 ksmbd_conn_unlock(conn);
3085 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3086 smb2_set_err_rsp(work);
3087 return -ENOENT;
3088 }
3089 ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT);
3090 ksmbd_conn_unlock(conn);
3091
3092 ksmbd_close_session_fds(work);
3093 ksmbd_conn_wait_idle(conn);
3094
3095 if (ksmbd_tree_conn_session_logoff(sess)) {
3096 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
3097 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3098 smb2_set_err_rsp(work);
3099 return -ENOENT;
3100 }
3101
3102 down_write(&conn->session_lock);
3103 sess->kerberos_expiry = 0;
3104 sess->state = SMB2_SESSION_EXPIRED;
3105 up_write(&conn->session_lock);
3106
3107 ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP);
3108
3109 rsp->StructureSize = cpu_to_le16(4);
3110 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
3111 if (err) {
3112 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3113 smb2_set_err_rsp(work);
3114 return err;
3115 }
3116 return 0;
3117 }
3118
3119 /**
3120 * create_smb2_pipe() - create IPC pipe
3121 * @work: smb work containing request buffer
3122 *
3123 * Return: 0 on success, otherwise error
3124 */
create_smb2_pipe(struct ksmbd_work * work)3125 static noinline int create_smb2_pipe(struct ksmbd_work *work)
3126 {
3127 struct smb2_create_rsp *rsp;
3128 struct smb2_create_req *req;
3129 int id = -1;
3130 int err;
3131 char *name;
3132
3133 WORK_BUFFERS(work, req, rsp);
3134
3135 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
3136 1, work->conn->local_nls);
3137 if (IS_ERR(name)) {
3138 rsp->hdr.Status = STATUS_NO_MEMORY;
3139 err = PTR_ERR(name);
3140 goto out;
3141 }
3142
3143 id = ksmbd_session_rpc_open(work->sess, name);
3144 if (id < 0) {
3145 /*
3146 * mdssvc (Spotlight) is a routine, expected probe from macOS
3147 * that we deliberately don't support -- it's disabled at the
3148 * __rpc_method() level (mgmt/user_session.c), but this
3149 * generic failure log would otherwise still fire on every
3150 * single probe regardless.
3151 */
3152 if (!(id == -ENOENT && (!strcmp(name, "\\mdssvc") ||
3153 !strcmp(name, "mdssvc"))))
3154 pr_err("Unable to open RPC pipe: %d\n", id);
3155 err = id;
3156 goto out;
3157 }
3158
3159 rsp->hdr.Status = STATUS_SUCCESS;
3160 rsp->StructureSize = cpu_to_le16(89);
3161 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
3162 rsp->Flags = 0;
3163 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
3164
3165 rsp->CreationTime = cpu_to_le64(0);
3166 rsp->LastAccessTime = cpu_to_le64(0);
3167 rsp->ChangeTime = cpu_to_le64(0);
3168 rsp->AllocationSize = cpu_to_le64(0);
3169 rsp->EndofFile = cpu_to_le64(0);
3170 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
3171 rsp->Reserved2 = 0;
3172 rsp->VolatileFileId = id;
3173 rsp->PersistentFileId = 0;
3174 rsp->CreateContextsOffset = 0;
3175 rsp->CreateContextsLength = 0;
3176
3177 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
3178 if (err)
3179 goto out;
3180
3181 kfree(name);
3182 return 0;
3183
3184 out:
3185 switch (err) {
3186 case -EINVAL:
3187 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3188 break;
3189 case -ENOENT:
3190 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3191 break;
3192 case -ENOSPC:
3193 case -ENOMEM:
3194 rsp->hdr.Status = STATUS_NO_MEMORY;
3195 break;
3196 }
3197
3198 if (id >= 0)
3199 ksmbd_session_rpc_close(work->sess, id);
3200
3201 if (!IS_ERR(name))
3202 kfree(name);
3203
3204 smb2_set_err_rsp(work);
3205 return err;
3206 }
3207
smb2_is_private_ea(const char * name,size_t name_len)3208 static bool smb2_is_private_ea(const char *name, size_t name_len)
3209 {
3210 if (name_len == SD_PREFIX_LEN &&
3211 !strncasecmp(name, SD_PREFIX, SD_PREFIX_LEN))
3212 return true;
3213 if (name_len == DOS_ATTRIBUTE_PREFIX_LEN &&
3214 !strncasecmp(name, DOS_ATTRIBUTE_PREFIX,
3215 DOS_ATTRIBUTE_PREFIX_LEN))
3216 return true;
3217 if (name_len >= STREAM_PREFIX_LEN &&
3218 !strncasecmp(name, STREAM_PREFIX, STREAM_PREFIX_LEN))
3219 return true;
3220
3221 return false;
3222 }
3223
3224 /**
3225 * smb2_set_ea() - handler for setting extended attributes using set
3226 * info command
3227 * @eabuf: set info command buffer
3228 * @buf_len: set info command buffer length
3229 * @path: dentry path for get ea
3230 * @get_write: get write access to a mount
3231 *
3232 * Return: 0 on success, otherwise error
3233 */
smb2_set_ea(struct smb2_ea_info * eabuf,unsigned int buf_len,const struct path * path,bool get_write)3234 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
3235 const struct path *path, bool get_write)
3236 {
3237 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3238 char *attr_name = NULL, *value;
3239 int rc = 0;
3240 unsigned int next = 0;
3241
3242 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
3243 le16_to_cpu(eabuf->EaValueLength))
3244 return -EINVAL;
3245
3246 attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
3247 if (!attr_name)
3248 return -ENOMEM;
3249
3250 do {
3251 if (!eabuf->EaNameLength)
3252 goto next;
3253
3254 ksmbd_debug(SMB,
3255 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
3256 eabuf->name, eabuf->EaNameLength,
3257 le16_to_cpu(eabuf->EaValueLength),
3258 le32_to_cpu(eabuf->NextEntryOffset));
3259
3260 if (eabuf->EaNameLength >
3261 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
3262 rc = -EINVAL;
3263 break;
3264 }
3265 if (smb2_is_private_ea(eabuf->name, eabuf->EaNameLength)) {
3266 rc = -EACCES;
3267 break;
3268 }
3269
3270 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
3271 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
3272 eabuf->EaNameLength);
3273 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
3274 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
3275
3276 if (!eabuf->EaValueLength) {
3277 rc = ksmbd_vfs_casexattr_len(idmap,
3278 path->dentry,
3279 attr_name,
3280 XATTR_USER_PREFIX_LEN +
3281 eabuf->EaNameLength);
3282
3283 /* delete the EA only when it exits */
3284 if (rc > 0) {
3285 rc = ksmbd_vfs_remove_xattr(idmap,
3286 path,
3287 attr_name,
3288 get_write);
3289
3290 if (rc < 0) {
3291 ksmbd_debug(SMB,
3292 "remove xattr failed(%d)\n",
3293 rc);
3294 break;
3295 }
3296 }
3297
3298 /* if the EA doesn't exist, just do nothing. */
3299 rc = 0;
3300 } else {
3301 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
3302 le16_to_cpu(eabuf->EaValueLength),
3303 0, get_write);
3304 if (rc < 0) {
3305 ksmbd_debug(SMB,
3306 "ksmbd_vfs_setxattr is failed(%d)\n",
3307 rc);
3308 break;
3309 }
3310 }
3311
3312 next:
3313 next = le32_to_cpu(eabuf->NextEntryOffset);
3314 if (next == 0 || buf_len < next)
3315 break;
3316 buf_len -= next;
3317 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
3318 if (buf_len < sizeof(struct smb2_ea_info)) {
3319 rc = -EINVAL;
3320 break;
3321 }
3322
3323 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
3324 le16_to_cpu(eabuf->EaValueLength)) {
3325 rc = -EINVAL;
3326 break;
3327 }
3328 } while (next != 0);
3329
3330 kfree(attr_name);
3331 return rc;
3332 }
3333
smb2_set_stream_name_xattr(const struct path * path,struct ksmbd_file * fp,char * stream_name,int s_type)3334 static noinline int smb2_set_stream_name_xattr(const struct path *path,
3335 struct ksmbd_file *fp,
3336 char *stream_name, int s_type)
3337 {
3338 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3339 size_t xattr_stream_size;
3340 char *xattr_stream_name;
3341 int rc;
3342
3343 rc = ksmbd_vfs_xattr_stream_name(stream_name,
3344 &xattr_stream_name,
3345 &xattr_stream_size,
3346 s_type);
3347 if (rc)
3348 return rc;
3349
3350 fp->stream.name = xattr_stream_name;
3351 fp->stream.size = xattr_stream_size;
3352
3353 /* Check if there is stream prefix in xattr space */
3354 rc = ksmbd_vfs_casexattr_len(idmap,
3355 path->dentry,
3356 xattr_stream_name,
3357 xattr_stream_size);
3358 if (rc >= 0)
3359 return 0;
3360
3361 if (fp->cdoption == FILE_OPEN_LE) {
3362 if (!strcmp(stream_name, "AFP_AfpInfo") &&
3363 test_share_config_flag(fp->tcon->share_conf,
3364 KSMBD_SHARE_FLAG_TIME_MACHINE)) {
3365 /*
3366 * Synthesize an empty AFP_AfpInfo xattr on first access.
3367 * type=0/creator=0 tells macOS to use the file extension
3368 * for icon and type detection.
3369 *
3370 * Scoped to TIME_MACHINE shares, matching the rest of
3371 * the AAPL series -- conn->is_aapl alone isn't a safe
3372 * gate here, since the pre-existing narrow UniqueId=0
3373 * path can also set it on ordinary, non-Time-Machine
3374 * shares whenever a Mac client happens to negotiate
3375 * AAPL there too.
3376 */
3377 static const u8 afpinfo_empty[60] = {
3378 0x00, 0x05, 0x16, 0x07, /* magic 0x00051607 BE */
3379 0x00, 0x02, 0x00, 0x00, /* version 0x00020000 BE */
3380 };
3381 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name,
3382 (void *)afpinfo_empty,
3383 sizeof(afpinfo_empty), 0, false);
3384 return rc < 0 ? rc : 0;
3385 }
3386 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
3387 return -EBADF;
3388 }
3389
3390 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
3391 if (rc < 0)
3392 pr_err("Failed to store XATTR stream name :%d\n", rc);
3393 return 0;
3394 }
3395
3396 /*
3397 * fp->stream.size is the byte length of the mangled xattr *name*
3398 * (used as attr_name_len when looking the xattr up), not the size of
3399 * the xattr's value. Reporting it as EndOfFile/AllocationSize for a
3400 * stream handle is wrong -- query the xattr's actual value length
3401 * instead.
3402 */
ksmbd_stream_eof(struct ksmbd_file * fp)3403 static loff_t ksmbd_stream_eof(struct ksmbd_file *fp)
3404 {
3405 ssize_t slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
3406 fp->filp->f_path.dentry,
3407 fp->stream.name,
3408 fp->stream.size);
3409 return slen < 0 ? 0 : (loff_t)slen;
3410 }
3411
smb2_remove_smb_xattrs(const struct path * path)3412 static int smb2_remove_smb_xattrs(const struct path *path)
3413 {
3414 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3415 char *name, *xattr_list = NULL;
3416 ssize_t xattr_list_len;
3417 int err = 0;
3418
3419 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
3420 if (xattr_list_len < 0) {
3421 goto out;
3422 } else if (!xattr_list_len) {
3423 ksmbd_debug(SMB, "empty xattr in the file\n");
3424 goto out;
3425 }
3426
3427 for (name = xattr_list; name - xattr_list < xattr_list_len;
3428 name += strlen(name) + 1) {
3429 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
3430
3431 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
3432 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
3433 STREAM_PREFIX_LEN)) {
3434 err = ksmbd_vfs_remove_xattr(idmap, path,
3435 name, true);
3436 if (err)
3437 ksmbd_debug(SMB, "remove xattr failed : %s\n",
3438 name);
3439 }
3440 }
3441 out:
3442 kvfree(xattr_list);
3443 return err;
3444 }
3445
smb2_create_truncate(const struct path * path)3446 static int smb2_create_truncate(const struct path *path)
3447 {
3448 int rc = vfs_truncate(path, 0);
3449
3450 if (rc) {
3451 pr_err("vfs_truncate failed, rc %d\n", rc);
3452 return rc;
3453 }
3454
3455 rc = smb2_remove_smb_xattrs(path);
3456 if (rc == -EOPNOTSUPP)
3457 rc = 0;
3458 if (rc)
3459 ksmbd_debug(SMB,
3460 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
3461 rc);
3462 return rc;
3463 }
3464
smb2_new_xattrs(struct ksmbd_tree_connect * tcon,const struct path * path,struct ksmbd_file * fp)3465 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
3466 struct ksmbd_file *fp)
3467 {
3468 struct xattr_dos_attrib da = {0};
3469 int rc;
3470
3471 if (!test_share_config_flag(tcon->share_conf,
3472 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
3473 return;
3474
3475 da.version = 4;
3476 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
3477 da.itime = da.create_time = fp->create_time;
3478 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
3479 XATTR_DOSINFO_ITIME;
3480
3481 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
3482 if (rc)
3483 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
3484 }
3485
smb2_parent_compressed(struct ksmbd_tree_connect * tcon,const struct path * path)3486 static bool smb2_parent_compressed(struct ksmbd_tree_connect *tcon,
3487 const struct path *path)
3488 {
3489 struct dentry *parent = dget_parent(path->dentry);
3490 struct file_kattr fa = { .flags_valid = true };
3491 struct xattr_dos_attrib da;
3492 bool compressed = false;
3493 int rc;
3494
3495 rc = vfs_fileattr_get(parent, &fa);
3496 if (!rc && fa.flags & FS_COMPR_FL) {
3497 compressed = true;
3498 goto out;
3499 }
3500
3501 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), parent, &da);
3502 if (rc > 0 && da.attr & FILE_ATTRIBUTE_COMPRESSED)
3503 compressed = true;
3504
3505 out:
3506 dput(parent);
3507 return compressed;
3508 }
3509
smb2_update_xattrs(struct ksmbd_tree_connect * tcon,const struct path * path,struct ksmbd_file * fp)3510 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
3511 const struct path *path, struct ksmbd_file *fp)
3512 {
3513 struct xattr_dos_attrib da = {};
3514 bool store_dos_attrs = test_share_config_flag(tcon->share_conf,
3515 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS);
3516 int rc;
3517
3518 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
3519
3520 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
3521 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
3522 path->dentry, &da);
3523 if (rc > 0) {
3524 if (store_dos_attrs) {
3525 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
3526 fp->create_time = da.create_time;
3527 fp->itime = da.itime;
3528 } else {
3529 fp->f_ci->m_fattr &=
3530 ~(FILE_ATTRIBUTE_COMPRESSED_LE |
3531 FILE_ATTRIBUTE_SPARSE_FILE_LE);
3532 fp->f_ci->m_fattr |=
3533 cpu_to_le32(da.attr &
3534 (FILE_ATTRIBUTE_COMPRESSED |
3535 FILE_ATTRIBUTE_SPARSE_FILE));
3536 }
3537 }
3538 }
3539
smb2_creat(struct ksmbd_work * work,struct path * path,char * name,int open_flags,umode_t posix_mode,bool is_dir)3540 static int smb2_creat(struct ksmbd_work *work,
3541 struct path *path, char *name, int open_flags,
3542 umode_t posix_mode, bool is_dir)
3543 {
3544 struct ksmbd_tree_connect *tcon = work->tcon;
3545 struct ksmbd_share_config *share = tcon->share_conf;
3546 umode_t mode;
3547 int rc;
3548
3549 if (!(open_flags & O_CREAT))
3550 return -EBADF;
3551
3552 ksmbd_debug(SMB, "file does not exist, so creating\n");
3553 if (is_dir == true) {
3554 ksmbd_debug(SMB, "creating directory\n");
3555
3556 mode = share_config_directory_mode(share, posix_mode);
3557 rc = ksmbd_vfs_mkdir(work, name, mode);
3558 if (rc)
3559 return rc;
3560 } else {
3561 ksmbd_debug(SMB, "creating regular file\n");
3562
3563 mode = share_config_create_mode(share, posix_mode);
3564 rc = ksmbd_vfs_create(work, name, mode);
3565 if (rc)
3566 return rc;
3567 }
3568
3569 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
3570 if (rc) {
3571 pr_err("cannot get linux path (%s), err = %d\n",
3572 name, rc);
3573 return rc;
3574 }
3575 return 0;
3576 }
3577
smb2_create_sd_buffer(struct ksmbd_work * work,struct smb2_create_req * req,const struct path * path)3578 static int smb2_create_sd_buffer(struct ksmbd_work *work,
3579 struct smb2_create_req *req,
3580 const struct path *path)
3581 {
3582 struct create_context *context;
3583 struct create_sd_buf_req *sd_buf;
3584
3585 if (!req->CreateContextsOffset)
3586 return -ENOENT;
3587
3588 /* Parse SD BUFFER create contexts */
3589 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
3590 if (!context)
3591 return -ENOENT;
3592 else if (IS_ERR(context))
3593 return PTR_ERR(context);
3594
3595 ksmbd_debug(SMB,
3596 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
3597 sd_buf = (struct create_sd_buf_req *)context;
3598 if (le16_to_cpu(context->DataOffset) +
3599 le32_to_cpu(context->DataLength) <
3600 sizeof(struct create_sd_buf_req))
3601 return -EINVAL;
3602 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
3603 le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
3604 }
3605
ksmbd_acls_fattr(struct smb_fattr * fattr,struct mnt_idmap * idmap,struct inode * inode)3606 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
3607 struct mnt_idmap *idmap,
3608 struct inode *inode)
3609 {
3610 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
3611 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
3612
3613 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
3614 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
3615 fattr->cf_mode = inode->i_mode;
3616 fattr->cf_acls = NULL;
3617 fattr->cf_dacls = NULL;
3618
3619 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
3620 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
3621 if (S_ISDIR(inode->i_mode))
3622 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
3623 }
3624 }
3625
3626 enum {
3627 DURABLE_RECONN_V2 = 1,
3628 DURABLE_RECONN,
3629 DURABLE_REQ_V2,
3630 DURABLE_REQ,
3631 };
3632
3633 struct durable_info {
3634 struct ksmbd_file *fp;
3635 unsigned short int type;
3636 bool persistent;
3637 bool reconnected;
3638 bool replay;
3639 bool replay_consumed;
3640 bool app_instance_id;
3641 bool app_instance_version_valid;
3642 unsigned int timeout;
3643 char *CreateGuid;
3644 char AppInstanceId[SMB2_CREATE_GUID_SIZE];
3645 u64 app_instance_version_high;
3646 u64 app_instance_version_low;
3647 };
3648
smb2_check_durable_replay(struct ksmbd_work * work,struct ksmbd_file * fp,struct lease_ctx_info * lc,bool persistent)3649 static int smb2_check_durable_replay(struct ksmbd_work *work,
3650 struct ksmbd_file *fp,
3651 struct lease_ctx_info *lc,
3652 bool persistent)
3653 {
3654 struct oplock_info *opinfo;
3655 int ret = 0;
3656
3657 if (!fp->is_durable && !fp->is_persistent)
3658 return -EACCES;
3659
3660 if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false)
3661 return -EACCES;
3662
3663 if (fp->is_persistent && !persistent)
3664 return -EINVAL;
3665
3666 opinfo = opinfo_get(fp);
3667 if (!opinfo)
3668 return 0;
3669
3670 if (opinfo->sess && opinfo->sess->id != work->sess->id) {
3671 ret = -ENOEXEC;
3672 goto out;
3673 }
3674
3675 if (opinfo->is_lease) {
3676 if (!lc ||
3677 memcmp(opinfo->o_lease->lease_key, lc->lease_key,
3678 SMB2_LEASE_KEY_SIZE)) {
3679 ret = -EACCES;
3680 goto out;
3681 }
3682 } else {
3683 if (lc) {
3684 ret = -EACCES;
3685 goto out;
3686 }
3687
3688 if (fp->is_durable && opinfo->level != SMB2_OPLOCK_LEVEL_BATCH)
3689 ret = -EACCES;
3690 }
3691 out:
3692 opinfo_put(opinfo);
3693 return ret;
3694 }
3695
smb2_durable_replay_consumed(struct ksmbd_file * fp)3696 static bool smb2_durable_replay_consumed(struct ksmbd_file *fp)
3697 {
3698 bool consumed;
3699
3700 spin_lock(&fp->f_lock);
3701 consumed = fp->durable_replay_consumed;
3702 spin_unlock(&fp->f_lock);
3703
3704 return consumed;
3705 }
3706
smb2_mark_durable_replay_consumed(struct ksmbd_file * fp)3707 static void smb2_mark_durable_replay_consumed(struct ksmbd_file *fp)
3708 {
3709 spin_lock(&fp->f_lock);
3710 fp->durable_replay_consumed = true;
3711 spin_unlock(&fp->f_lock);
3712 }
3713
smb2_durable_replay_differs(struct ksmbd_file * fp,struct smb2_create_req * req)3714 static bool smb2_durable_replay_differs(struct ksmbd_file *fp,
3715 struct smb2_create_req *req)
3716 {
3717 return fp->cdoption != req->CreateDisposition ||
3718 fp->create_file_attributes != req->FileAttributes;
3719 }
3720
parse_durable_handle_context(struct ksmbd_work * work,struct smb2_create_req * req,struct lease_ctx_info * lc,struct durable_info * dh_info)3721 static int parse_durable_handle_context(struct ksmbd_work *work,
3722 struct smb2_create_req *req,
3723 struct lease_ctx_info *lc,
3724 struct durable_info *dh_info)
3725 {
3726 struct ksmbd_conn *conn = work->conn;
3727 struct create_context *context;
3728 int dh_idx, err = 0;
3729 u64 persistent_id = 0;
3730 int req_op_level;
3731 static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
3732
3733 req_op_level = req->RequestedOplockLevel;
3734 for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
3735 dh_idx++) {
3736 context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
3737 if (IS_ERR(context)) {
3738 err = PTR_ERR(context);
3739 goto out;
3740 }
3741 if (!context)
3742 continue;
3743
3744 switch (dh_idx) {
3745 case DURABLE_RECONN_V2:
3746 {
3747 struct create_durable_handle_reconnect_v2 *recon_v2;
3748 u32 flags;
3749
3750 if (dh_info->type == DURABLE_RECONN ||
3751 dh_info->type == DURABLE_REQ_V2) {
3752 err = -EINVAL;
3753 goto out;
3754 }
3755
3756 if (le32_to_cpu(context->DataLength) <
3757 sizeof(recon_v2->dcontext)) {
3758 err = -EINVAL;
3759 goto out;
3760 }
3761
3762 recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
3763 flags = le32_to_cpu(recon_v2->dcontext.Flags);
3764 if (flags & ~SMB2_DHANDLE_FLAG_PERSISTENT) {
3765 err = -EINVAL;
3766 goto out;
3767 }
3768 dh_info->persistent = flags & SMB2_DHANDLE_FLAG_PERSISTENT;
3769 persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
3770 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3771 if (!dh_info->fp) {
3772 ksmbd_debug(SMB, "Failed to get durable handle state\n");
3773 err = -EBADF;
3774 goto out;
3775 }
3776
3777 /* A zero VolatileFileId means that the client did not specify it. */
3778 if (recon_v2->dcontext.Fid.VolatileFileId &&
3779 dh_info->fp->durable_volatile_id !=
3780 recon_v2->dcontext.Fid.VolatileFileId) {
3781 err = -EBADF;
3782 ksmbd_put_durable_fd(dh_info->fp);
3783 goto out;
3784 }
3785
3786 if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
3787 SMB2_CREATE_GUID_SIZE)) {
3788 err = -EBADF;
3789 ksmbd_put_durable_fd(dh_info->fp);
3790 goto out;
3791 }
3792
3793 /* A persistent reconnect must match the original open type. */
3794 if (dh_info->fp->is_persistent != dh_info->persistent) {
3795 err = dh_info->persistent ? -EINVAL : -EBADF;
3796 ksmbd_put_durable_fd(dh_info->fp);
3797 goto out;
3798 }
3799
3800 dh_info->type = dh_idx;
3801 dh_info->reconnected = true;
3802 ksmbd_debug(SMB,
3803 "reconnect v2 Persistent-id from reconnect = %llu\n",
3804 persistent_id);
3805 break;
3806 }
3807 case DURABLE_RECONN:
3808 {
3809 create_durable_reconn_t *recon;
3810
3811 if (dh_info->type == DURABLE_RECONN_V2 ||
3812 dh_info->type == DURABLE_REQ_V2) {
3813 err = -EINVAL;
3814 goto out;
3815 }
3816
3817 if (le32_to_cpu(context->DataLength) <
3818 sizeof(recon->Data)) {
3819 err = -EINVAL;
3820 goto out;
3821 }
3822
3823 recon = (create_durable_reconn_t *)context;
3824 persistent_id = recon->Data.Fid.PersistentFileId;
3825 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3826 if (!dh_info->fp) {
3827 ksmbd_debug(SMB, "Failed to get durable handle state\n");
3828 err = -EBADF;
3829 goto out;
3830 }
3831
3832 /* A zero VolatileFileId means that the client did not specify it. */
3833 if (recon->Data.Fid.VolatileFileId &&
3834 dh_info->fp->durable_volatile_id !=
3835 recon->Data.Fid.VolatileFileId) {
3836 err = -EBADF;
3837 ksmbd_put_durable_fd(dh_info->fp);
3838 goto out;
3839 }
3840
3841 dh_info->type = dh_idx;
3842 dh_info->reconnected = true;
3843 ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
3844 persistent_id);
3845 break;
3846 }
3847 case DURABLE_REQ_V2:
3848 {
3849 struct create_durable_req_v2 *durable_v2_blob;
3850
3851 if (dh_info->type == DURABLE_RECONN ||
3852 dh_info->type == DURABLE_RECONN_V2) {
3853 err = -EINVAL;
3854 goto out;
3855 }
3856
3857 if (le32_to_cpu(context->DataLength) <
3858 sizeof(durable_v2_blob->dcontext)) {
3859 err = -EINVAL;
3860 goto out;
3861 }
3862
3863 durable_v2_blob =
3864 (struct create_durable_req_v2 *)context;
3865 if (le32_to_cpu(durable_v2_blob->dcontext.Flags) &
3866 ~SMB2_DHANDLE_FLAG_PERSISTENT) {
3867 err = -EINVAL;
3868 goto out;
3869 }
3870 ksmbd_debug(SMB, "Request for durable v2 open\n");
3871 dh_info->CreateGuid = durable_v2_blob->dcontext.CreateGuid;
3872 dh_info->persistent =
3873 le32_to_cpu(durable_v2_blob->dcontext.Flags) &
3874 SMB2_DHANDLE_FLAG_PERSISTENT;
3875 dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
3876 if (dh_info->fp) {
3877 if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
3878 SMB2_CLIENT_GUID_SIZE)) {
3879 if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
3880 err = -ENOEXEC;
3881 ksmbd_put_durable_fd(dh_info->fp);
3882 goto out;
3883 }
3884
3885 if (dh_info->fp->f_state == FP_NEW) {
3886 /* Original CREATE is still pending. */
3887 ksmbd_put_durable_fd(dh_info->fp);
3888 err = -EAGAIN;
3889 goto out;
3890 }
3891
3892 if (!dh_info->fp->is_durable &&
3893 !dh_info->fp->is_persistent) {
3894 /*
3895 * A DurableHandleReqV2 CREATE can complete
3896 * without granting durability (for example, if
3897 * it requested no oplock). Its CreateGuid still
3898 * identifies a completed CREATE for replay.
3899 */
3900 if (dh_info->fp->conn &&
3901 ksmbd_vfs_compare_durable_owner(
3902 dh_info->fp, work->sess->user)) {
3903 if (smb2_durable_replay_consumed(
3904 dh_info->fp)) {
3905 ksmbd_put_durable_fd(dh_info->fp);
3906 dh_info->fp = NULL;
3907 dh_info->type = dh_idx;
3908 dh_info->replay_consumed = true;
3909 break;
3910 }
3911 if (smb2_durable_replay_differs(
3912 dh_info->fp, req))
3913 smb2_mark_durable_replay_consumed(
3914 dh_info->fp);
3915 dh_info->replay = true;
3916 dh_info->type = dh_idx;
3917 goto out;
3918 }
3919 ksmbd_put_durable_fd(dh_info->fp);
3920 err = -EACCES;
3921 goto out;
3922 }
3923
3924 if (dh_info->fp->conn &&
3925 smb2_durable_replay_consumed(dh_info->fp)) {
3926 ksmbd_put_durable_fd(dh_info->fp);
3927 dh_info->fp = NULL;
3928 dh_info->type = dh_idx;
3929 dh_info->replay_consumed = true;
3930 break;
3931 }
3932
3933 err = smb2_check_durable_replay(work,
3934 dh_info->fp,
3935 lc,
3936 dh_info->persistent);
3937 if (err) {
3938 ksmbd_put_durable_fd(dh_info->fp);
3939 goto out;
3940 }
3941
3942 if (dh_info->fp->conn) {
3943 if (smb2_durable_replay_differs(dh_info->fp,
3944 req))
3945 smb2_mark_durable_replay_consumed(
3946 dh_info->fp);
3947 dh_info->replay = true;
3948 } else {
3949 dh_info->reconnected = true;
3950 }
3951 dh_info->type = dh_idx;
3952 goto out;
3953 }
3954 ksmbd_put_durable_fd(dh_info->fp);
3955 dh_info->fp = NULL;
3956 }
3957
3958 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3959 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3960 dh_info->timeout =
3961 le32_to_cpu(durable_v2_blob->dcontext.Timeout);
3962 dh_info->type = dh_idx;
3963 }
3964 break;
3965 }
3966 case DURABLE_REQ:
3967 if (dh_info->type == DURABLE_RECONN)
3968 goto out;
3969 if (dh_info->type == DURABLE_RECONN_V2 ||
3970 dh_info->type == DURABLE_REQ_V2) {
3971 err = -EINVAL;
3972 goto out;
3973 }
3974
3975 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3976 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3977 ksmbd_debug(SMB, "Request for durable open\n");
3978 dh_info->type = dh_idx;
3979 }
3980 }
3981 }
3982
3983 out:
3984 return err;
3985 }
3986
parse_app_instance_id(struct smb2_create_req * req,struct durable_info * dh_info)3987 static int parse_app_instance_id(struct smb2_create_req *req,
3988 struct durable_info *dh_info)
3989 {
3990 struct create_context *context;
3991 char *data;
3992
3993 context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
3994 SMB2_CREATE_GUID_SIZE);
3995 if (IS_ERR(context))
3996 return PTR_ERR(context);
3997 if (!context)
3998 return 0;
3999
4000 if (le32_to_cpu(context->DataLength) < 20)
4001 return -EINVAL;
4002
4003 data = (char *)context + le16_to_cpu(context->DataOffset);
4004 if (data[0] != 20 || data[1])
4005 return -EINVAL;
4006
4007 memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
4008 dh_info->app_instance_id = true;
4009 return 0;
4010 }
4011
parse_app_instance_version(struct smb2_create_req * req,struct durable_info * dh_info)4012 static int parse_app_instance_version(struct smb2_create_req *req,
4013 struct durable_info *dh_info)
4014 {
4015 struct create_context *context;
4016 char *data;
4017
4018 context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_VERSION,
4019 SMB2_CREATE_GUID_SIZE);
4020 if (IS_ERR(context))
4021 return PTR_ERR(context);
4022 if (!context)
4023 return 0;
4024
4025 if (le32_to_cpu(context->DataLength) < 24)
4026 return -EINVAL;
4027
4028 data = (char *)context + le16_to_cpu(context->DataOffset);
4029 if (get_unaligned_le16(data) != 24 ||
4030 get_unaligned_le16(data + 2) != 0)
4031 return -EINVAL;
4032
4033 dh_info->app_instance_version_high = get_unaligned_le64(data + 8);
4034 dh_info->app_instance_version_low = get_unaligned_le64(data + 16);
4035 dh_info->app_instance_version_valid = true;
4036 return 0;
4037 }
4038
smb2_handle_app_instance_id(struct smb2_create_rsp * rsp,struct durable_info * dh_info)4039 static int smb2_handle_app_instance_id(struct smb2_create_rsp *rsp,
4040 struct durable_info *dh_info)
4041 {
4042 struct ksmbd_file *old_fp;
4043 bool reject = false;
4044
4045 if (!dh_info->app_instance_id)
4046 return 0;
4047
4048 old_fp = ksmbd_lookup_fd_app_instance_id(dh_info->AppInstanceId);
4049 if (!old_fp)
4050 return 0;
4051
4052 if (dh_info->app_instance_version_valid) {
4053 if (old_fp->app_instance_version_valid &&
4054 (dh_info->app_instance_version_high <
4055 old_fp->app_instance_version_high ||
4056 (dh_info->app_instance_version_high ==
4057 old_fp->app_instance_version_high &&
4058 dh_info->app_instance_version_low <=
4059 old_fp->app_instance_version_low)))
4060 reject = true;
4061 } else if (old_fp->app_instance_version_valid) {
4062 reject = true;
4063 }
4064
4065 ksmbd_put_durable_fd(old_fp);
4066 if (reject) {
4067 rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED;
4068 return -EIO;
4069 }
4070
4071 return ksmbd_close_fd_app_instance_id(dh_info->AppInstanceId);
4072 }
4073
4074 /**
4075 * smb2_open() - handler for smb file open request
4076 * @work: smb work containing request buffer
4077 *
4078 * Return: 0 on success, otherwise error
4079 */
smb2_open(struct ksmbd_work * work)4080 int smb2_open(struct ksmbd_work *work)
4081 {
4082 struct ksmbd_conn *conn = work->conn;
4083 struct ksmbd_session *sess = work->sess;
4084 struct ksmbd_tree_connect *tcon = work->tcon;
4085 struct smb2_create_req *req;
4086 struct smb2_create_rsp *rsp;
4087 struct path path;
4088 struct ksmbd_share_config *share = tcon->share_conf;
4089 struct ksmbd_file *fp = NULL;
4090 struct file *filp = NULL;
4091 struct mnt_idmap *idmap = NULL;
4092 struct kstat stat;
4093 struct create_context *context;
4094 struct lease_ctx_info *lc = NULL;
4095 struct create_ea_buf_req *ea_buf = NULL;
4096 struct oplock_info *opinfo;
4097 struct durable_info dh_info = {0};
4098 __le32 *next_ptr = NULL;
4099 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
4100 int rc = 0;
4101 int contxt_cnt = 0, query_disk_id = 0;
4102 bool maximal_access_ctxt = false, posix_ctxt = false;
4103 bool aapl_ctxt = false;
4104 bool durable_rsp = true;
4105 __u64 aapl_req_bitmap = 0, aapl_client_caps = 0;
4106 int s_type = 0;
4107 int next_off = 0;
4108 char *name = NULL;
4109 char *stream_name = NULL;
4110 bool file_present = false, created = false, already_permitted = false;
4111 int share_ret, need_truncate = 0;
4112 u64 time, alloc_size = 0;
4113 umode_t posix_mode = 0;
4114 __le32 daccess, maximal_access = 0;
4115 u32 dos_attr;
4116 int iov_len = 0;
4117
4118 ksmbd_debug(SMB, "Received smb2 create request\n");
4119
4120 WORK_BUFFERS(work, req, rsp);
4121
4122 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
4123 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
4124 ksmbd_debug(SMB, "invalid flag in chained command\n");
4125 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4126 smb2_set_err_rsp(work);
4127 return -EINVAL;
4128 }
4129
4130 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
4131 ksmbd_debug(SMB, "IPC pipe create request\n");
4132 return create_smb2_pipe(work);
4133 }
4134
4135 if (req->CreateContextsOffset && tcon->posix_extensions) {
4136 context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
4137 if (IS_ERR(context)) {
4138 rc = PTR_ERR(context);
4139 goto err_out2;
4140 } else if (context) {
4141 struct create_posix *posix = (struct create_posix *)context;
4142
4143 if (le16_to_cpu(context->DataOffset) +
4144 le32_to_cpu(context->DataLength) <
4145 sizeof(struct create_posix) - 4) {
4146 rc = -EINVAL;
4147 goto err_out2;
4148 }
4149 ksmbd_debug(SMB, "get posix context\n");
4150
4151 posix_mode = le32_to_cpu(posix->Mode);
4152 posix_ctxt = true;
4153 }
4154 }
4155
4156 if (req->NameLength) {
4157 name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
4158 le16_to_cpu(req->NameLength),
4159 work->conn->local_nls);
4160 if (IS_ERR(name)) {
4161 rc = PTR_ERR(name);
4162 name = NULL;
4163 goto err_out2;
4164 }
4165
4166 ksmbd_debug(SMB, "converted name = %s\n", name);
4167
4168 if (posix_ctxt == false) {
4169 if (strchr(name, ':')) {
4170 if (!test_share_config_flag(work->tcon->share_conf,
4171 KSMBD_SHARE_FLAG_STREAMS)) {
4172 rc = -EBADF;
4173 goto err_out2;
4174 }
4175 rc = parse_stream_name(name, &stream_name, &s_type);
4176 if (rc < 0)
4177 goto err_out2;
4178 }
4179
4180 rc = ksmbd_validate_filename(name);
4181 if (rc < 0)
4182 goto err_out2;
4183 }
4184
4185 if (ksmbd_share_veto_filename(share, name)) {
4186 rc = -ENOENT;
4187 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
4188 name);
4189 goto err_out2;
4190 }
4191 } else {
4192 name = kstrdup("", KSMBD_DEFAULT_GFP);
4193 if (!name) {
4194 rc = -ENOMEM;
4195 goto err_out2;
4196 }
4197 }
4198
4199 req_op_level = req->RequestedOplockLevel;
4200
4201 if (req->CreateContextsOffset) {
4202 rc = parse_app_instance_id(req, &dh_info);
4203 if (rc)
4204 goto err_out2;
4205 rc = parse_app_instance_version(req, &dh_info);
4206 if (rc)
4207 goto err_out2;
4208 }
4209
4210 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
4211 req->CreateContextsOffset) {
4212 lc = parse_lease_state(req);
4213 if (IS_ERR(lc)) {
4214 rc = PTR_ERR(lc);
4215 lc = NULL;
4216 goto err_out2;
4217 }
4218 if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4219 kfree(lc);
4220 lc = NULL;
4221 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
4222 req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4223 }
4224 rc = parse_durable_handle_context(work, req, lc, &dh_info);
4225 if (rc) {
4226 ksmbd_debug(SMB, "error parsing durable handle context\n");
4227 goto err_out2;
4228 }
4229
4230 if (dh_info.replay == true) {
4231 fp = dh_info.fp;
4232 if (ksmbd_override_fsids(work)) {
4233 rc = -ENOMEM;
4234 goto err_out2;
4235 }
4236
4237 file_info = FILE_OPENED;
4238 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4239 if (rc)
4240 goto err_out2;
4241
4242 goto reconnected_fp;
4243 }
4244
4245 if (dh_info.reconnected == true) {
4246 rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
4247 lc, sess->user, name);
4248 if (rc)
4249 goto err_out2;
4250
4251 rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
4252 if (rc)
4253 goto err_out2;
4254
4255 fp = dh_info.fp;
4256
4257 if (ksmbd_override_fsids(work)) {
4258 rc = -ENOMEM;
4259 goto err_out2;
4260 }
4261
4262 file_info = FILE_OPENED;
4263
4264 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4265 if (rc)
4266 goto err_out2;
4267
4268 goto reconnected_fp;
4269 }
4270
4271 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
4272 lc = parse_lease_state(req);
4273 if (IS_ERR(lc)) {
4274 rc = PTR_ERR(lc);
4275 lc = NULL;
4276 goto err_out2;
4277 }
4278 if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4279 kfree(lc);
4280 lc = NULL;
4281 req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4282 }
4283 }
4284
4285 if (dh_info.app_instance_id && !dh_info.reconnected &&
4286 !dh_info.replay) {
4287 rc = smb2_handle_app_instance_id(rsp, &dh_info);
4288 if (rc)
4289 goto err_out2;
4290 }
4291
4292 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
4293 pr_err("Invalid impersonationlevel : 0x%x\n",
4294 le32_to_cpu(req->ImpersonationLevel));
4295 rc = -EIO;
4296 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
4297 goto err_out2;
4298 }
4299
4300 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
4301 pr_err("Invalid create options : 0x%x\n",
4302 le32_to_cpu(req->CreateOptions));
4303 rc = -EINVAL;
4304 goto err_out2;
4305 } else {
4306 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
4307 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
4308 req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;
4309
4310 if (req->CreateOptions &
4311 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
4312 FILE_RESERVE_OPFILTER_LE)) {
4313 rc = -EOPNOTSUPP;
4314 goto err_out2;
4315 }
4316
4317 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4318 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
4319 rc = -EINVAL;
4320 goto err_out2;
4321 }
4322 }
4323 }
4324
4325 if (le32_to_cpu(req->CreateDisposition) >
4326 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
4327 pr_err("Invalid create disposition : 0x%x\n",
4328 le32_to_cpu(req->CreateDisposition));
4329 rc = -EINVAL;
4330 goto err_out2;
4331 }
4332
4333 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
4334 pr_err("Invalid desired access : 0x%x\n",
4335 le32_to_cpu(req->DesiredAccess));
4336 rc = -EACCES;
4337 goto err_out2;
4338 }
4339
4340 if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
4341 req->CreateDisposition == FILE_OPEN_IF_LE &&
4342 !req->FileAttributes) {
4343 rc = -EACCES;
4344 goto err_out2;
4345 }
4346
4347 if (req->FileAttributes &&
4348 (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
4349 pr_err("Invalid file attribute : 0x%x\n",
4350 le32_to_cpu(req->FileAttributes));
4351 rc = -EINVAL;
4352 goto err_out2;
4353 }
4354
4355 if (req->CreateContextsOffset) {
4356 /* Parse non-durable handle create contexts */
4357 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
4358 if (IS_ERR(context)) {
4359 rc = PTR_ERR(context);
4360 goto err_out2;
4361 } else if (context) {
4362 ea_buf = (struct create_ea_buf_req *)context;
4363 if (le16_to_cpu(context->DataOffset) +
4364 le32_to_cpu(context->DataLength) <
4365 sizeof(struct create_ea_buf_req)) {
4366 rc = -EINVAL;
4367 goto err_out2;
4368 }
4369 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
4370 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4371 rc = -EACCES;
4372 goto err_out2;
4373 }
4374 }
4375
4376 context = smb2_find_context_vals(req,
4377 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
4378 if (IS_ERR(context)) {
4379 rc = PTR_ERR(context);
4380 goto err_out2;
4381 } else if (context) {
4382 ksmbd_debug(SMB,
4383 "get query maximal access context\n");
4384 maximal_access_ctxt = 1;
4385 }
4386
4387 context = smb2_find_context_vals(req,
4388 SMB2_CREATE_TIMEWARP_REQUEST, 4);
4389 if (IS_ERR(context)) {
4390 rc = PTR_ERR(context);
4391 goto err_out2;
4392 } else if (context) {
4393 ksmbd_debug(SMB, "get timewarp context\n");
4394 rc = -EBADF;
4395 goto err_out2;
4396 }
4397 }
4398
4399 if (ksmbd_override_fsids(work)) {
4400 rc = -ENOMEM;
4401 goto err_out2;
4402 }
4403
4404 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4405 &path, 1);
4406
4407 /*
4408 * A durable handle opened with delete-on-close is preserved across a
4409 * disconnect so it can be reclaimed by a durable reconnect. When a new
4410 * delete-on-close open for the same name arrives instead, the
4411 * disconnected handle must give way: close it so its delete-on-close
4412 * removes the file, then re-resolve so this open can create a fresh one.
4413 */
4414 if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
4415 (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4416 req->CreateDisposition == FILE_OPEN_IF_LE) &&
4417 ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
4418 path_put(&path);
4419 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4420 &path, 1);
4421 }
4422
4423 if (!rc) {
4424 file_present = true;
4425
4426 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
4427 struct xattr_dos_attrib da;
4428
4429 /*
4430 * If file exists with under flags, return access
4431 * denied error.
4432 */
4433 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4434 req->CreateDisposition == FILE_OPEN_IF_LE) {
4435 rc = -EACCES;
4436 goto err_out;
4437 }
4438
4439 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4440 ksmbd_debug(SMB,
4441 "User does not have write permission\n");
4442 rc = -EACCES;
4443 goto err_out;
4444 }
4445
4446 if (test_share_config_flag(tcon->share_conf,
4447 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
4448 ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path.mnt),
4449 path.dentry, &da) > 0 &&
4450 da.attr & FILE_ATTRIBUTE_READONLY) {
4451 rsp->hdr.Status = STATUS_CANNOT_DELETE;
4452 rc = -EACCES;
4453 goto err_out;
4454 }
4455 } else if (d_is_symlink(path.dentry)) {
4456 rc = -EACCES;
4457 goto err_out;
4458 }
4459
4460 idmap = mnt_idmap(path.mnt);
4461 } else {
4462 if (rc != -ENOENT)
4463 goto err_out;
4464 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
4465 name, rc);
4466 rc = 0;
4467 }
4468
4469 if (!file_present && req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
4470 req->FileAttributes & FILE_ATTRIBUTE_READONLY_LE) {
4471 rsp->hdr.Status = STATUS_CANNOT_DELETE;
4472 rc = -EACCES;
4473 goto err_out;
4474 }
4475
4476 /*
4477 * An explicit ::$DATA suffix names the unnamed data stream and is
4478 * canonicalized to a NULL stream name (base file), but the request
4479 * still has to be validated against the data-stream type, e.g. opening
4480 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
4481 * STATUS_NOT_A_DIRECTORY.
4482 */
4483 if (stream_name || s_type == DATA_STREAM) {
4484 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4485 if (s_type == DATA_STREAM) {
4486 rc = -EIO;
4487 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4488 }
4489 } else {
4490 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
4491 !stream_name && s_type == DATA_STREAM) {
4492 rc = -EIO;
4493 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4494 }
4495 }
4496
4497 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
4498 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
4499 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4500 rc = -EIO;
4501 }
4502
4503 if (rc < 0)
4504 goto err_out;
4505 }
4506
4507 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
4508 S_ISDIR(d_inode(path.dentry)->i_mode) &&
4509 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4510 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
4511 name, req->CreateOptions);
4512 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4513 rc = -EIO;
4514 goto err_out;
4515 }
4516
4517 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
4518 !(req->CreateDisposition == FILE_CREATE_LE) &&
4519 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
4520 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4521 rc = -EIO;
4522 goto err_out;
4523 }
4524
4525 if (!stream_name && file_present &&
4526 req->CreateDisposition == FILE_CREATE_LE) {
4527 rc = -EEXIST;
4528 goto err_out;
4529 }
4530
4531 daccess = smb_map_generic_desired_access(req->DesiredAccess);
4532
4533 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4534 rc = smb_check_perm_dacl(conn, &path, &daccess,
4535 req->DesiredAccess,
4536 sess->user->uid, false);
4537 if (rc)
4538 goto err_out;
4539
4540 if (maximal_access_ctxt) {
4541 maximal_access = FILE_MAXIMAL_ACCESS_LE;
4542 rc = smb_check_perm_dacl(conn, &path, &maximal_access,
4543 0, sess->user->uid, false);
4544 if (rc)
4545 goto err_out;
4546
4547 /*
4548 * smb_check_perm_dacl() returns success without
4549 * touching *pdaccess when the object has no stored
4550 * NT ACL, leaving maximal_access as the
4551 * FILE_MAXIMAL_ACCESS_LE request sentinel instead of
4552 * a real access mask.
4553 */
4554 if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
4555 ksmbd_vfs_query_maximal_access(idmap, path.dentry,
4556 &maximal_access);
4557 }
4558 }
4559
4560 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
4561 if (!file_present) {
4562 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
4563 } else {
4564 ksmbd_vfs_query_maximal_access(idmap,
4565 path.dentry,
4566 &daccess);
4567 already_permitted = true;
4568 }
4569 maximal_access = daccess;
4570 }
4571
4572 open_flags = smb2_create_open_flags(file_present, daccess,
4573 req->CreateDisposition,
4574 &may_flags,
4575 req->CreateOptions,
4576 file_present ? d_inode(path.dentry)->i_mode : 0);
4577
4578 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4579 if (open_flags & (O_CREAT | O_TRUNC)) {
4580 ksmbd_debug(SMB,
4581 "User does not have write permission\n");
4582 rc = -EACCES;
4583 goto err_out;
4584 }
4585 }
4586
4587 /*create file if not present */
4588 if (!file_present) {
4589 rc = smb2_creat(work, &path, name, open_flags,
4590 posix_mode,
4591 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
4592 if (rc) {
4593 if (rc == -ENOENT) {
4594 rc = -EIO;
4595 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
4596 }
4597 goto err_out;
4598 }
4599
4600 created = true;
4601 idmap = mnt_idmap(path.mnt);
4602 if (ea_buf) {
4603 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
4604 sizeof(struct smb2_ea_info)) {
4605 rc = -EINVAL;
4606 goto err_out;
4607 }
4608
4609 rc = smb2_set_ea(&ea_buf->ea,
4610 le32_to_cpu(ea_buf->ccontext.DataLength),
4611 &path, false);
4612 if (rc == -EOPNOTSUPP)
4613 rc = 0;
4614 else if (rc)
4615 goto err_out;
4616 }
4617 } else if (!already_permitted) {
4618 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
4619 * because execute(search) permission on a parent directory,
4620 * is already granted.
4621 */
4622 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
4623 rc = inode_permission(idmap,
4624 d_inode(path.dentry),
4625 may_flags);
4626 if (rc)
4627 goto err_out;
4628
4629 if ((daccess & FILE_DELETE_LE) ||
4630 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4631 rc = inode_permission(idmap,
4632 d_inode(path.dentry->d_parent),
4633 MAY_EXEC | MAY_WRITE);
4634 if (rc)
4635 goto err_out;
4636 }
4637 }
4638 }
4639
4640 rc = ksmbd_query_inode_status(path.dentry->d_parent);
4641 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
4642 rc = -EBUSY;
4643 goto err_out;
4644 }
4645
4646 rc = 0;
4647 filp = dentry_open(&path, open_flags, current_cred());
4648 if (IS_ERR(filp)) {
4649 rc = PTR_ERR(filp);
4650 pr_err("dentry open for dir failed, rc %d\n", rc);
4651 goto err_out;
4652 }
4653
4654 if (file_present) {
4655 if (!(open_flags & O_TRUNC))
4656 file_info = FILE_OPENED;
4657 else
4658 file_info = FILE_OVERWRITTEN;
4659
4660 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
4661 FILE_SUPERSEDE_LE)
4662 file_info = FILE_SUPERSEDED;
4663 } else if (open_flags & O_CREAT) {
4664 file_info = FILE_CREATED;
4665 }
4666
4667 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
4668
4669 /* Obtain Volatile-ID */
4670 fp = ksmbd_open_fd(work, filp);
4671 if (IS_ERR(fp)) {
4672 fput(filp);
4673 rc = PTR_ERR(fp);
4674 fp = NULL;
4675 goto err_out;
4676 }
4677
4678 /* Get Persistent-ID */
4679 ksmbd_open_durable_fd(fp);
4680 if (!has_file_id(fp->persistent_id)) {
4681 rc = -ENOMEM;
4682 goto err_out;
4683 }
4684
4685 /*
4686 * Publish the client and create GUID before an oplock/lease break can
4687 * make this CREATE pending. A replay of that in-flight CREATE must find
4688 * this FP_NEW handle and fail with STATUS_FILE_NOT_AVAILABLE instead of
4689 * waiting on the same break again.
4690 */
4691 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
4692 if (dh_info.app_instance_id) {
4693 memcpy(fp->app_instance_id, dh_info.AppInstanceId,
4694 SMB2_CREATE_GUID_SIZE);
4695 fp->has_app_instance_id = true;
4696 }
4697 if (dh_info.app_instance_version_valid) {
4698 fp->app_instance_version_high =
4699 dh_info.app_instance_version_high;
4700 fp->app_instance_version_low = dh_info.app_instance_version_low;
4701 fp->app_instance_version_valid = true;
4702 }
4703 if (dh_info.CreateGuid) {
4704 memcpy(fp->create_guid, dh_info.CreateGuid, SMB2_CREATE_GUID_SIZE);
4705 fp->durable_replay_consumed = dh_info.replay_consumed;
4706 rc = ksmbd_vfs_set_durable_owner(fp, sess->user);
4707 if (rc)
4708 goto err_out;
4709 }
4710
4711 fp->cdoption = req->CreateDisposition;
4712 fp->create_file_attributes = req->FileAttributes;
4713 fp->daccess = daccess;
4714 fp->saccess = req->ShareAccess;
4715 fp->coption = req->CreateOptions;
4716
4717 /* Set default windows and posix acls if creating new file */
4718 if (created) {
4719 int posix_acl_rc;
4720 struct inode *inode = d_inode(path.dentry);
4721
4722 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
4723 &path,
4724 d_inode(path.dentry->d_parent));
4725 if (posix_acl_rc)
4726 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
4727
4728 rc = smb2_create_sd_buffer(work, req, &path);
4729 if (rc && rc != -ENOENT)
4730 goto err_out;
4731
4732 if (rc == -ENOENT) {
4733 if (test_share_config_flag(work->tcon->share_conf,
4734 KSMBD_SHARE_FLAG_ACL_XATTR)) {
4735 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
4736 sess->user->gid);
4737 }
4738 if (rc) {
4739 if (posix_acl_rc)
4740 ksmbd_vfs_set_init_posix_acl(idmap,
4741 &path);
4742
4743 if (test_share_config_flag(work->tcon->share_conf,
4744 KSMBD_SHARE_FLAG_ACL_XATTR)) {
4745 struct smb_fattr fattr;
4746 struct smb_ntsd *pntsd;
4747 int pntsd_size;
4748 size_t scratch_len;
4749
4750 ksmbd_acls_fattr(&fattr, idmap, inode);
4751 scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
4752 NULL, 0,
4753 OWNER_SECINFO | GROUP_SECINFO |
4754 DACL_SECINFO);
4755 if (!scratch_len || scratch_len == SIZE_MAX) {
4756 rc = -EFBIG;
4757 posix_acl_release(fattr.cf_acls);
4758 posix_acl_release(fattr.cf_dacls);
4759 goto err_out;
4760 }
4761
4762 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
4763 if (!pntsd) {
4764 rc = -ENOMEM;
4765 posix_acl_release(fattr.cf_acls);
4766 posix_acl_release(fattr.cf_dacls);
4767 goto err_out;
4768 }
4769
4770 rc = build_sec_desc(idmap,
4771 pntsd, NULL, 0,
4772 OWNER_SECINFO |
4773 GROUP_SECINFO |
4774 DACL_SECINFO,
4775 &pntsd_size, &fattr);
4776 posix_acl_release(fattr.cf_acls);
4777 posix_acl_release(fattr.cf_dacls);
4778 if (rc) {
4779 kvfree(pntsd);
4780 goto err_out;
4781 }
4782
4783 rc = ksmbd_vfs_set_sd_xattr(conn,
4784 idmap,
4785 &path,
4786 pntsd,
4787 pntsd_size,
4788 false);
4789 kvfree(pntsd);
4790 if (rc)
4791 pr_err("failed to store ntacl in xattr : %d\n",
4792 rc);
4793 }
4794 }
4795 }
4796 rc = 0;
4797 }
4798
4799 if (stream_name) {
4800 rc = smb2_set_stream_name_xattr(&path,
4801 fp,
4802 stream_name,
4803 s_type);
4804 if (rc)
4805 goto err_out;
4806 file_info = FILE_CREATED;
4807 }
4808
4809 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
4810 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
4811
4812 fp->is_posix_ctxt = posix_ctxt;
4813
4814 /* fp should be searchable through ksmbd_inode.m_fp_list
4815 * after daccess, saccess, attrib_only, and stream are
4816 * initialized.
4817 */
4818 down_write(&fp->f_ci->m_lock);
4819 list_add(&fp->node, &fp->f_ci->m_fp_list);
4820 up_write(&fp->f_ci->m_lock);
4821
4822 /* Check delete pending among previous fp before oplock break */
4823 if (ksmbd_inode_pending_delete(fp)) {
4824 rc = -EBUSY;
4825 goto err_out;
4826 }
4827
4828 if (!stream_name && daccess & FILE_DELETE_LE &&
4829 ksmbd_has_stream_without_delete_share(fp)) {
4830 rc = -EPERM;
4831 goto err_out;
4832 }
4833
4834 if (file_present || created)
4835 path_put(&path);
4836
4837 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
4838 !fp->attrib_only && !stream_name) {
4839 smb_break_all_oplock(work, fp);
4840 need_truncate = 1;
4841 }
4842
4843 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
4844 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
4845 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
4846 !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
4847 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
4848 rc = share_ret;
4849 goto err_out1;
4850 }
4851 } else {
4852 if (created && !lc)
4853 smb_send_parent_lease_break_noti(fp, NULL);
4854
4855 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
4856 if (S_ISDIR(file_inode(filp)->i_mode)) {
4857 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
4858 lc->is_dir = true;
4859 }
4860
4861 /*
4862 * Compare parent lease using parent key. If there is no
4863 * a lease that has same parent key, Send lease break
4864 * notification.
4865 */
4866 smb_send_parent_lease_break_noti(fp, lc);
4867
4868 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
4869 ksmbd_debug(SMB,
4870 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
4871 name, req_op_level, lc->req_state);
4872 rc = find_same_lease_key(conn, fp->f_ci, lc);
4873 if (rc)
4874 goto err_out1;
4875 } else if (open_flags == O_RDONLY &&
4876 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
4877 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
4878 req_op_level = SMB2_OPLOCK_LEVEL_II;
4879
4880 rc = smb_grant_oplock(work, req_op_level,
4881 fp->persistent_id, fp,
4882 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
4883 lc, share_ret,
4884 smb3_hdr_replay(&req->hdr));
4885 if (rc < 0)
4886 goto err_out1;
4887 }
4888
4889 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
4890 smb_break_all_levII_oplock_for_delete(work, fp);
4891 ksmbd_fd_set_delete_on_close(fp, file_info);
4892 }
4893
4894 if (need_truncate) {
4895 rc = smb2_create_truncate(&fp->filp->f_path);
4896 if (rc)
4897 goto err_out1;
4898 }
4899
4900 if (req->CreateContextsOffset) {
4901 struct create_alloc_size_req *az_req;
4902
4903 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
4904 SMB2_CREATE_ALLOCATION_SIZE, 4);
4905 if (IS_ERR(az_req)) {
4906 rc = PTR_ERR(az_req);
4907 goto err_out1;
4908 } else if (az_req) {
4909 int err;
4910
4911 if (le16_to_cpu(az_req->ccontext.DataOffset) +
4912 le32_to_cpu(az_req->ccontext.DataLength) <
4913 sizeof(struct create_alloc_size_req)) {
4914 rc = -EINVAL;
4915 goto err_out1;
4916 }
4917 alloc_size = le64_to_cpu(az_req->AllocationSize);
4918 fp->allocation_size_set = true;
4919 ksmbd_debug(SMB,
4920 "request smb2 create allocate size : %llu\n",
4921 alloc_size);
4922 /*
4923 * fp->filp is the base file's data fork for a stream
4924 * handle (streams are xattr-backed on the same
4925 * underlying file) -- fallocate has no meaning for a
4926 * stream and would otherwise pre-allocate storage on
4927 * the base file's data instead.
4928 */
4929 if (!ksmbd_stream_fd(fp)) {
4930 smb_break_all_levII_oplock(work, fp, 1);
4931 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
4932 alloc_size);
4933 if (err < 0)
4934 ksmbd_debug(SMB,
4935 "vfs_fallocate is failed : %d\n",
4936 err);
4937 }
4938 }
4939
4940 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
4941 if (IS_ERR(context)) {
4942 rc = PTR_ERR(context);
4943 goto err_out1;
4944 } else if (context) {
4945 ksmbd_debug(SMB, "get query on disk id context\n");
4946 query_disk_id = 1;
4947 }
4948
4949 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_TIME_MACHINE)) {
4950 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
4951 if (IS_ERR(context)) {
4952 rc = PTR_ERR(context);
4953 goto err_out1;
4954 } else if (context) {
4955 struct aapl_server_query_req *aapl_req;
4956
4957 if (le32_to_cpu(context->DataLength) <
4958 sizeof(struct aapl_server_query_req)) {
4959 rc = -EINVAL;
4960 goto err_out1;
4961 }
4962
4963 aapl_req = (struct aapl_server_query_req *)
4964 ((char *)context +
4965 le16_to_cpu(context->DataOffset));
4966 if (le32_to_cpu(aapl_req->cmd) ==
4967 SMB2_CRTCTX_AAPL_SERVER_QUERY) {
4968 conn->is_aapl = true;
4969 aapl_ctxt = true;
4970 aapl_req_bitmap = le64_to_cpu(aapl_req->req_bitmap);
4971 aapl_client_caps = le64_to_cpu(aapl_req->client_caps);
4972 }
4973 }
4974 } else if (conn->is_aapl == false) {
4975 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
4976 if (IS_ERR(context)) {
4977 rc = PTR_ERR(context);
4978 goto err_out1;
4979 } else if (context)
4980 conn->is_aapl = true;
4981 }
4982 }
4983
4984 rc = ksmbd_vfs_getattr(&path, &stat);
4985 if (rc)
4986 goto err_out1;
4987
4988 if (stat.result_mask & STATX_BTIME)
4989 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
4990 else
4991 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
4992 fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
4993 fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
4994 (alloc_size ?: stat.blocks << 9);
4995 if (created || fp->f_ci->m_fattr == 0)
4996 fp->f_ci->m_fattr =
4997 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
4998
4999 if (!created)
5000 smb2_update_xattrs(tcon, &path, fp);
5001 if (need_truncate && req->FileAttributes) {
5002 dos_attr = le32_to_cpu(req->FileAttributes);
5003 fp->f_ci->m_fattr =
5004 cpu_to_le32(smb2_get_dos_mode(&stat, dos_attr));
5005 smb2_new_xattrs(tcon, &path, fp);
5006 }
5007
5008 ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);
5009
5010 if (created) {
5011 if (fp->coption & FILE_NO_COMPRESSION_LE) {
5012 rc = ksmbd_vfs_set_compression_create(work, fp,
5013 COMPRESSION_FORMAT_NONE);
5014 if (rc)
5015 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_COMPRESSED_LE;
5016 rc = 0;
5017 } else if (smb2_parent_compressed(tcon, &path)) {
5018 rc = ksmbd_vfs_set_compression_create(work, fp,
5019 COMPRESSION_FORMAT_LZNT1);
5020 if (rc)
5021 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_COMPRESSED_LE;
5022 rc = 0;
5023 }
5024 }
5025
5026 if (created)
5027 smb2_new_xattrs(tcon, &path, fp);
5028
5029 fp->create_action = cpu_to_le32(file_info);
5030
5031 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
5032 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
5033 test_share_config_flag(work->tcon->share_conf,
5034 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY) &&
5035 (conn->vals->req_capabilities &
5036 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)) {
5037 /* MS-SMB2 3.3.5.9.10: a persistent open is durable too. */
5038 fp->is_durable = true;
5039 fp->is_persistent = true;
5040 } else {
5041 fp->is_durable = true;
5042 }
5043 if (dh_info.type == DURABLE_REQ_V2) {
5044 if (dh_info.app_instance_id)
5045 memcpy(fp->app_instance_id,
5046 dh_info.AppInstanceId,
5047 SMB2_CREATE_GUID_SIZE);
5048 if (dh_info.timeout)
5049 fp->durable_timeout =
5050 min_t(unsigned int, dh_info.timeout,
5051 DURABLE_HANDLE_MAX_TIMEOUT);
5052 else
5053 fp->durable_timeout = 60000;
5054 }
5055 }
5056
5057 /*
5058 * conn->is_aapl detection above (this function's create-context
5059 * parsing) is skipped on the reconnect path below, since a
5060 * reconnect always arrives on a fresh connection -- if the client
5061 * cares, it sends its own AAPL context on this same CREATE, which
5062 * this function's normal (non-reconnect) parsing already handles.
5063 */
5064 reconnected_fp:
5065 if (dh_info.replay)
5066 file_info = le32_to_cpu(fp->create_action);
5067 rsp->StructureSize = cpu_to_le16(89);
5068 opinfo = opinfo_get(fp);
5069 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
5070 /*
5071 * A durable CREATE replay does not modify the existing open. When
5072 * replayed without an oplock, however, its response reflects that
5073 * request and cannot include a new durable-handle response context.
5074 */
5075 if (dh_info.replay && !lc &&
5076 req_op_level == SMB2_OPLOCK_LEVEL_NONE) {
5077 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
5078 durable_rsp = false;
5079 }
5080 rsp->Flags = 0;
5081 rsp->CreateAction = cpu_to_le32(file_info);
5082 rsp->CreationTime = cpu_to_le64(fp->create_time);
5083 time = ksmbd_UnixTimeToNT(stat.atime);
5084 rsp->LastAccessTime = cpu_to_le64(time);
5085 time = ksmbd_UnixTimeToNT(stat.mtime);
5086 fp->open_mtime = time;
5087 rsp->LastWriteTime = cpu_to_le64(time);
5088 rsp->ChangeTime = cpu_to_le64(fp->change_time);
5089 /*
5090 * The cached allocation size hides filesystem rounding for the
5091 * requested allocation, but it can go stale when the file grows past
5092 * it via writes (e.g. across a durable reconnect). Refresh it once the
5093 * file exceeds the cached value, rounding the end of file up to the
5094 * volume allocation unit (the filesystem block size, matching the
5095 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
5096 * using the raw on-disk block count, which can include filesystem
5097 * preallocation and metadata rounding.
5098 */
5099 if (ksmbd_stream_fd(fp)) {
5100 loff_t seof = ksmbd_stream_eof(fp);
5101
5102 rsp->AllocationSize = cpu_to_le64((u64)seof);
5103 rsp->EndofFile = cpu_to_le64((u64)seof);
5104 } else {
5105 if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
5106 fp->allocation_size = round_up(stat.size, stat.blksize);
5107 rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
5108 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5109 }
5110 rsp->FileAttributes = fp->f_ci->m_fattr;
5111
5112 rsp->Reserved2 = 0;
5113
5114 rsp->PersistentFileId = fp->persistent_id;
5115 rsp->VolatileFileId = fp->volatile_id;
5116
5117 rsp->CreateContextsOffset = 0;
5118 rsp->CreateContextsLength = 0;
5119 iov_len = offsetof(struct smb2_create_rsp, Buffer);
5120
5121 /* If lease is request send lease context response */
5122 if (opinfo && opinfo->is_lease) {
5123 struct create_context *lease_ccontext;
5124
5125 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
5126 name, opinfo->o_lease->state);
5127 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
5128
5129 lease_ccontext = (struct create_context *)rsp->Buffer;
5130 contxt_cnt++;
5131 create_lease_buf(rsp->Buffer, opinfo->o_lease);
5132 le32_add_cpu(&rsp->CreateContextsLength,
5133 conn->vals->create_lease_size);
5134 iov_len += conn->vals->create_lease_size;
5135 next_ptr = &lease_ccontext->Next;
5136 next_off = conn->vals->create_lease_size;
5137 }
5138 opinfo_put(opinfo);
5139
5140 if (maximal_access_ctxt) {
5141 struct create_context *mxac_ccontext;
5142
5143 if (maximal_access == 0)
5144 ksmbd_vfs_query_maximal_access(idmap,
5145 path.dentry,
5146 &maximal_access);
5147 mxac_ccontext = (struct create_context *)(rsp->Buffer +
5148 le32_to_cpu(rsp->CreateContextsLength));
5149 contxt_cnt++;
5150 create_mxac_rsp_buf(rsp->Buffer +
5151 le32_to_cpu(rsp->CreateContextsLength),
5152 le32_to_cpu(maximal_access));
5153 le32_add_cpu(&rsp->CreateContextsLength,
5154 conn->vals->create_mxac_size);
5155 iov_len += conn->vals->create_mxac_size;
5156 if (next_ptr)
5157 *next_ptr = cpu_to_le32(next_off);
5158 next_ptr = &mxac_ccontext->Next;
5159 next_off = conn->vals->create_mxac_size;
5160 }
5161
5162 if (query_disk_id) {
5163 struct create_context *disk_id_ccontext;
5164
5165 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
5166 le32_to_cpu(rsp->CreateContextsLength));
5167 contxt_cnt++;
5168 create_disk_id_rsp_buf(rsp->Buffer +
5169 le32_to_cpu(rsp->CreateContextsLength),
5170 stat.ino, tcon->id);
5171 le32_add_cpu(&rsp->CreateContextsLength,
5172 conn->vals->create_disk_id_size);
5173 iov_len += conn->vals->create_disk_id_size;
5174 if (next_ptr)
5175 *next_ptr = cpu_to_le32(next_off);
5176 next_ptr = &disk_id_ccontext->Next;
5177 next_off = conn->vals->create_disk_id_size;
5178 }
5179
5180 if (durable_rsp &&
5181 (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2)) {
5182 struct create_context *durable_ccontext;
5183
5184 durable_ccontext = (struct create_context *)(rsp->Buffer +
5185 le32_to_cpu(rsp->CreateContextsLength));
5186 contxt_cnt++;
5187 if (dh_info.type == DURABLE_REQ) {
5188 create_durable_rsp_buf(rsp->Buffer +
5189 le32_to_cpu(rsp->CreateContextsLength));
5190 le32_add_cpu(&rsp->CreateContextsLength,
5191 conn->vals->create_durable_size);
5192 iov_len += conn->vals->create_durable_size;
5193 } else {
5194 create_durable_v2_rsp_buf(rsp->Buffer +
5195 le32_to_cpu(rsp->CreateContextsLength),
5196 fp);
5197 le32_add_cpu(&rsp->CreateContextsLength,
5198 conn->vals->create_durable_v2_size);
5199 iov_len += conn->vals->create_durable_v2_size;
5200 }
5201
5202 if (next_ptr)
5203 *next_ptr = cpu_to_le32(next_off);
5204 next_ptr = &durable_ccontext->Next;
5205 next_off = dh_info.type == DURABLE_REQ ?
5206 conn->vals->create_durable_size :
5207 conn->vals->create_durable_v2_size;
5208 }
5209
5210 if (posix_ctxt) {
5211 struct create_context *posix_ccontext;
5212
5213 posix_ccontext = (struct create_context *)(rsp->Buffer +
5214 le32_to_cpu(rsp->CreateContextsLength));
5215 contxt_cnt++;
5216 create_posix_rsp_buf(rsp->Buffer +
5217 le32_to_cpu(rsp->CreateContextsLength),
5218 fp);
5219 le32_add_cpu(&rsp->CreateContextsLength,
5220 conn->vals->create_posix_size);
5221 iov_len += conn->vals->create_posix_size;
5222 if (next_ptr)
5223 *next_ptr = cpu_to_le32(next_off);
5224 next_ptr = &posix_ccontext->Next;
5225 next_off = conn->vals->create_posix_size;
5226 }
5227
5228 /*
5229 * AAPL create context response: see smb2pdu.h for the capability
5230 * rationale. Scoped to TIME_MACHINE shares only.
5231 */
5232 if (aapl_ctxt) {
5233 if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR)
5234 conn->aapl_readdir_attr = true;
5235 /*
5236 * V2 extends the same inline-FinderInfo mechanism (see
5237 * smb2pdu.h), so a V2-requesting client also gets
5238 * aapl_readdir_attr treatment -- the reply just advertises
5239 * the V2 bit instead of the V1 one (create_aapl_rsp_buf).
5240 */
5241 if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2) {
5242 conn->aapl_readdir_attr = true;
5243 conn->aapl_readdir_attr_v2 = true;
5244 }
5245
5246 contxt_cnt++;
5247 create_aapl_rsp_buf(rsp->Buffer +
5248 le32_to_cpu(rsp->CreateContextsLength),
5249 SMB2_CRTCTX_AAPL_FULL_SYNC,
5250 aapl_req_bitmap,
5251 conn->aapl_readdir_attr_v2);
5252 le32_add_cpu(&rsp->CreateContextsLength,
5253 conn->vals->create_aapl_size);
5254 iov_len += conn->vals->create_aapl_size;
5255 if (next_ptr)
5256 *next_ptr = cpu_to_le32(next_off);
5257 /* AAPL is last; next_ptr need not be updated */
5258 }
5259
5260 if (contxt_cnt > 0) {
5261 rsp->CreateContextsOffset =
5262 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
5263 }
5264
5265 err_out:
5266 if (rc && (file_present || created))
5267 path_put(&path);
5268
5269 err_out1:
5270 ksmbd_revert_fsids(work);
5271
5272 err_out2:
5273 if (!rc) {
5274 if (!dh_info.replay)
5275 rc = ksmbd_update_fstate(&work->sess->file_table, fp,
5276 FP_INITED);
5277 if (!rc)
5278 rc = smb2_set_request_open(work, fp, &req->hdr, false, false);
5279 if (!rc)
5280 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
5281 }
5282 if (rc) {
5283 if (rc == -EINVAL)
5284 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5285 else if (rc == -EOPNOTSUPP)
5286 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
5287 else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) &&
5288 !rsp->hdr.Status) {
5289 if (req->DesiredAccess & FILE_ACCESS_SYSTEM_SECURITY_LE)
5290 rsp->hdr.Status = STATUS_PRIVILEGE_NOT_HELD;
5291 else
5292 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5293 }
5294 else if (rc == -ENOENT)
5295 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
5296 else if (rc == -EPERM)
5297 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
5298 else if (rc == -EBUSY)
5299 rsp->hdr.Status = STATUS_DELETE_PENDING;
5300 else if (rc == -EBADF)
5301 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
5302 else if (rc == -ENOEXEC)
5303 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
5304 else if (rc == -ENXIO)
5305 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
5306 else if (rc == -EEXIST)
5307 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
5308 else if (rc == -EMFILE)
5309 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5310 else if (rc == -EINPROGRESS)
5311 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5312 else if (rc == -EAGAIN)
5313 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5314 if (!rsp->hdr.Status)
5315 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5316
5317 if (fp && !dh_info.replay)
5318 ksmbd_fd_put(work, fp);
5319 smb2_set_err_rsp(work);
5320 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
5321 }
5322
5323 if (dh_info.replay)
5324 ksmbd_put_durable_fd(dh_info.fp);
5325
5326 if (dh_info.reconnected) {
5327 /*
5328 * If reconnect succeeded, fp was republished in the
5329 * session file table. On a later error, ksmbd_fd_put()
5330 * above drops the session reference; drop the durable
5331 * lookup reference through the same session-aware path so
5332 * final close removes the volatile id before freeing fp.
5333 */
5334 if (rc && fp == dh_info.fp)
5335 ksmbd_fd_put(work, dh_info.fp);
5336 else
5337 ksmbd_put_durable_fd(dh_info.fp);
5338 }
5339
5340 kfree(name);
5341 kfree(lc);
5342
5343 return rc;
5344 }
5345
readdir_info_level_struct_sz(int info_level)5346 static int readdir_info_level_struct_sz(int info_level)
5347 {
5348 switch (info_level) {
5349 case FILE_FULL_DIRECTORY_INFORMATION:
5350 return sizeof(FILE_FULL_DIRECTORY_INFO);
5351 case FILE_BOTH_DIRECTORY_INFORMATION:
5352 return sizeof(FILE_BOTH_DIRECTORY_INFO);
5353 case FILE_DIRECTORY_INFORMATION:
5354 return sizeof(FILE_DIRECTORY_INFO);
5355 case FILE_NAMES_INFORMATION:
5356 return sizeof(struct file_names_info);
5357 case FILEID_FULL_DIRECTORY_INFORMATION:
5358 return sizeof(FILE_ID_FULL_DIR_INFO);
5359 case FILEID_BOTH_DIRECTORY_INFORMATION:
5360 return sizeof(struct file_id_both_directory_info);
5361 case SMB_FIND_FILE_POSIX_INFO:
5362 return sizeof(struct smb2_posix_info);
5363 default:
5364 return -EOPNOTSUPP;
5365 }
5366 }
5367
dentry_name(struct ksmbd_dir_info * d_info,int info_level)5368 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
5369 {
5370 switch (info_level) {
5371 case FILE_FULL_DIRECTORY_INFORMATION:
5372 {
5373 FILE_FULL_DIRECTORY_INFO *ffdinfo;
5374
5375 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
5376 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
5377 d_info->name = ffdinfo->FileName;
5378 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
5379 return 0;
5380 }
5381 case FILE_BOTH_DIRECTORY_INFORMATION:
5382 {
5383 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5384
5385 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
5386 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
5387 d_info->name = fbdinfo->FileName;
5388 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
5389 return 0;
5390 }
5391 case FILE_DIRECTORY_INFORMATION:
5392 {
5393 FILE_DIRECTORY_INFO *fdinfo;
5394
5395 fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
5396 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
5397 d_info->name = fdinfo->FileName;
5398 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
5399 return 0;
5400 }
5401 case FILE_NAMES_INFORMATION:
5402 {
5403 struct file_names_info *fninfo;
5404
5405 fninfo = (struct file_names_info *)d_info->rptr;
5406 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
5407 d_info->name = fninfo->FileName;
5408 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
5409 return 0;
5410 }
5411 case FILEID_FULL_DIRECTORY_INFORMATION:
5412 {
5413 FILE_ID_FULL_DIR_INFO *dinfo;
5414
5415 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
5416 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
5417 d_info->name = dinfo->FileName;
5418 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
5419 return 0;
5420 }
5421 case FILEID_BOTH_DIRECTORY_INFORMATION:
5422 {
5423 struct file_id_both_directory_info *fibdinfo;
5424
5425 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
5426 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
5427 d_info->name = fibdinfo->FileName;
5428 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
5429 return 0;
5430 }
5431 case SMB_FIND_FILE_POSIX_INFO:
5432 {
5433 struct smb2_posix_info *posix_info;
5434
5435 posix_info = (struct smb2_posix_info *)d_info->rptr;
5436 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
5437 d_info->name = posix_info->name;
5438 d_info->name_len = le32_to_cpu(posix_info->name_len);
5439 return 0;
5440 }
5441 default:
5442 return -EINVAL;
5443 }
5444 }
5445
5446 /**
5447 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
5448 * buffer
5449 * @conn: connection instance
5450 * @info_level: smb information level
5451 * @d_info: structure included variables for query dir
5452 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
5453 *
5454 * if directory has many entries, find first can't read it fully.
5455 * find next might be called multiple times to read remaining dir entries
5456 *
5457 * Return: 0 on success, otherwise error
5458 */
smb2_populate_readdir_entry(struct ksmbd_conn * conn,int info_level,struct ksmbd_dir_info * d_info,struct ksmbd_kstat * ksmbd_kstat)5459 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
5460 struct ksmbd_dir_info *d_info,
5461 struct ksmbd_kstat *ksmbd_kstat)
5462 {
5463 int next_entry_offset = 0;
5464 char *conv_name;
5465 int conv_len;
5466 void *kstat;
5467 int struct_sz, rc = 0;
5468
5469 conv_name = ksmbd_convert_dir_info_name(d_info,
5470 conn->local_nls,
5471 &conv_len);
5472 if (!conv_name)
5473 return -ENOMEM;
5474
5475 /* Somehow the name has only terminating NULL bytes */
5476 if (conv_len < 0) {
5477 rc = -EINVAL;
5478 goto free_conv_name;
5479 }
5480
5481 struct_sz = readdir_info_level_struct_sz(info_level);
5482 if (struct_sz == -EOPNOTSUPP) {
5483 rc = -EINVAL;
5484 goto free_conv_name;
5485 }
5486
5487 struct_sz += conv_len;
5488 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
5489 d_info->last_entry_off_align = next_entry_offset - struct_sz;
5490
5491 if (next_entry_offset > d_info->out_buf_len) {
5492 d_info->out_buf_len = 0;
5493 rc = -ENOSPC;
5494 goto free_conv_name;
5495 }
5496
5497 kstat = d_info->wptr;
5498 if (info_level != FILE_NAMES_INFORMATION)
5499 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
5500
5501 switch (info_level) {
5502 case FILE_FULL_DIRECTORY_INFORMATION:
5503 {
5504 FILE_FULL_DIRECTORY_INFO *ffdinfo;
5505
5506 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
5507 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
5508 ffdinfo->EaSize =
5509 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5510 if (ffdinfo->EaSize)
5511 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5512 if (d_info->hide_dot_file && d_info->name[0] == '.')
5513 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5514 memcpy(ffdinfo->FileName, conv_name, conv_len);
5515 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5516 break;
5517 }
5518 case FILE_BOTH_DIRECTORY_INFORMATION:
5519 {
5520 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5521
5522 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
5523 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
5524 fbdinfo->EaSize =
5525 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5526 if (fbdinfo->EaSize)
5527 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5528 fbdinfo->ShortNameLength = 0;
5529 fbdinfo->Reserved = 0;
5530 if (d_info->hide_dot_file && d_info->name[0] == '.')
5531 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5532 memcpy(fbdinfo->FileName, conv_name, conv_len);
5533 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5534 break;
5535 }
5536 case FILE_DIRECTORY_INFORMATION:
5537 {
5538 FILE_DIRECTORY_INFO *fdinfo;
5539
5540 fdinfo = (FILE_DIRECTORY_INFO *)kstat;
5541 fdinfo->FileNameLength = cpu_to_le32(conv_len);
5542 if (d_info->hide_dot_file && d_info->name[0] == '.')
5543 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5544 memcpy(fdinfo->FileName, conv_name, conv_len);
5545 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5546 break;
5547 }
5548 case FILE_NAMES_INFORMATION:
5549 {
5550 struct file_names_info *fninfo;
5551
5552 fninfo = (struct file_names_info *)kstat;
5553 fninfo->FileNameLength = cpu_to_le32(conv_len);
5554 memcpy(fninfo->FileName, conv_name, conv_len);
5555 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5556 break;
5557 }
5558 case FILEID_FULL_DIRECTORY_INFORMATION:
5559 {
5560 FILE_ID_FULL_DIR_INFO *dinfo;
5561
5562 dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
5563 dinfo->FileNameLength = cpu_to_le32(conv_len);
5564 dinfo->EaSize =
5565 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5566 if (dinfo->EaSize)
5567 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5568 dinfo->Reserved = 0;
5569 if (conn->is_aapl)
5570 dinfo->UniqueId = 0;
5571 else
5572 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5573 if (d_info->hide_dot_file && d_info->name[0] == '.')
5574 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5575 memcpy(dinfo->FileName, conv_name, conv_len);
5576 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5577 break;
5578 }
5579 case FILEID_BOTH_DIRECTORY_INFORMATION:
5580 {
5581 struct file_id_both_directory_info *fibdinfo;
5582
5583 fibdinfo = (struct file_id_both_directory_info *)kstat;
5584 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
5585 if (conn->is_aapl)
5586 fibdinfo->UniqueId = 0;
5587 else
5588 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5589 fibdinfo->ShortNameLength = 0;
5590 fibdinfo->Reserved = 0;
5591 if (conn->aapl_readdir_attr) {
5592 /*
5593 * READDIR_ATTR wire format, confirmed against reference server's
5594 * reference implementation marshalling (reference implementation behavior):
5595 * EaSize = max_access (expanded specific
5596 * rights, simplified to "grant all")
5597 * ShortNameLength = 24 (fixed; not 0, despite the spec)
5598 * ShortName[0..7] = resource fork size (uint64 LE, 0 = no rfork)
5599 * ShortName[8..23] = compressed FinderInfo (type+creator+flags+
5600 * ext_flags+date_added, 16 bytes LE; all
5601 * zeros means type=0/creator=0, i.e. use
5602 * the file extension for icon lookup)
5603 * Reserved2 = Unix mode bits (uint16 LE)
5604 * Reparse-point tag is indicated via ExtFileAttributes, not EaSize.
5605 *
5606 * V2 (conn->aapl_readdir_attr_v2): ShortNameLength+Reserved
5607 * are read as a single flags field instead of being ignored
5608 * -- see smb2pdu.h for the wire-format confirmation and
5609 * AAPL_READDIR_ATTR_V2_NO_XATTR's meaning.
5610 */
5611 __le32 reparse_tag =
5612 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5613
5614 if (reparse_tag)
5615 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5616 /*
5617 * FILE_GENERIC_ALL_LE (0x10000000) is the raw
5618 * "generic all" meta-bit -- valid only in a
5619 * client's requested access mask, for the server
5620 * to expand. It has none of the specific FILE_*
5621 * rights bits set (FILE_LIST_DIRECTORY, FILE_TRAVERSE,
5622 * etc.), so reporting it here as max_access would make
5623 * macOS's bit-by-bit access checks fail on every
5624 * entry -> permanent "no entry" badges in Finder.
5625 * Report the actual expanded rights instead, same
5626 * as smb_map_generic_desired_access() does when
5627 * translating a client's GENERIC_ALL request.
5628 */
5629 fibdinfo->EaSize = cpu_to_le32(GENERIC_ALL_FLAGS);
5630 /*
5631 * The spec says ShortNameLength should be 0 when
5632 * there's no short name; 24 here instead matches
5633 * reference implementation marshalling (reference
5634 * behavior) for server-to-server wire parity.
5635 * V2 repurposes it as a flags field that is
5636 * interpreted; V1 doesn't. Either value is safe
5637 * here, so keep 24 for parity.
5638 */
5639 if (conn->aapl_readdir_attr_v2) {
5640 /*
5641 * V2 repurposes this field as flags (see comment
5642 * above) -- 24 is a V1-only convention that real
5643 * macOS clients ignore outright, so don't reuse it
5644 * here as a base value for a field V2 clients
5645 * actually interpret.
5646 */
5647 fibdinfo->ShortNameLength = 0;
5648 if (!ksmbd_kstat->has_ads_stream)
5649 fibdinfo->ShortNameLength = AAPL_READDIR_ATTR_V2_NO_XATTR;
5650 } else {
5651 fibdinfo->ShortNameLength = 24;
5652 }
5653 memset(fibdinfo->ShortName, 0, sizeof(fibdinfo->ShortName));
5654 fibdinfo->Reserved2 = cpu_to_le16(ksmbd_kstat->kstat->mode & 0xffff);
5655 } else {
5656 fibdinfo->EaSize =
5657 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5658 if (fibdinfo->EaSize)
5659 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5660 fibdinfo->Reserved2 = cpu_to_le16(0);
5661 }
5662 if (d_info->hide_dot_file && d_info->name[0] == '.')
5663 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5664 memcpy(fibdinfo->FileName, conv_name, conv_len);
5665 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5666 break;
5667 }
5668 case SMB_FIND_FILE_POSIX_INFO:
5669 {
5670 struct smb2_posix_info *posix_info;
5671 u64 time;
5672
5673 posix_info = (struct smb2_posix_info *)kstat;
5674 posix_info->Ignored = 0;
5675 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
5676 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
5677 posix_info->ChangeTime = cpu_to_le64(time);
5678 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
5679 posix_info->LastAccessTime = cpu_to_le64(time);
5680 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
5681 posix_info->LastWriteTime = cpu_to_le64(time);
5682 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
5683 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
5684 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
5685 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
5686 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
5687 switch (ksmbd_kstat->kstat->mode & S_IFMT) {
5688 case S_IFDIR:
5689 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5690 break;
5691 case S_IFLNK:
5692 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5693 break;
5694 case S_IFCHR:
5695 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5696 break;
5697 case S_IFBLK:
5698 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5699 break;
5700 case S_IFIFO:
5701 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5702 break;
5703 case S_IFSOCK:
5704 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5705 }
5706
5707 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
5708 posix_info->DosAttributes =
5709 S_ISDIR(ksmbd_kstat->kstat->mode) ?
5710 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
5711 if (d_info->hide_dot_file && d_info->name[0] == '.')
5712 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5713 /*
5714 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5715 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5716 * sub_auth(4 * 1(num_subauth)) + RID(4).
5717 */
5718 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
5719 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
5720 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
5721 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
5722 memcpy(posix_info->name, conv_name, conv_len);
5723 posix_info->name_len = cpu_to_le32(conv_len);
5724 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
5725 break;
5726 }
5727
5728 } /* switch (info_level) */
5729
5730 d_info->last_entry_offset = d_info->data_count;
5731 d_info->data_count += next_entry_offset;
5732 d_info->out_buf_len -= next_entry_offset;
5733 d_info->wptr += next_entry_offset;
5734
5735 ksmbd_debug(SMB,
5736 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
5737 info_level, d_info->out_buf_len,
5738 next_entry_offset, d_info->data_count);
5739
5740 free_conv_name:
5741 kfree(conv_name);
5742 return rc;
5743 }
5744
5745 struct smb2_query_dir_private {
5746 struct ksmbd_work *work;
5747 char *search_pattern;
5748 struct ksmbd_file *dir_fp;
5749
5750 struct ksmbd_dir_info *d_info;
5751 int info_level;
5752 };
5753
process_query_dir_entries(struct smb2_query_dir_private * priv)5754 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
5755 {
5756 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
5757 struct kstat kstat;
5758 struct ksmbd_kstat ksmbd_kstat;
5759 int rc;
5760 int i;
5761
5762 for (i = 0; i < priv->d_info->num_entry; i++) {
5763 struct dentry *dent;
5764 struct path path;
5765
5766 if (dentry_name(priv->d_info, priv->info_level))
5767 return -EINVAL;
5768
5769 dent = lookup_one_unlocked(idmap,
5770 &QSTR_LEN(priv->d_info->name,
5771 priv->d_info->name_len),
5772 priv->dir_fp->filp->f_path.dentry);
5773
5774 if (IS_ERR(dent)) {
5775 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
5776 priv->d_info->name,
5777 PTR_ERR(dent));
5778 continue;
5779 }
5780 if (unlikely(d_is_negative(dent))) {
5781 dput(dent);
5782 ksmbd_debug(SMB, "Negative dentry `%s'\n",
5783 priv->d_info->name);
5784 continue;
5785 }
5786
5787 if (test_share_config_flag(priv->work->tcon->share_conf,
5788 KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) {
5789 __le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
5790 FILE_READ_ATTRIBUTES_LE;
5791
5792 path.mnt = priv->dir_fp->filp->f_path.mnt;
5793 path.dentry = dent;
5794 rc = smb_check_perm_dacl(priv->work->conn, &path,
5795 &daccess, daccess,
5796 priv->work->sess->user->uid,
5797 true);
5798 if (rc) {
5799 dput(dent);
5800 continue;
5801 }
5802 }
5803
5804 ksmbd_kstat.kstat = &kstat;
5805 if (priv->info_level != FILE_NAMES_INFORMATION) {
5806 rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
5807 idmap,
5808 dent,
5809 &ksmbd_kstat);
5810 if (rc) {
5811 dput(dent);
5812 continue;
5813 }
5814 }
5815
5816 rc = smb2_populate_readdir_entry(priv->work->conn,
5817 priv->info_level,
5818 priv->d_info,
5819 &ksmbd_kstat);
5820 dput(dent);
5821 if (rc)
5822 return rc;
5823 }
5824 return 0;
5825 }
5826
reserve_populate_dentry(struct ksmbd_dir_info * d_info,int info_level)5827 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
5828 int info_level)
5829 {
5830 int struct_sz;
5831 int conv_len;
5832 int next_entry_offset;
5833
5834 struct_sz = readdir_info_level_struct_sz(info_level);
5835 if (struct_sz == -EOPNOTSUPP)
5836 return -EOPNOTSUPP;
5837
5838 conv_len = (d_info->name_len + 1) * 2;
5839 next_entry_offset = ALIGN(struct_sz + conv_len,
5840 KSMBD_DIR_INFO_ALIGNMENT);
5841
5842 if (next_entry_offset > d_info->out_buf_len) {
5843 d_info->out_buf_len = 0;
5844 return -ENOSPC;
5845 }
5846
5847 switch (info_level) {
5848 case FILE_FULL_DIRECTORY_INFORMATION:
5849 {
5850 FILE_FULL_DIRECTORY_INFO *ffdinfo;
5851
5852 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
5853 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
5854 ffdinfo->FileName[d_info->name_len] = 0x00;
5855 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5856 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5857 break;
5858 }
5859 case FILE_BOTH_DIRECTORY_INFORMATION:
5860 {
5861 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5862
5863 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
5864 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
5865 fbdinfo->FileName[d_info->name_len] = 0x00;
5866 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5867 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5868 break;
5869 }
5870 case FILE_DIRECTORY_INFORMATION:
5871 {
5872 FILE_DIRECTORY_INFO *fdinfo;
5873
5874 fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
5875 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
5876 fdinfo->FileName[d_info->name_len] = 0x00;
5877 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5878 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5879 break;
5880 }
5881 case FILE_NAMES_INFORMATION:
5882 {
5883 struct file_names_info *fninfo;
5884
5885 fninfo = (struct file_names_info *)d_info->wptr;
5886 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
5887 fninfo->FileName[d_info->name_len] = 0x00;
5888 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
5889 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5890 break;
5891 }
5892 case FILEID_FULL_DIRECTORY_INFORMATION:
5893 {
5894 FILE_ID_FULL_DIR_INFO *dinfo;
5895
5896 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
5897 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
5898 dinfo->FileName[d_info->name_len] = 0x00;
5899 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5900 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5901 break;
5902 }
5903 case FILEID_BOTH_DIRECTORY_INFORMATION:
5904 {
5905 struct file_id_both_directory_info *fibdinfo;
5906
5907 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
5908 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
5909 fibdinfo->FileName[d_info->name_len] = 0x00;
5910 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5911 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5912 break;
5913 }
5914 case SMB_FIND_FILE_POSIX_INFO:
5915 {
5916 struct smb2_posix_info *posix_info;
5917
5918 posix_info = (struct smb2_posix_info *)d_info->wptr;
5919 memcpy(posix_info->name, d_info->name, d_info->name_len);
5920 posix_info->name[d_info->name_len] = 0x00;
5921 posix_info->name_len = cpu_to_le32(d_info->name_len);
5922 posix_info->NextEntryOffset =
5923 cpu_to_le32(next_entry_offset);
5924 break;
5925 }
5926 } /* switch (info_level) */
5927
5928 d_info->num_entry++;
5929 d_info->out_buf_len -= next_entry_offset;
5930 d_info->wptr += next_entry_offset;
5931 return 0;
5932 }
5933
__query_dir(struct dir_context * ctx,const char * name,int namlen,loff_t offset,u64 ino,unsigned int d_type)5934 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
5935 loff_t offset, u64 ino, unsigned int d_type)
5936 {
5937 struct ksmbd_readdir_data *buf;
5938 struct smb2_query_dir_private *priv;
5939 struct ksmbd_dir_info *d_info;
5940 int rc;
5941
5942 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
5943 priv = buf->private;
5944 d_info = priv->d_info;
5945
5946 /* dot and dotdot entries are already reserved */
5947 if (!strcmp(".", name) || !strcmp("..", name))
5948 return true;
5949 d_info->num_scan++;
5950 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
5951 return true;
5952 if (!match_pattern(name, namlen, priv->search_pattern))
5953 return true;
5954
5955 d_info->name = name;
5956 d_info->name_len = namlen;
5957 rc = reserve_populate_dentry(d_info, priv->info_level);
5958 if (rc)
5959 return false;
5960 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
5961 d_info->out_buf_len = 0;
5962 return true;
5963 }
5964
verify_info_level(int info_level)5965 static int verify_info_level(int info_level)
5966 {
5967 switch (info_level) {
5968 case FILE_FULL_DIRECTORY_INFORMATION:
5969 case FILE_BOTH_DIRECTORY_INFORMATION:
5970 case FILE_DIRECTORY_INFORMATION:
5971 case FILE_NAMES_INFORMATION:
5972 case FILEID_FULL_DIRECTORY_INFORMATION:
5973 case FILEID_BOTH_DIRECTORY_INFORMATION:
5974 case SMB_FIND_FILE_POSIX_INFO:
5975 break;
5976 default:
5977 return -EOPNOTSUPP;
5978 }
5979
5980 return 0;
5981 }
5982
smb2_resp_buf_len(struct ksmbd_work * work,unsigned short hdr2_len)5983 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
5984 {
5985 int free_len;
5986
5987 free_len = (int)(work->response_sz -
5988 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
5989 return free_len;
5990 }
5991
smb2_calc_max_out_buf_len(struct ksmbd_work * work,unsigned short hdr2_len,unsigned int out_buf_len)5992 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
5993 unsigned short hdr2_len,
5994 unsigned int out_buf_len)
5995 {
5996 int free_len;
5997
5998 if (out_buf_len > work->conn->vals->max_trans_size)
5999 return -EINVAL;
6000
6001 free_len = smb2_resp_buf_len(work, hdr2_len);
6002 if (free_len < 0)
6003 return -EINVAL;
6004
6005 return min_t(int, out_buf_len, free_len);
6006 }
6007
smb2_query_dir(struct ksmbd_work * work)6008 int smb2_query_dir(struct ksmbd_work *work)
6009 {
6010 struct ksmbd_conn *conn = work->conn;
6011 struct smb2_query_directory_req *req;
6012 struct smb2_query_directory_rsp *rsp;
6013 struct ksmbd_share_config *share = work->tcon->share_conf;
6014 struct ksmbd_file *dir_fp = NULL;
6015 struct ksmbd_dir_info d_info;
6016 int rc = 0;
6017 char *srch_ptr = NULL;
6018 unsigned char srch_flag;
6019 int buffer_sz;
6020 struct smb2_query_dir_private query_dir_private = {NULL, };
6021 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6022
6023 ksmbd_debug(SMB, "Received smb2 query directory request\n");
6024
6025 WORK_BUFFERS(work, req, rsp);
6026
6027 if (smb2_compound_has_failed(work, &rsp->hdr))
6028 return -EACCES;
6029
6030 if (work->next_smb2_rcv_hdr_off &&
6031 !has_file_id(req->VolatileFileId)) {
6032 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6033 work->compound_fid);
6034 id = work->compound_fid;
6035 pid = work->compound_pfid;
6036 }
6037
6038 if (!has_file_id(id)) {
6039 id = req->VolatileFileId;
6040 pid = req->PersistentFileId;
6041 }
6042
6043 if (ksmbd_override_fsids(work)) {
6044 rsp->hdr.Status = STATUS_NO_MEMORY;
6045 smb2_set_err_rsp(work);
6046 return -ENOMEM;
6047 }
6048
6049 rc = verify_info_level(req->FileInformationClass);
6050 if (rc) {
6051 rc = -EFAULT;
6052 goto err_out2;
6053 }
6054
6055 dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
6056 if (!dir_fp) {
6057 rc = -EBADF;
6058 goto err_out2;
6059 }
6060
6061 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
6062 inode_permission(file_mnt_idmap(dir_fp->filp),
6063 file_inode(dir_fp->filp),
6064 MAY_READ | MAY_EXEC)) {
6065 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
6066 rc = -EACCES;
6067 goto err_out2;
6068 }
6069
6070 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
6071 pr_err("can't do query dir for a file\n");
6072 rc = -EINVAL;
6073 goto err_out2;
6074 }
6075
6076 srch_flag = req->Flags;
6077 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
6078 le16_to_cpu(req->FileNameLength), 1,
6079 conn->local_nls);
6080 if (IS_ERR(srch_ptr)) {
6081 ksmbd_debug(SMB, "Search Pattern not found\n");
6082 rc = -EINVAL;
6083 goto err_out2;
6084 } else {
6085 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
6086 }
6087
6088 mutex_lock(&dir_fp->readdir_lock);
6089
6090 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
6091 ksmbd_debug(SMB, "Restart directory scan\n");
6092 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
6093 }
6094
6095 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
6096 d_info.wptr = (char *)rsp->Buffer;
6097 d_info.rptr = (char *)rsp->Buffer;
6098 d_info.out_buf_len =
6099 smb2_calc_max_out_buf_len(work,
6100 offsetof(struct smb2_query_directory_rsp, Buffer),
6101 le32_to_cpu(req->OutputBufferLength));
6102 if (d_info.out_buf_len < 0) {
6103 rc = -EINVAL;
6104 goto err_out;
6105 }
6106 d_info.flags = srch_flag;
6107
6108 /*
6109 * reserve dot and dotdot entries in head of buffer
6110 * in first response
6111 */
6112 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
6113 dir_fp, &d_info, srch_ptr,
6114 smb2_populate_readdir_entry);
6115 if (rc == -ENOSPC)
6116 rc = 0;
6117 else if (rc)
6118 goto err_out;
6119
6120 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
6121 d_info.hide_dot_file = true;
6122
6123 buffer_sz = d_info.out_buf_len;
6124 d_info.rptr = d_info.wptr;
6125 query_dir_private.work = work;
6126 query_dir_private.search_pattern = srch_ptr;
6127 query_dir_private.dir_fp = dir_fp;
6128 query_dir_private.d_info = &d_info;
6129 query_dir_private.info_level = req->FileInformationClass;
6130 dir_fp->readdir_data.private = &query_dir_private;
6131 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
6132 again:
6133 d_info.num_scan = 0;
6134 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
6135 /*
6136 * num_entry can be 0 if the directory iteration stops before reaching
6137 * the end of the directory and no file is matched with the search
6138 * pattern.
6139 */
6140 if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
6141 d_info.out_buf_len > 0)
6142 goto again;
6143 /*
6144 * req->OutputBufferLength is too small to contain even one entry.
6145 * In this case, it immediately returns OutputBufferLength 0 to client.
6146 */
6147 if (!d_info.out_buf_len && !d_info.num_entry)
6148 goto no_buf_len;
6149 if (rc > 0 || rc == -ENOSPC)
6150 rc = 0;
6151 else if (rc)
6152 goto err_out;
6153
6154 d_info.wptr = d_info.rptr;
6155 d_info.out_buf_len = buffer_sz;
6156 rc = process_query_dir_entries(&query_dir_private);
6157 if (rc)
6158 goto err_out;
6159
6160 if (!d_info.data_count && d_info.out_buf_len >= 0) {
6161 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
6162 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6163 } else {
6164 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
6165 rsp->hdr.Status = STATUS_NO_MORE_FILES;
6166 }
6167 rsp->StructureSize = cpu_to_le16(9);
6168 rsp->OutputBufferOffset = cpu_to_le16(0);
6169 rsp->OutputBufferLength = cpu_to_le32(0);
6170 rsp->Buffer[0] = 0;
6171 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6172 offsetof(struct smb2_query_directory_rsp, Buffer)
6173 + 1);
6174 if (rc)
6175 goto err_out;
6176 } else {
6177 no_buf_len:
6178 ((FILE_DIRECTORY_INFO *)
6179 ((char *)rsp->Buffer + d_info.last_entry_offset))
6180 ->NextEntryOffset = 0;
6181 if (d_info.data_count >= d_info.last_entry_off_align)
6182 d_info.data_count -= d_info.last_entry_off_align;
6183
6184 rsp->StructureSize = cpu_to_le16(9);
6185 rsp->OutputBufferOffset = cpu_to_le16(72);
6186 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
6187 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6188 offsetof(struct smb2_query_directory_rsp, Buffer) +
6189 d_info.data_count);
6190 if (rc)
6191 goto err_out;
6192 }
6193
6194 mutex_unlock(&dir_fp->readdir_lock);
6195 kfree(srch_ptr);
6196 ksmbd_fd_put(work, dir_fp);
6197 ksmbd_revert_fsids(work);
6198 return 0;
6199
6200 err_out:
6201 pr_err("error while processing smb2 query dir rc = %d\n", rc);
6202 mutex_unlock(&dir_fp->readdir_lock);
6203 kfree(srch_ptr);
6204
6205 err_out2:
6206 if (rc == -EINVAL)
6207 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6208 else if (rc == -EACCES)
6209 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6210 else if (rc == -ENOENT)
6211 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6212 else if (rc == -EBADF)
6213 rsp->hdr.Status = STATUS_FILE_CLOSED;
6214 else if (rc == -ENOMEM)
6215 rsp->hdr.Status = STATUS_NO_MEMORY;
6216 else if (rc == -EFAULT)
6217 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6218 else if (rc == -EIO)
6219 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
6220 if (!rsp->hdr.Status)
6221 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6222
6223 smb2_set_err_rsp(work);
6224 ksmbd_fd_put(work, dir_fp);
6225 ksmbd_revert_fsids(work);
6226 return rc;
6227 }
6228
6229 /**
6230 * buffer_check_err() - helper function to check buffer errors
6231 * @reqOutputBufferLength: max buffer length expected in command response
6232 * @fixed_len: minimum fixed response length
6233 * @rsp: query info response buffer contains output buffer length
6234 * @rsp_org: base response buffer pointer in case of chained response
6235 *
6236 * Return: 0 on success, otherwise error
6237 */
buffer_check_err(int reqOutputBufferLength,unsigned int fixed_len,struct smb2_query_info_rsp * rsp,void * rsp_org)6238 static int buffer_check_err(int reqOutputBufferLength,
6239 unsigned int fixed_len,
6240 struct smb2_query_info_rsp *rsp,
6241 void *rsp_org)
6242 {
6243 unsigned int output_len = le32_to_cpu(rsp->OutputBufferLength);
6244
6245 if (reqOutputBufferLength < fixed_len) {
6246 pr_err("Invalid Buffer Size Requested\n");
6247 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6248 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
6249 return -EINVAL;
6250 }
6251
6252 if (reqOutputBufferLength < output_len) {
6253 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
6254 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
6255 }
6256 return 0;
6257 }
6258
get_standard_info_pipe(struct smb2_query_info_rsp * rsp,void * rsp_org)6259 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
6260 void *rsp_org)
6261 {
6262 struct smb2_file_standard_info *sinfo;
6263
6264 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
6265
6266 sinfo->AllocationSize = cpu_to_le64(4096);
6267 sinfo->EndOfFile = cpu_to_le64(0);
6268 sinfo->NumberOfLinks = cpu_to_le32(1);
6269 sinfo->DeletePending = 1;
6270 sinfo->Directory = 0;
6271 rsp->OutputBufferLength =
6272 cpu_to_le32(sizeof(struct smb2_file_standard_info));
6273 }
6274
get_internal_info_pipe(struct smb2_query_info_rsp * rsp,u64 num,void * rsp_org)6275 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
6276 void *rsp_org)
6277 {
6278 struct smb2_file_internal_info *file_info;
6279
6280 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
6281
6282 /* any unique number */
6283 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
6284 rsp->OutputBufferLength =
6285 cpu_to_le32(sizeof(struct smb2_file_internal_info));
6286 }
6287
smb2_get_info_file_pipe(struct ksmbd_session * sess,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp,void * rsp_org)6288 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
6289 struct smb2_query_info_req *req,
6290 struct smb2_query_info_rsp *rsp,
6291 void *rsp_org)
6292 {
6293 u64 id;
6294 int rc;
6295
6296 /*
6297 * Windows can sometime send query file info request on
6298 * pipe without opening it, checking error condition here
6299 */
6300 id = req->VolatileFileId;
6301
6302 lockdep_assert_not_held(&sess->rpc_lock);
6303
6304 down_read(&sess->rpc_lock);
6305 if (!ksmbd_session_rpc_method(sess, id)) {
6306 up_read(&sess->rpc_lock);
6307 return -ENOENT;
6308 }
6309 up_read(&sess->rpc_lock);
6310
6311 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
6312 req->FileInfoClass, req->VolatileFileId);
6313
6314 switch (req->FileInfoClass) {
6315 case FILE_STANDARD_INFORMATION:
6316 get_standard_info_pipe(rsp, rsp_org);
6317 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6318 le32_to_cpu(rsp->OutputBufferLength),
6319 rsp, rsp_org);
6320 break;
6321 case FILE_INTERNAL_INFORMATION:
6322 get_internal_info_pipe(rsp, id, rsp_org);
6323 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6324 le32_to_cpu(rsp->OutputBufferLength),
6325 rsp, rsp_org);
6326 break;
6327 default:
6328 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
6329 req->FileInfoClass);
6330 rc = -EOPNOTSUPP;
6331 }
6332 return rc;
6333 }
6334
6335 /**
6336 * smb2_get_ea() - handler for smb2 get extended attribute command
6337 * @work: smb work containing query info command buffer
6338 * @fp: ksmbd_file pointer
6339 * @req: get extended attribute request
6340 * @rsp: response buffer pointer
6341 * @rsp_org: base response buffer pointer in case of chained response
6342 *
6343 * Return: 0 on success, otherwise error
6344 */
smb2_get_ea(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp,void * rsp_org)6345 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
6346 struct smb2_query_info_req *req,
6347 struct smb2_query_info_rsp *rsp, void *rsp_org)
6348 {
6349 struct smb2_ea_info *eainfo, *prev_eainfo;
6350 char *name, *ptr, *xattr_list = NULL, *buf;
6351 int rc, name_len, value_len, xattr_list_len, idx;
6352 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
6353 struct smb2_ea_info_req *ea_req = NULL;
6354 const struct path *path;
6355 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
6356
6357 if (!(fp->daccess & FILE_READ_EA_LE)) {
6358 pr_err("Not permitted to read ext attr : 0x%x\n",
6359 fp->daccess);
6360 return -EACCES;
6361 }
6362
6363 path = &fp->filp->f_path;
6364 /* single EA entry is requested with given user.* name */
6365 if (req->InputBufferLength) {
6366 if (le32_to_cpu(req->InputBufferLength) <=
6367 sizeof(struct smb2_ea_info_req))
6368 return -EINVAL;
6369
6370 ea_req = (struct smb2_ea_info_req *)((char *)req +
6371 le16_to_cpu(req->InputBufferOffset));
6372
6373 if (le32_to_cpu(req->InputBufferLength) <
6374 offsetof(struct smb2_ea_info_req, name) +
6375 ea_req->EaNameLength)
6376 return -EINVAL;
6377 } else {
6378 /* need to send all EAs, if no specific EA is requested*/
6379 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
6380 ksmbd_debug(SMB,
6381 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
6382 le32_to_cpu(req->Flags));
6383 }
6384
6385 buf_free_len =
6386 smb2_calc_max_out_buf_len(work,
6387 offsetof(struct smb2_query_info_rsp, Buffer),
6388 le32_to_cpu(req->OutputBufferLength));
6389 if (buf_free_len < 0)
6390 return -EINVAL;
6391
6392 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
6393 if (rc < 0) {
6394 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6395 goto out;
6396 } else if (!rc) { /* there is no EA in the file */
6397 ksmbd_debug(SMB, "no ea data in the file\n");
6398 goto done;
6399 }
6400 xattr_list_len = rc;
6401
6402 ptr = (char *)rsp->Buffer;
6403 eainfo = (struct smb2_ea_info *)ptr;
6404 prev_eainfo = eainfo;
6405 idx = 0;
6406
6407 while (idx < xattr_list_len) {
6408 name = xattr_list + idx;
6409 name_len = strlen(name);
6410
6411 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
6412 idx += name_len + 1;
6413
6414 /*
6415 * CIFS does not support EA other than user.* namespace,
6416 * still keep the framework generic, to list other attrs
6417 * in future.
6418 */
6419 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6420 continue;
6421
6422 if (req->InputBufferLength &&
6423 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
6424 ea_req->EaNameLength))
6425 continue;
6426
6427 if (smb2_is_private_ea(&name[XATTR_USER_PREFIX_LEN],
6428 name_len - XATTR_USER_PREFIX_LEN))
6429 continue;
6430
6431 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6432 name_len -= XATTR_USER_PREFIX_LEN;
6433
6434 ptr = eainfo->name + name_len + 1;
6435 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
6436 name_len + 1);
6437 /* bailout if xattr can't fit in buf_free_len */
6438 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
6439 name, &buf);
6440 if (value_len <= 0) {
6441 rc = -ENOENT;
6442 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6443 goto out;
6444 }
6445
6446 buf_free_len -= value_len;
6447 if (buf_free_len < 0) {
6448 kfree(buf);
6449 break;
6450 }
6451
6452 memcpy(ptr, buf, value_len);
6453 kfree(buf);
6454
6455 ptr += value_len;
6456 eainfo->Flags = 0;
6457 eainfo->EaNameLength = name_len;
6458
6459 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6460 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
6461 name_len);
6462 else
6463 memcpy(eainfo->name, name, name_len);
6464
6465 eainfo->name[name_len] = '\0';
6466 eainfo->EaValueLength = cpu_to_le16(value_len);
6467 next_offset = offsetof(struct smb2_ea_info, name) +
6468 name_len + 1 + value_len;
6469
6470 /* align next xattr entry at 4 byte bundary */
6471 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
6472 if (alignment_bytes) {
6473 if (buf_free_len < alignment_bytes)
6474 break;
6475 memset(ptr, '\0', alignment_bytes);
6476 ptr += alignment_bytes;
6477 next_offset += alignment_bytes;
6478 buf_free_len -= alignment_bytes;
6479 }
6480 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
6481 prev_eainfo = eainfo;
6482 eainfo = (struct smb2_ea_info *)ptr;
6483 rsp_data_cnt += next_offset;
6484
6485 if (req->InputBufferLength) {
6486 ksmbd_debug(SMB, "single entry requested\n");
6487 break;
6488 }
6489 }
6490
6491 /* no more ea entries */
6492 prev_eainfo->NextEntryOffset = 0;
6493 done:
6494 rc = 0;
6495 if (rsp_data_cnt == 0)
6496 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
6497 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
6498 out:
6499 kvfree(xattr_list);
6500 return rc;
6501 }
6502
get_file_access_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6503 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
6504 struct ksmbd_file *fp, void *rsp_org)
6505 {
6506 struct smb2_file_access_info *file_info;
6507
6508 file_info = (struct smb2_file_access_info *)rsp->Buffer;
6509 file_info->AccessFlags = fp->daccess;
6510 rsp->OutputBufferLength =
6511 cpu_to_le32(sizeof(struct smb2_file_access_info));
6512 }
6513
get_file_basic_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6514 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
6515 struct ksmbd_file *fp, void *rsp_org)
6516 {
6517 struct file_basic_info *basic_info;
6518 struct kstat stat;
6519 u64 time;
6520 int ret;
6521
6522 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6523 pr_err("no right to read the attributes : 0x%x\n",
6524 fp->daccess);
6525 return -EACCES;
6526 }
6527
6528 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6529 AT_STATX_SYNC_AS_STAT);
6530 if (ret)
6531 return ret;
6532
6533 basic_info = (struct file_basic_info *)rsp->Buffer;
6534 basic_info->CreationTime = cpu_to_le64(fp->create_time);
6535 time = ksmbd_UnixTimeToNT(stat.atime);
6536 basic_info->LastAccessTime = cpu_to_le64(time);
6537 time = ksmbd_UnixTimeToNT(stat.mtime);
6538 basic_info->LastWriteTime = cpu_to_le64(time);
6539 basic_info->ChangeTime = cpu_to_le64(fp->change_time);
6540 basic_info->Attributes = fp->f_ci->m_fattr;
6541 basic_info->Pad = 0;
6542 rsp->OutputBufferLength =
6543 cpu_to_le32(sizeof(struct file_basic_info));
6544 return 0;
6545 }
6546
get_file_allocation_stat(struct ksmbd_file * fp,struct kstat * stat)6547 static int get_file_allocation_stat(struct ksmbd_file *fp, struct kstat *stat)
6548 {
6549 int ret;
6550
6551 /*
6552 * Buffered writes can leave delayed allocation in a state where two
6553 * consecutive queries report different block counts even when the
6554 * second write only overwrites the first one. Complete writeback before
6555 * reporting the filesystem allocation for an ordinary open.
6556 */
6557 if (!fp->allocation_size_set) {
6558 ret = file_write_and_wait(fp->filp);
6559 if (ret)
6560 return ret;
6561 }
6562
6563 ret = vfs_getattr(&fp->filp->f_path, stat, STATX_BASIC_STATS,
6564 AT_STATX_SYNC_AS_STAT);
6565 if (!ret && !fp->allocation_size_set)
6566 fp->allocation_size = S_ISDIR(stat->mode) ? 0 : stat->blocks << 9;
6567
6568 return ret;
6569 }
6570
get_file_standard_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6571 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
6572 struct ksmbd_file *fp, void *rsp_org)
6573 {
6574 struct smb2_file_standard_info *sinfo;
6575 unsigned int delete_pending;
6576 struct kstat stat;
6577 int ret;
6578
6579 ret = get_file_allocation_stat(fp, &stat);
6580 if (ret)
6581 return ret;
6582
6583 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
6584 delete_pending = ksmbd_inode_pending_delete(fp);
6585
6586 if (ksmbd_stream_fd(fp) == false) {
6587 sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
6588 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
6589 } else {
6590 loff_t seof = ksmbd_stream_eof(fp);
6591
6592 sinfo->AllocationSize = cpu_to_le64((u64)seof);
6593 sinfo->EndOfFile = cpu_to_le64((u64)seof);
6594 }
6595 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
6596 sinfo->DeletePending = delete_pending;
6597 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
6598 rsp->OutputBufferLength =
6599 cpu_to_le32(sizeof(struct smb2_file_standard_info));
6600
6601 return 0;
6602 }
6603
get_file_alignment_info(struct smb2_query_info_rsp * rsp,void * rsp_org)6604 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
6605 void *rsp_org)
6606 {
6607 struct smb2_file_alignment_info *file_info;
6608
6609 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
6610 file_info->AlignmentRequirement = 0;
6611 rsp->OutputBufferLength =
6612 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
6613 }
6614
get_file_all_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6615 static int get_file_all_info(struct ksmbd_work *work,
6616 struct smb2_query_info_rsp *rsp,
6617 struct ksmbd_file *fp,
6618 void *rsp_org)
6619 {
6620 struct ksmbd_conn *conn = work->conn;
6621 struct smb2_file_all_info *file_info;
6622 unsigned int delete_pending;
6623 struct kstat stat;
6624 int conv_len;
6625 char *filename;
6626 u64 time;
6627 int ret, buf_free_len, filename_len;
6628
6629 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6630 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
6631 fp->daccess);
6632 return -EACCES;
6633 }
6634
6635 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
6636 if (IS_ERR(filename))
6637 return PTR_ERR(filename);
6638
6639 filename_len = strlen(filename);
6640 buf_free_len = smb2_resp_buf_len(work,
6641 offsetof(struct smb2_query_info_rsp, Buffer) +
6642 offsetof(struct smb2_file_all_info, FileName));
6643 if (buf_free_len < (filename_len + 1) * 2) {
6644 kfree(filename);
6645 return -EINVAL;
6646 }
6647
6648 ret = get_file_allocation_stat(fp, &stat);
6649 if (ret) {
6650 kfree(filename);
6651 return ret;
6652 }
6653
6654 ksmbd_debug(SMB, "filename = %s\n", filename);
6655 delete_pending = ksmbd_inode_pending_delete(fp);
6656 file_info = (struct smb2_file_all_info *)rsp->Buffer;
6657
6658 file_info->CreationTime = cpu_to_le64(fp->create_time);
6659 time = ksmbd_UnixTimeToNT(stat.atime);
6660 file_info->LastAccessTime = cpu_to_le64(time);
6661 time = ksmbd_UnixTimeToNT(stat.mtime);
6662 file_info->LastWriteTime = cpu_to_le64(time);
6663 file_info->ChangeTime = cpu_to_le64(fp->change_time);
6664 file_info->Attributes = fp->f_ci->m_fattr;
6665 file_info->Pad1 = 0;
6666 if (ksmbd_stream_fd(fp) == false) {
6667 file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
6668 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
6669 } else {
6670 loff_t seof = ksmbd_stream_eof(fp);
6671
6672 file_info->AllocationSize = cpu_to_le64((u64)seof);
6673 file_info->EndOfFile = cpu_to_le64((u64)seof);
6674 }
6675 file_info->NumberOfLinks =
6676 cpu_to_le32(get_nlink(&stat) - delete_pending);
6677 file_info->DeletePending = delete_pending;
6678 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
6679 file_info->Pad2 = 0;
6680 file_info->IndexNumber = cpu_to_le64(stat.ino);
6681 file_info->EASize = 0;
6682 file_info->AccessFlags = fp->daccess;
6683 if (ksmbd_stream_fd(fp) == false)
6684 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
6685 else
6686 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
6687 file_info->Mode = fp->coption;
6688 file_info->AlignmentRequirement = 0;
6689 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
6690 min(filename_len, PATH_MAX),
6691 conn->local_nls, 0);
6692 conv_len *= 2;
6693 file_info->FileNameLength = cpu_to_le32(conv_len);
6694 rsp->OutputBufferLength =
6695 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
6696 kfree(filename);
6697 return 0;
6698 }
6699
get_file_alternate_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6700 static void get_file_alternate_info(struct ksmbd_work *work,
6701 struct smb2_query_info_rsp *rsp,
6702 struct ksmbd_file *fp,
6703 void *rsp_org)
6704 {
6705 struct ksmbd_conn *conn = work->conn;
6706 struct smb2_file_alt_name_info *file_info;
6707 struct dentry *dentry = fp->filp->f_path.dentry;
6708 int conv_len;
6709
6710 spin_lock(&dentry->d_lock);
6711 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
6712 conv_len = ksmbd_extract_shortname(conn,
6713 dentry->d_name.name,
6714 file_info->FileName);
6715 spin_unlock(&dentry->d_lock);
6716 file_info->FileNameLength = cpu_to_le32(conv_len);
6717 rsp->OutputBufferLength =
6718 cpu_to_le32(struct_size(file_info, FileName, conv_len));
6719 }
6720
smb2_get_normalized_stream_name(struct ksmbd_file * fp)6721 static char *smb2_get_normalized_stream_name(struct ksmbd_file *fp)
6722 {
6723 char *name, *stream_name = NULL, *xattr_list = NULL;
6724 ssize_t xattr_list_len;
6725
6726 if (!ksmbd_stream_fd(fp))
6727 return NULL;
6728
6729 xattr_list_len = ksmbd_vfs_listxattr(fp->filp->f_path.dentry,
6730 &xattr_list);
6731 if (xattr_list_len <= 0)
6732 goto out;
6733
6734 for (name = xattr_list; name - xattr_list < xattr_list_len;
6735 name += strlen(name) + 1) {
6736 char *type;
6737
6738 if (strlen(name) + 1 != fp->stream.size ||
6739 strncasecmp(name, fp->stream.name, fp->stream.size - 1))
6740 continue;
6741
6742 name += XATTR_NAME_STREAM_LEN;
6743 type = strrchr(name, ':');
6744 if (type)
6745 stream_name = kstrndup(name, type - name,
6746 KSMBD_DEFAULT_GFP);
6747 break;
6748 }
6749 out:
6750 kvfree(xattr_list);
6751 return stream_name;
6752 }
6753
get_file_normalized_name_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp)6754 static int get_file_normalized_name_info(struct ksmbd_work *work,
6755 struct smb2_query_info_rsp *rsp,
6756 struct ksmbd_file *fp)
6757 {
6758 struct smb2_file_alt_name_info *file_info;
6759 char *filename, *normalized, *stream_name;
6760 int conv_len, filename_len;
6761
6762 if (work->conn->dialect < SMB311_PROT_ID) {
6763 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6764 return -EOPNOTSUPP;
6765 }
6766
6767 filename = convert_to_nt_pathname(work->tcon->share_conf,
6768 &fp->filp->f_path);
6769 if (IS_ERR(filename))
6770 return PTR_ERR(filename);
6771 if (filename[0] == '\\')
6772 memmove(filename, filename + 1, strlen(filename));
6773
6774 stream_name = smb2_get_normalized_stream_name(fp);
6775 normalized = kasprintf(KSMBD_DEFAULT_GFP, "%s%s%s", filename,
6776 stream_name ? ":" : "",
6777 stream_name ? stream_name : "");
6778 kfree(stream_name);
6779 kfree(filename);
6780 if (!normalized)
6781 return -ENOMEM;
6782
6783 filename_len = strlen(normalized);
6784 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
6785 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName,
6786 normalized, filename_len,
6787 work->conn->local_nls, 0);
6788 kfree(normalized);
6789 conv_len *= 2;
6790 file_info->FileNameLength = cpu_to_le32(conv_len);
6791 rsp->OutputBufferLength = cpu_to_le32(sizeof(*file_info) + conv_len);
6792 return 0;
6793 }
6794
get_file_stream_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6795 static int get_file_stream_info(struct ksmbd_work *work,
6796 struct smb2_query_info_rsp *rsp,
6797 struct ksmbd_file *fp,
6798 void *rsp_org)
6799 {
6800 struct ksmbd_conn *conn = work->conn;
6801 struct smb2_file_stream_info *file_info;
6802 char *stream_name, *xattr_list = NULL, *stream_buf;
6803 struct kstat stat;
6804 const struct path *path = &fp->filp->f_path;
6805 ssize_t xattr_list_len;
6806 ssize_t slen;
6807 loff_t ssize;
6808 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
6809 int buf_free_len;
6810 int ret;
6811
6812 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6813 AT_STATX_SYNC_AS_STAT);
6814 if (ret)
6815 return ret;
6816
6817 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
6818
6819 buf_free_len = smb2_resp_buf_len(work,
6820 offsetof(struct smb2_query_info_rsp, Buffer));
6821 if (buf_free_len < 0)
6822 goto out;
6823
6824 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
6825 if (xattr_list_len < 0) {
6826 goto out;
6827 } else if (!xattr_list_len) {
6828 ksmbd_debug(SMB, "empty xattr in the file\n");
6829 goto out;
6830 }
6831
6832 while (idx < xattr_list_len) {
6833 stream_name = xattr_list + idx;
6834 streamlen = strlen(stream_name);
6835 idx += streamlen + 1;
6836
6837 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
6838
6839 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
6840 STREAM_PREFIX, STREAM_PREFIX_LEN))
6841 continue;
6842
6843 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
6844 STREAM_PREFIX_LEN);
6845 streamlen = stream_name_len;
6846
6847 /* plus : size */
6848 streamlen += 1;
6849 stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
6850 if (!stream_buf)
6851 break;
6852
6853 streamlen = snprintf(stream_buf, streamlen + 1,
6854 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
6855
6856 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
6857 if (next > buf_free_len) {
6858 kfree(stream_buf);
6859 break;
6860 }
6861
6862 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
6863 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
6864 stream_buf, streamlen,
6865 conn->local_nls, 0);
6866 streamlen *= 2;
6867 kfree(stream_buf);
6868 file_info->StreamNameLength = cpu_to_le32(streamlen);
6869 /*
6870 * stream_name_len is the byte length of the xattr's *name*,
6871 * not its value -- same class of bug ksmbd_stream_eof()
6872 * (smb2pdu.c) already fixes for EndOfFile/AllocationSize on
6873 * a stream handle; this enumeration path needs the same
6874 * real xattr value length, not the name length reused as a
6875 * size.
6876 */
6877 slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
6878 path->dentry, stream_name,
6879 strlen(stream_name) + 1);
6880 ssize = slen < 0 ? 0 : (loff_t)slen;
6881 file_info->StreamSize = cpu_to_le64(ssize);
6882 file_info->StreamAllocationSize = cpu_to_le64(ssize);
6883
6884 nbytes += next;
6885 buf_free_len -= next;
6886 file_info->NextEntryOffset = cpu_to_le32(next);
6887 }
6888
6889 out:
6890 if (!S_ISDIR(stat.mode) &&
6891 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
6892 file_info = (struct smb2_file_stream_info *)
6893 &rsp->Buffer[nbytes];
6894 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
6895 "::$DATA", 7, conn->local_nls, 0);
6896 streamlen *= 2;
6897 file_info->StreamNameLength = cpu_to_le32(streamlen);
6898 file_info->StreamSize = cpu_to_le64(stat.size);
6899 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
6900 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
6901 }
6902
6903 /* last entry offset should be 0 */
6904 file_info->NextEntryOffset = 0;
6905 kvfree(xattr_list);
6906
6907 rsp->OutputBufferLength = cpu_to_le32(nbytes);
6908
6909 return 0;
6910 }
6911
get_file_internal_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6912 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
6913 struct ksmbd_file *fp, void *rsp_org)
6914 {
6915 struct smb2_file_internal_info *file_info;
6916 struct kstat stat;
6917 int ret;
6918
6919 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6920 AT_STATX_SYNC_AS_STAT);
6921 if (ret)
6922 return ret;
6923
6924 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
6925 file_info->IndexNumber = cpu_to_le64(stat.ino);
6926 rsp->OutputBufferLength =
6927 cpu_to_le32(sizeof(struct smb2_file_internal_info));
6928
6929 return 0;
6930 }
6931
get_file_network_open_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6932 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
6933 struct ksmbd_file *fp, void *rsp_org)
6934 {
6935 struct smb2_file_network_open_info *file_info;
6936 struct kstat stat;
6937 u64 time;
6938 int ret;
6939
6940 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6941 pr_err("no right to read the attributes : 0x%x\n",
6942 fp->daccess);
6943 return -EACCES;
6944 }
6945
6946 ret = get_file_allocation_stat(fp, &stat);
6947 if (ret)
6948 return ret;
6949
6950 file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
6951
6952 file_info->CreationTime = cpu_to_le64(fp->create_time);
6953 time = ksmbd_UnixTimeToNT(stat.atime);
6954 file_info->LastAccessTime = cpu_to_le64(time);
6955 time = ksmbd_UnixTimeToNT(stat.mtime);
6956 file_info->LastWriteTime = cpu_to_le64(time);
6957 file_info->ChangeTime = cpu_to_le64(fp->change_time);
6958 file_info->Attributes = fp->f_ci->m_fattr;
6959 if (ksmbd_stream_fd(fp) == false) {
6960 file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
6961 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
6962 } else {
6963 loff_t seof = ksmbd_stream_eof(fp);
6964
6965 file_info->AllocationSize = cpu_to_le64((u64)seof);
6966 file_info->EndOfFile = cpu_to_le64((u64)seof);
6967 }
6968 file_info->Reserved = cpu_to_le32(0);
6969 rsp->OutputBufferLength =
6970 cpu_to_le32(sizeof(struct smb2_file_network_open_info));
6971 return 0;
6972 }
6973
get_file_ea_info(struct smb2_query_info_rsp * rsp,void * rsp_org)6974 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
6975 {
6976 struct smb2_file_ea_info *file_info;
6977
6978 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
6979 file_info->EASize = 0;
6980 rsp->OutputBufferLength =
6981 cpu_to_le32(sizeof(struct smb2_file_ea_info));
6982 }
6983
get_file_position_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6984 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
6985 struct ksmbd_file *fp, void *rsp_org)
6986 {
6987 struct smb2_file_pos_info *file_info;
6988
6989 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
6990 if (ksmbd_stream_fd(fp) == false)
6991 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
6992 else
6993 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
6994
6995 rsp->OutputBufferLength =
6996 cpu_to_le32(sizeof(struct smb2_file_pos_info));
6997 }
6998
get_file_mode_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)6999 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
7000 struct ksmbd_file *fp, void *rsp_org)
7001 {
7002 struct smb2_file_mode_info *file_info;
7003
7004 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
7005 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
7006 rsp->OutputBufferLength =
7007 cpu_to_le32(sizeof(struct smb2_file_mode_info));
7008 }
7009
get_file_compression_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)7010 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
7011 struct ksmbd_file *fp, void *rsp_org)
7012 {
7013 struct smb2_file_comp_info *file_info;
7014 struct kstat stat;
7015 u16 fmt;
7016 int ret;
7017
7018 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7019 AT_STATX_SYNC_AS_STAT);
7020 if (ret)
7021 return ret;
7022
7023 ret = ksmbd_vfs_get_compression(fp, &fmt);
7024 if (ret)
7025 return ret;
7026
7027 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
7028 file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
7029 file_info->CompressionFormat = cpu_to_le16(fmt);
7030 file_info->CompressionUnitShift = 0;
7031 file_info->ChunkShift = 0;
7032 file_info->ClusterShift = 0;
7033 memset(&file_info->Reserved[0], 0, 3);
7034
7035 rsp->OutputBufferLength =
7036 cpu_to_le32(sizeof(struct smb2_file_comp_info));
7037
7038 return 0;
7039 }
7040
get_file_attribute_tag_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)7041 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
7042 struct ksmbd_file *fp, void *rsp_org)
7043 {
7044 struct smb2_file_attr_tag_info *file_info;
7045
7046 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7047 pr_err("no right to read the attributes : 0x%x\n",
7048 fp->daccess);
7049 return -EACCES;
7050 }
7051
7052 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
7053 file_info->FileAttributes = fp->f_ci->m_fattr;
7054 file_info->ReparseTag = 0;
7055 rsp->OutputBufferLength =
7056 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
7057 return 0;
7058 }
7059
find_file_posix_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)7060 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
7061 struct ksmbd_file *fp, void *rsp_org)
7062 {
7063 struct smb311_posix_qinfo *file_info;
7064 struct inode *inode = file_inode(fp->filp);
7065 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
7066 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
7067 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
7068 struct kstat stat;
7069 u64 time;
7070 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
7071 int ret;
7072
7073 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7074 pr_err("no right to read the attributes : 0x%x\n",
7075 fp->daccess);
7076 return -EACCES;
7077 }
7078
7079 ret = get_file_allocation_stat(fp, &stat);
7080 if (ret)
7081 return ret;
7082
7083 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
7084 file_info->CreationTime = cpu_to_le64(fp->create_time);
7085 time = ksmbd_UnixTimeToNT(stat.atime);
7086 file_info->LastAccessTime = cpu_to_le64(time);
7087 time = ksmbd_UnixTimeToNT(stat.mtime);
7088 file_info->LastWriteTime = cpu_to_le64(time);
7089 file_info->ChangeTime = cpu_to_le64(fp->change_time);
7090 file_info->DosAttributes = fp->f_ci->m_fattr;
7091 file_info->Inode = cpu_to_le64(stat.ino);
7092 if (ksmbd_stream_fd(fp) == false) {
7093 file_info->EndOfFile = cpu_to_le64(stat.size);
7094 file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7095 } else {
7096 loff_t seof = ksmbd_stream_eof(fp);
7097
7098 file_info->EndOfFile = cpu_to_le64((u64)seof);
7099 file_info->AllocationSize = cpu_to_le64((u64)seof);
7100 }
7101 file_info->HardLinks = cpu_to_le32(stat.nlink);
7102 file_info->Mode = cpu_to_le32(stat.mode & 0777);
7103 switch (stat.mode & S_IFMT) {
7104 case S_IFDIR:
7105 file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
7106 break;
7107 case S_IFLNK:
7108 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
7109 break;
7110 case S_IFCHR:
7111 file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
7112 break;
7113 case S_IFBLK:
7114 file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
7115 break;
7116 case S_IFIFO:
7117 file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
7118 break;
7119 case S_IFSOCK:
7120 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
7121 }
7122
7123 file_info->DeviceId = cpu_to_le32(stat.rdev);
7124
7125 /*
7126 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
7127 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
7128 * sub_auth(4 * 1(num_subauth)) + RID(4).
7129 */
7130 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
7131 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
7132 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
7133 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
7134
7135 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
7136
7137 return 0;
7138 }
7139
smb2_get_info_file(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)7140 static int smb2_get_info_file(struct ksmbd_work *work,
7141 struct smb2_query_info_req *req,
7142 struct smb2_query_info_rsp *rsp)
7143 {
7144 struct ksmbd_file *fp;
7145 int fileinfoclass = 0;
7146 int rc = 0;
7147 unsigned int fixed_len;
7148 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7149
7150 if (test_share_config_flag(work->tcon->share_conf,
7151 KSMBD_SHARE_FLAG_PIPE)) {
7152 /* smb2 info file called for pipe */
7153 rc = smb2_get_info_file_pipe(work->sess, req, rsp,
7154 work->response_buf);
7155 goto iov_pin_out;
7156 }
7157
7158 if (work->next_smb2_rcv_hdr_off) {
7159 if (!has_file_id(req->VolatileFileId)) {
7160 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7161 work->compound_fid);
7162 id = work->compound_fid;
7163 pid = work->compound_pfid;
7164 }
7165 }
7166
7167 if (!has_file_id(id)) {
7168 id = req->VolatileFileId;
7169 pid = req->PersistentFileId;
7170 }
7171
7172 fp = ksmbd_lookup_fd_slow(work, id, pid);
7173 if (!fp)
7174 return -ENOENT;
7175
7176 fileinfoclass = req->FileInfoClass;
7177
7178 switch (fileinfoclass) {
7179 case FILE_ACCESS_INFORMATION:
7180 get_file_access_info(rsp, fp, work->response_buf);
7181 break;
7182
7183 case FILE_BASIC_INFORMATION:
7184 rc = get_file_basic_info(rsp, fp, work->response_buf);
7185 break;
7186
7187 case FILE_STANDARD_INFORMATION:
7188 rc = get_file_standard_info(rsp, fp, work->response_buf);
7189 break;
7190
7191 case FILE_ALIGNMENT_INFORMATION:
7192 get_file_alignment_info(rsp, work->response_buf);
7193 break;
7194
7195 case FILE_ALL_INFORMATION:
7196 rc = get_file_all_info(work, rsp, fp, work->response_buf);
7197 break;
7198
7199 case FILE_ALTERNATE_NAME_INFORMATION:
7200 get_file_alternate_info(work, rsp, fp, work->response_buf);
7201 break;
7202 case FILE_NORMALIZED_NAME_INFORMATION:
7203 rc = get_file_normalized_name_info(work, rsp, fp);
7204 break;
7205
7206 case FILE_STREAM_INFORMATION:
7207 rc = get_file_stream_info(work, rsp, fp, work->response_buf);
7208 break;
7209
7210 case FILE_INTERNAL_INFORMATION:
7211 rc = get_file_internal_info(rsp, fp, work->response_buf);
7212 break;
7213
7214 case FILE_NETWORK_OPEN_INFORMATION:
7215 rc = get_file_network_open_info(rsp, fp, work->response_buf);
7216 break;
7217
7218 case FILE_EA_INFORMATION:
7219 get_file_ea_info(rsp, work->response_buf);
7220 break;
7221
7222 case FILE_FULL_EA_INFORMATION:
7223 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
7224 break;
7225
7226 case FILE_POSITION_INFORMATION:
7227 get_file_position_info(rsp, fp, work->response_buf);
7228 break;
7229
7230 case FILE_MODE_INFORMATION:
7231 get_file_mode_info(rsp, fp, work->response_buf);
7232 break;
7233
7234 case FILE_COMPRESSION_INFORMATION:
7235 rc = get_file_compression_info(rsp, fp, work->response_buf);
7236 break;
7237
7238 case FILE_ATTRIBUTE_TAG_INFORMATION:
7239 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
7240 break;
7241 case SMB_FIND_FILE_POSIX_INFO:
7242 if (!work->tcon->posix_extensions) {
7243 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
7244 rc = -EOPNOTSUPP;
7245 } else {
7246 rc = find_file_posix_info(rsp, fp, work->response_buf);
7247 }
7248 break;
7249 default:
7250 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
7251 fileinfoclass);
7252 rc = -EOPNOTSUPP;
7253 }
7254 if (!rc) {
7255 fixed_len = le32_to_cpu(rsp->OutputBufferLength);
7256 switch (fileinfoclass) {
7257 case FILE_ALL_INFORMATION:
7258 fixed_len = FILE_ALL_INFORMATION_SIZE;
7259 break;
7260 case FILE_ALTERNATE_NAME_INFORMATION:
7261 fixed_len = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
7262 break;
7263 case FILE_STREAM_INFORMATION:
7264 fixed_len = FILE_STREAM_INFORMATION_SIZE;
7265 break;
7266 }
7267 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7268 fixed_len,
7269 rsp, work->response_buf);
7270 }
7271 ksmbd_fd_put(work, fp);
7272
7273 iov_pin_out:
7274 if (!rc)
7275 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7276 offsetof(struct smb2_query_info_rsp, Buffer) +
7277 le32_to_cpu(rsp->OutputBufferLength));
7278 return rc;
7279 }
7280
smb2_get_info_filesystem(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)7281 static int smb2_get_info_filesystem(struct ksmbd_work *work,
7282 struct smb2_query_info_req *req,
7283 struct smb2_query_info_rsp *rsp)
7284 {
7285 struct ksmbd_conn *conn = work->conn;
7286 struct ksmbd_share_config *share = work->tcon->share_conf;
7287 int fsinfoclass = 0;
7288 struct kstatfs stfs;
7289 struct path path;
7290 int rc = 0, len;
7291 unsigned int fixed_len = 0;
7292
7293 if (!share->path)
7294 return -EIO;
7295
7296 scoped_with_init_fs()
7297 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
7298 if (rc) {
7299 pr_err("cannot create vfs path\n");
7300 return -EIO;
7301 }
7302
7303 rc = vfs_statfs(&path, &stfs);
7304 if (rc) {
7305 pr_err("cannot do stat of path %s\n", share->path);
7306 path_put(&path);
7307 return -EIO;
7308 }
7309
7310 fsinfoclass = req->FileInfoClass;
7311
7312 switch (fsinfoclass) {
7313 case FS_DEVICE_INFORMATION:
7314 {
7315 FILE_SYSTEM_DEVICE_INFO *info;
7316
7317 info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
7318
7319 info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
7320 info->DeviceCharacteristics =
7321 cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
7322 if (!test_tree_conn_flag(work->tcon,
7323 KSMBD_TREE_CONN_FLAG_WRITABLE))
7324 info->DeviceCharacteristics |=
7325 cpu_to_le32(FILE_READ_ONLY_DEVICE);
7326 rsp->OutputBufferLength = cpu_to_le32(8);
7327 fixed_len = 8;
7328 break;
7329 }
7330 case FS_ATTRIBUTE_INFORMATION:
7331 {
7332 FILE_SYSTEM_ATTRIBUTE_INFO *info;
7333 struct file_kattr fa = {};
7334 size_t sz;
7335 u32 attrs;
7336 int err;
7337
7338 info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
7339 attrs = FILE_SUPPORTS_OBJECT_IDS |
7340 FILE_PERSISTENT_ACLS |
7341 FILE_UNICODE_ON_DISK |
7342 FILE_FILE_COMPRESSION |
7343 FILE_SUPPORTS_SPARSE_FILES |
7344 FILE_SUPPORTS_BLOCK_REFCOUNTING;
7345
7346 err = vfs_fileattr_get(path.dentry, &fa);
7347 /*
7348 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
7349 * filesystems that lack FS_IOC_FSGETXATTR support.
7350 */
7351 if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
7352 err != -EINVAL && err != -EOPNOTSUPP) {
7353 path_put(&path);
7354 return err;
7355 }
7356 if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
7357 attrs |= FILE_CASE_SENSITIVE_SEARCH;
7358 if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
7359 attrs |= FILE_CASE_PRESERVED_NAMES;
7360
7361 info->Attributes = cpu_to_le32(attrs);
7362 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
7363
7364 if (test_share_config_flag(work->tcon->share_conf,
7365 KSMBD_SHARE_FLAG_STREAMS))
7366 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
7367
7368 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
7369 /*
7370 * some application(potableapp) can not run on ksmbd share
7371 * because only NTFS handle security setting on windows.
7372 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
7373 * ksmbd should show share as NTFS. Later, If needed, we can add
7374 * fs type(s) parameter to change fs type user wanted.
7375 */
7376 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
7377 "NTFS", PATH_MAX, conn->local_nls, 0);
7378 len = len * 2;
7379 info->FileSystemNameLen = cpu_to_le32(len);
7380 sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
7381 rsp->OutputBufferLength = cpu_to_le32(sz);
7382 fixed_len = 16;
7383 break;
7384 }
7385 case FS_VOLUME_INFORMATION:
7386 {
7387 struct filesystem_vol_info *info;
7388 size_t sz;
7389 unsigned int serial_crc = 0;
7390
7391 info = (struct filesystem_vol_info *)(rsp->Buffer);
7392 info->VolumeCreationTime = 0;
7393 serial_crc = crc32_le(serial_crc, share->name,
7394 strlen(share->name));
7395 serial_crc = crc32_le(serial_crc, share->path,
7396 strlen(share->path));
7397 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
7398 strlen(ksmbd_netbios_name()));
7399 /* Taking dummy value of serial number*/
7400 info->VolumeSerialNumber = cpu_to_le32(serial_crc);
7401 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
7402 share->name, PATH_MAX,
7403 conn->local_nls, 0);
7404 len = len * 2;
7405 info->VolumeLabelLength = cpu_to_le32(len);
7406 info->Reserved = 0;
7407 info->SupportsObjects = 0;
7408 sz = sizeof(struct filesystem_vol_info) + len;
7409 rsp->OutputBufferLength = cpu_to_le32(sz);
7410 fixed_len = 24;
7411 break;
7412 }
7413 case FS_SIZE_INFORMATION:
7414 {
7415 FILE_SYSTEM_SIZE_INFO *info;
7416
7417 info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
7418 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
7419 info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
7420 info->SectorsPerAllocationUnit = cpu_to_le32(1);
7421 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
7422 rsp->OutputBufferLength = cpu_to_le32(24);
7423 fixed_len = 24;
7424 break;
7425 }
7426 case FS_FULL_SIZE_INFORMATION:
7427 {
7428 struct smb2_fs_full_size_info *info;
7429
7430 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
7431 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
7432 info->CallerAvailableAllocationUnits =
7433 cpu_to_le64(stfs.f_bavail);
7434 info->ActualAvailableAllocationUnits =
7435 cpu_to_le64(stfs.f_bfree);
7436 info->SectorsPerAllocationUnit = cpu_to_le32(1);
7437 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
7438 rsp->OutputBufferLength = cpu_to_le32(32);
7439 fixed_len = 32;
7440 break;
7441 }
7442 case FS_OBJECT_ID_INFORMATION:
7443 {
7444 struct object_id_info *info;
7445
7446 info = (struct object_id_info *)(rsp->Buffer);
7447
7448 if (path.mnt->mnt_sb->s_uuid_len == 16)
7449 memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
7450 path.mnt->mnt_sb->s_uuid_len);
7451 else
7452 memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
7453
7454 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
7455 info->extended_info.version = cpu_to_le32(1);
7456 info->extended_info.release = cpu_to_le32(1);
7457 info->extended_info.rel_date = 0;
7458 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
7459 rsp->OutputBufferLength = cpu_to_le32(64);
7460 fixed_len = 64;
7461 break;
7462 }
7463 case FS_SECTOR_SIZE_INFORMATION:
7464 {
7465 struct smb3_fs_ss_info *info;
7466 unsigned int sector_size =
7467 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
7468
7469 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
7470
7471 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
7472 info->PhysicalBytesPerSectorForAtomicity =
7473 cpu_to_le32(sector_size);
7474 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
7475 info->FSEffPhysicalBytesPerSectorForAtomicity =
7476 cpu_to_le32(sector_size);
7477 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
7478 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE |
7479 SSINFO_FLAGS_TRIM_ENABLED);
7480 info->ByteOffsetForSectorAlignment = 0;
7481 info->ByteOffsetForPartitionAlignment = 0;
7482 rsp->OutputBufferLength = cpu_to_le32(28);
7483 fixed_len = 28;
7484 break;
7485 }
7486 case FS_CONTROL_INFORMATION:
7487 {
7488 /*
7489 * TODO : The current implementation is based on
7490 * test result with win7(NTFS) server. It's need to
7491 * modify this to get valid Quota values
7492 * from Linux kernel
7493 */
7494 struct smb2_fs_control_info *info;
7495
7496 info = (struct smb2_fs_control_info *)(rsp->Buffer);
7497 info->FreeSpaceStartFiltering = 0;
7498 info->FreeSpaceThreshold = 0;
7499 info->FreeSpaceStopFiltering = 0;
7500 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
7501 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
7502 info->Padding = 0;
7503 rsp->OutputBufferLength = cpu_to_le32(48);
7504 fixed_len = 48;
7505 break;
7506 }
7507 case FS_POSIX_INFORMATION:
7508 {
7509 FILE_SYSTEM_POSIX_INFO *info;
7510
7511 if (!work->tcon->posix_extensions) {
7512 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
7513 path_put(&path);
7514 return -EOPNOTSUPP;
7515 } else {
7516 info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
7517 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
7518 info->BlockSize = cpu_to_le32(stfs.f_bsize);
7519 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
7520 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
7521 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
7522 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
7523 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
7524 rsp->OutputBufferLength = cpu_to_le32(56);
7525 fixed_len = 56;
7526 }
7527 break;
7528 }
7529 default:
7530 path_put(&path);
7531 return -EOPNOTSUPP;
7532 }
7533 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7534 fixed_len,
7535 rsp, work->response_buf);
7536 path_put(&path);
7537
7538 if (!rc)
7539 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7540 offsetof(struct smb2_query_info_rsp, Buffer) +
7541 le32_to_cpu(rsp->OutputBufferLength));
7542 return rc;
7543 }
7544
smb2_get_info_sec(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)7545 static int smb2_get_info_sec(struct ksmbd_work *work,
7546 struct smb2_query_info_req *req,
7547 struct smb2_query_info_rsp *rsp)
7548 {
7549 struct ksmbd_file *fp;
7550 struct mnt_idmap *idmap;
7551 struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
7552 struct smb_fattr fattr = {{0}};
7553 struct inode *inode;
7554 __u32 secdesclen = 0;
7555 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7556 int addition_info = le32_to_cpu(req->AdditionalInformation);
7557 int rc = 0, ppntsd_size = 0, max_len;
7558 size_t scratch_len = 0;
7559
7560 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
7561 PROTECTED_DACL_SECINFO |
7562 UNPROTECTED_DACL_SECINFO)) {
7563 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
7564 addition_info);
7565
7566 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7567 return -EINVAL;
7568 }
7569
7570 if (work->next_smb2_rcv_hdr_off) {
7571 if (!has_file_id(req->VolatileFileId)) {
7572 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7573 work->compound_fid);
7574 id = work->compound_fid;
7575 pid = work->compound_pfid;
7576 }
7577 }
7578
7579 if (!has_file_id(id)) {
7580 id = req->VolatileFileId;
7581 pid = req->PersistentFileId;
7582 }
7583
7584 fp = ksmbd_lookup_fd_slow(work, id, pid);
7585 if (!fp)
7586 return -ENOENT;
7587
7588 if (addition_info & (OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO) &&
7589 !(fp->daccess & FILE_READ_CONTROL_LE)) {
7590 ksmbd_fd_put(work, fp);
7591 return -EACCES;
7592 }
7593
7594 if (le32_to_cpu(req->OutputBufferLength) < sizeof(struct smb_ntsd)) {
7595 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7596 ksmbd_fd_put(work, fp);
7597 return -ENOSPC;
7598 }
7599
7600 idmap = file_mnt_idmap(fp->filp);
7601 inode = file_inode(fp->filp);
7602 ksmbd_acls_fattr(&fattr, idmap, inode);
7603
7604 if (test_share_config_flag(work->tcon->share_conf,
7605 KSMBD_SHARE_FLAG_ACL_XATTR))
7606 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
7607 fp->filp->f_path.dentry,
7608 &ppntsd);
7609
7610 /* Check if sd buffer size exceeds response buffer size */
7611 max_len = smb2_calc_max_out_buf_len(work,
7612 offsetof(struct smb2_query_info_rsp, Buffer),
7613 le32_to_cpu(req->OutputBufferLength));
7614 if (max_len < 0) {
7615 rc = -EINVAL;
7616 goto release_acl;
7617 }
7618
7619 scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
7620 ppntsd_size, addition_info);
7621 if (!scratch_len || scratch_len == SIZE_MAX) {
7622 rc = -EFBIG;
7623 goto release_acl;
7624 }
7625
7626 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
7627 if (!pntsd) {
7628 rc = -ENOMEM;
7629 goto release_acl;
7630 }
7631
7632 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
7633 addition_info, &secdesclen, &fattr);
7634
7635 release_acl:
7636 posix_acl_release(fattr.cf_acls);
7637 posix_acl_release(fattr.cf_dacls);
7638 kfree(ppntsd);
7639 ksmbd_fd_put(work, fp);
7640
7641 if (!rc && ALIGN(secdesclen, 8) > scratch_len)
7642 rc = -EFBIG;
7643 if (rc)
7644 goto err_out;
7645
7646 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
7647 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7648 le32_to_cpu(rsp->OutputBufferLength),
7649 rsp, work->response_buf);
7650 if (rc)
7651 goto err_out;
7652
7653 rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7654 offsetof(struct smb2_query_info_rsp, Buffer),
7655 pntsd, secdesclen);
7656 err_out:
7657 if (rc) {
7658 rsp->OutputBufferLength = 0;
7659 kvfree(pntsd);
7660 }
7661
7662 return rc;
7663 }
7664
7665 /**
7666 * smb2_query_info() - handler for smb2 query info command
7667 * @work: smb work containing query info request buffer
7668 *
7669 * Return: 0 on success, otherwise error
7670 */
smb2_query_info(struct ksmbd_work * work)7671 int smb2_query_info(struct ksmbd_work *work)
7672 {
7673 struct smb2_query_info_req *req;
7674 struct smb2_query_info_rsp *rsp;
7675 int rc = 0;
7676
7677 ksmbd_debug(SMB, "Received request smb2 query info request\n");
7678
7679 WORK_BUFFERS(work, req, rsp);
7680
7681 if (smb2_compound_has_failed(work, &rsp->hdr))
7682 return -EACCES;
7683
7684 if (ksmbd_override_fsids(work)) {
7685 rc = -ENOMEM;
7686 goto err_out;
7687 }
7688
7689 rsp->StructureSize = cpu_to_le16(9);
7690 rsp->OutputBufferOffset = cpu_to_le16(72);
7691
7692 switch (req->InfoType) {
7693 case SMB2_O_INFO_FILE:
7694 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
7695 rc = smb2_get_info_file(work, req, rsp);
7696 break;
7697 case SMB2_O_INFO_FILESYSTEM:
7698 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
7699 rc = smb2_get_info_filesystem(work, req, rsp);
7700 break;
7701 case SMB2_O_INFO_SECURITY:
7702 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
7703 rc = smb2_get_info_sec(work, req, rsp);
7704 break;
7705 default:
7706 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
7707 req->InfoType);
7708 rc = -EOPNOTSUPP;
7709 }
7710 ksmbd_revert_fsids(work);
7711
7712 err_out:
7713 if (rc < 0) {
7714 if (rc == -EACCES)
7715 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7716 else if (rc == -ENOENT)
7717 rsp->hdr.Status = STATUS_FILE_CLOSED;
7718 else if (rc == -EIO)
7719 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7720 else if (rc == -ENOMEM)
7721 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7722 else if (rc == -EINVAL && rsp->hdr.Status == 0)
7723 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7724 else if (rsp->hdr.Status == 0)
7725 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7726 smb2_set_err_rsp(work);
7727
7728 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
7729 rc);
7730 return rc;
7731 }
7732 return 0;
7733 }
7734
7735 /**
7736 * smb2_close_pipe() - handler for closing IPC pipe
7737 * @work: smb work containing close request buffer
7738 *
7739 * Return: 0
7740 */
smb2_close_pipe(struct ksmbd_work * work)7741 static noinline int smb2_close_pipe(struct ksmbd_work *work)
7742 {
7743 u64 id;
7744 struct smb2_close_req *req;
7745 struct smb2_close_rsp *rsp;
7746
7747 WORK_BUFFERS(work, req, rsp);
7748
7749 id = req->VolatileFileId;
7750 ksmbd_session_rpc_close(work->sess, id);
7751
7752 rsp->StructureSize = cpu_to_le16(60);
7753 rsp->Flags = 0;
7754 rsp->Reserved = 0;
7755 rsp->CreationTime = 0;
7756 rsp->LastAccessTime = 0;
7757 rsp->LastWriteTime = 0;
7758 rsp->ChangeTime = 0;
7759 rsp->AllocationSize = 0;
7760 rsp->EndOfFile = 0;
7761 rsp->Attributes = 0;
7762
7763 return ksmbd_iov_pin_rsp(work, (void *)rsp,
7764 sizeof(struct smb2_close_rsp));
7765 }
7766
7767 /**
7768 * smb2_close() - handler for smb2 close file command
7769 * @work: smb work containing close request buffer
7770 *
7771 * Return: 0 on success, otherwise error
7772 */
smb2_close(struct ksmbd_work * work)7773 int smb2_close(struct ksmbd_work *work)
7774 {
7775 u64 volatile_id = KSMBD_NO_FID;
7776 u64 sess_id;
7777 struct smb2_close_req *req;
7778 struct smb2_close_rsp *rsp;
7779 struct ksmbd_file *fp;
7780 u64 time;
7781 int err = 0;
7782
7783 ksmbd_debug(SMB, "Received smb2 close request\n");
7784
7785 WORK_BUFFERS(work, req, rsp);
7786
7787 if (smb2_compound_has_failed(work, &rsp->hdr))
7788 return -EACCES;
7789
7790 if (test_share_config_flag(work->tcon->share_conf,
7791 KSMBD_SHARE_FLAG_PIPE)) {
7792 ksmbd_debug(SMB, "IPC pipe close request\n");
7793 return smb2_close_pipe(work);
7794 }
7795
7796 sess_id = le64_to_cpu(req->hdr.SessionId);
7797 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
7798 sess_id = work->compound_sid;
7799
7800 work->compound_sid = 0;
7801 if (work->sess && work->sess->id == sess_id) {
7802 work->compound_sid = sess_id;
7803 } else {
7804 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
7805 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
7806 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7807 err = -EBADF;
7808 goto out;
7809 }
7810
7811 if (work->next_smb2_rcv_hdr_off &&
7812 !has_file_id(req->VolatileFileId)) {
7813 if (!has_file_id(work->compound_fid)) {
7814 /* file already closed, return FILE_CLOSED */
7815 ksmbd_debug(SMB, "file already closed\n");
7816 rsp->hdr.Status = STATUS_FILE_CLOSED;
7817 err = -EBADF;
7818 goto out;
7819 } else {
7820 ksmbd_debug(SMB,
7821 "Compound request set FID = %llu:%llu\n",
7822 work->compound_fid,
7823 work->compound_pfid);
7824 volatile_id = work->compound_fid;
7825
7826 /* file closed, stored id is not valid anymore */
7827 work->compound_fid = KSMBD_NO_FID;
7828 work->compound_pfid = KSMBD_NO_FID;
7829 }
7830 } else {
7831 volatile_id = req->VolatileFileId;
7832 }
7833 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
7834
7835 rsp->StructureSize = cpu_to_le16(60);
7836 rsp->Reserved = 0;
7837
7838 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
7839 struct kstat stat;
7840 int ret;
7841
7842 fp = ksmbd_lookup_fd_fast(work, volatile_id);
7843 if (!fp) {
7844 err = -ENOENT;
7845 goto out;
7846 }
7847
7848 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7849 AT_STATX_SYNC_AS_STAT);
7850 if (ret) {
7851 ksmbd_fd_put(work, fp);
7852 goto out;
7853 }
7854
7855 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
7856 rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
7857 rsp->EndOfFile = cpu_to_le64(stat.size);
7858 rsp->Attributes = fp->f_ci->m_fattr;
7859 rsp->CreationTime = cpu_to_le64(fp->create_time);
7860 time = ksmbd_UnixTimeToNT(stat.atime);
7861 rsp->LastAccessTime = cpu_to_le64(time);
7862 time = ksmbd_UnixTimeToNT(stat.mtime);
7863 if (time > fp->open_mtime &&
7864 time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
7865 time = fp->open_mtime;
7866 rsp->LastWriteTime = cpu_to_le64(time);
7867 rsp->ChangeTime = cpu_to_le64(fp->change_time);
7868 ksmbd_fd_put(work, fp);
7869 } else {
7870 rsp->Flags = 0;
7871 rsp->AllocationSize = 0;
7872 rsp->EndOfFile = 0;
7873 rsp->Attributes = 0;
7874 rsp->CreationTime = 0;
7875 rsp->LastAccessTime = 0;
7876 rsp->LastWriteTime = 0;
7877 rsp->ChangeTime = 0;
7878 }
7879
7880 err = ksmbd_close_fd(work, volatile_id);
7881 out:
7882 if (!err)
7883 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7884 sizeof(struct smb2_close_rsp));
7885
7886 if (err) {
7887 if (rsp->hdr.Status == 0)
7888 rsp->hdr.Status = STATUS_FILE_CLOSED;
7889 smb2_set_err_rsp(work);
7890 }
7891
7892 return err;
7893 }
7894
7895 /**
7896 * smb2_echo() - handler for smb2 echo(ping) command
7897 * @work: smb work containing echo request buffer
7898 *
7899 * Return: 0 on success, otherwise error
7900 */
smb2_echo(struct ksmbd_work * work)7901 int smb2_echo(struct ksmbd_work *work)
7902 {
7903 struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
7904
7905 ksmbd_debug(SMB, "Received smb2 echo request\n");
7906
7907 if (work->next_smb2_rcv_hdr_off)
7908 rsp = ksmbd_resp_buf_next(work);
7909
7910 rsp->StructureSize = cpu_to_le16(4);
7911 rsp->Reserved = 0;
7912 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
7913 }
7914
smb2_rename(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_rename_info * file_info,struct nls_table * local_nls)7915 static int smb2_rename(struct ksmbd_work *work,
7916 struct ksmbd_file *fp,
7917 struct smb2_file_rename_info *file_info,
7918 struct nls_table *local_nls)
7919 {
7920 struct ksmbd_share_config *share = fp->tcon->share_conf;
7921 char *new_name = NULL;
7922 int rc, flags = 0;
7923
7924 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
7925 new_name = smb2_get_name(file_info->FileName,
7926 le32_to_cpu(file_info->FileNameLength),
7927 local_nls);
7928 if (IS_ERR(new_name))
7929 return PTR_ERR(new_name);
7930
7931 if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
7932 int s_type;
7933 char *xattr_stream_name, *stream_name = NULL;
7934 size_t xattr_stream_size;
7935 int len;
7936
7937 rc = parse_stream_name(new_name, &stream_name, &s_type);
7938 if (rc < 0)
7939 goto out;
7940
7941 len = strlen(new_name);
7942 if (len > 0 && new_name[len - 1] != '/') {
7943 pr_err("not allow base filename in rename\n");
7944 rc = -ESHARE;
7945 goto out;
7946 }
7947
7948 rc = ksmbd_vfs_xattr_stream_name(stream_name,
7949 &xattr_stream_name,
7950 &xattr_stream_size,
7951 s_type);
7952 if (rc)
7953 goto out;
7954
7955 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
7956 &fp->filp->f_path,
7957 xattr_stream_name,
7958 NULL, 0, 0, true);
7959 if (rc < 0) {
7960 pr_err("failed to store stream name in xattr: %d\n",
7961 rc);
7962 rc = -EINVAL;
7963 }
7964 kfree(xattr_stream_name);
7965 goto out;
7966 }
7967
7968 ksmbd_debug(SMB, "new name %s\n", new_name);
7969 if (ksmbd_share_veto_filename(share, new_name)) {
7970 rc = -ENOENT;
7971 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
7972 goto out;
7973 }
7974
7975 if (!file_info->ReplaceIfExists)
7976 flags = RENAME_NOREPLACE;
7977
7978 rc = ksmbd_vfs_check_rename_share(work, &fp->filp->f_path);
7979 if (rc)
7980 goto out;
7981
7982 smb_break_all_levII_oplock_rename(work, fp);
7983 rc = ksmbd_vfs_rename(work, fp, new_name, flags);
7984 out:
7985 kfree(new_name);
7986 return rc;
7987 }
7988
smb2_create_link(struct ksmbd_work * work,struct ksmbd_share_config * share,struct smb2_file_link_info * file_info,unsigned int buf_len,struct file * filp,struct nls_table * local_nls)7989 static int smb2_create_link(struct ksmbd_work *work,
7990 struct ksmbd_share_config *share,
7991 struct smb2_file_link_info *file_info,
7992 unsigned int buf_len, struct file *filp,
7993 struct nls_table *local_nls)
7994 {
7995 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
7996 struct path path;
7997 int rc;
7998
7999 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
8000 le32_to_cpu(file_info->FileNameLength))
8001 return -EINVAL;
8002
8003 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
8004 pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
8005 if (!pathname)
8006 return -ENOMEM;
8007
8008 link_name = smb2_get_name(file_info->FileName,
8009 le32_to_cpu(file_info->FileNameLength),
8010 local_nls);
8011 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
8012 rc = -EINVAL;
8013 goto out;
8014 }
8015
8016 ksmbd_debug(SMB, "link name is %s\n", link_name);
8017 target_name = file_path(filp, pathname, PATH_MAX);
8018 if (IS_ERR(target_name)) {
8019 rc = -EINVAL;
8020 goto out;
8021 }
8022
8023 ksmbd_debug(SMB, "target name is %s\n", target_name);
8024 rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
8025 &path, 0);
8026 if (rc) {
8027 if (rc != -ENOENT)
8028 goto out;
8029 } else {
8030 if (file_info->ReplaceIfExists) {
8031 rc = ksmbd_vfs_remove_file(work, &path);
8032 if (rc) {
8033 rc = -EINVAL;
8034 ksmbd_debug(SMB, "cannot delete %s\n",
8035 link_name);
8036 }
8037 } else {
8038 rc = -EEXIST;
8039 ksmbd_debug(SMB, "link already exists\n");
8040 }
8041 ksmbd_vfs_kern_path_end_removing(&path);
8042 if (rc)
8043 goto out;
8044 }
8045 rc = ksmbd_vfs_link(work, target_name, link_name);
8046 if (rc)
8047 rc = -EINVAL;
8048 out:
8049
8050 if (!IS_ERR(link_name))
8051 kfree(link_name);
8052 kfree(pathname);
8053 return rc;
8054 }
8055
set_file_basic_info(struct ksmbd_file * fp,struct file_basic_info * file_info,struct ksmbd_share_config * share)8056 static int set_file_basic_info(struct ksmbd_file *fp,
8057 struct file_basic_info *file_info,
8058 struct ksmbd_share_config *share)
8059 {
8060 struct iattr attrs;
8061 struct file *filp;
8062 struct inode *inode;
8063 struct mnt_idmap *idmap;
8064 __le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE |
8065 FILE_ATTRIBUTE_COMPRESSED_LE;
8066 int rc = 0;
8067
8068 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
8069 return -EACCES;
8070
8071 attrs.ia_valid = 0;
8072 filp = fp->filp;
8073 inode = file_inode(filp);
8074 idmap = file_mnt_idmap(filp);
8075
8076 if (file_info->CreationTime)
8077 fp->create_time = le64_to_cpu(file_info->CreationTime);
8078
8079 if (file_info->LastAccessTime) {
8080 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
8081 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
8082 }
8083
8084 if (file_info->ChangeTime) {
8085 fp->change_time = le64_to_cpu(file_info->ChangeTime);
8086 inode_set_ctime_to_ts(inode,
8087 ksmbd_NTtimeToUnix(file_info->ChangeTime));
8088 }
8089
8090 if (file_info->LastWriteTime) {
8091 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
8092 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
8093 }
8094
8095 if (file_info->Attributes) {
8096 if (!S_ISDIR(inode->i_mode) &&
8097 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
8098 pr_err("can't change a file to a directory\n");
8099 return -EINVAL;
8100 }
8101
8102 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
8103 fp->f_ci->m_fattr =
8104 (file_info->Attributes & ~FILE_ATTRIBUTE_COMPRESSED_LE) |
8105 (fp->f_ci->m_fattr & attrs_mask);
8106 }
8107
8108 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
8109 (file_info->CreationTime || file_info->Attributes)) {
8110 struct xattr_dos_attrib da = {0};
8111
8112 da.version = 4;
8113 da.itime = fp->itime;
8114 da.create_time = fp->create_time;
8115 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8116 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
8117 XATTR_DOSINFO_ITIME;
8118
8119 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
8120 true);
8121 if (rc)
8122 ksmbd_debug(SMB,
8123 "failed to restore file attribute in EA\n");
8124 rc = 0;
8125 }
8126
8127 if (attrs.ia_valid) {
8128 struct dentry *dentry = filp->f_path.dentry;
8129 struct inode *inode = d_inode(dentry);
8130
8131 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
8132 return -EACCES;
8133
8134 inode_lock(inode);
8135 rc = notify_change(idmap, dentry, &attrs, NULL);
8136 inode_unlock(inode);
8137 }
8138 return rc;
8139 }
8140
set_file_allocation_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_alloc_info * file_alloc_info)8141 static int set_file_allocation_info(struct ksmbd_work *work,
8142 struct ksmbd_file *fp,
8143 struct smb2_file_alloc_info *file_alloc_info)
8144 {
8145 /*
8146 * TODO : It's working fine only when store dos attributes
8147 * is not yes. need to implement a logic which works
8148 * properly with any smb.conf option
8149 */
8150
8151 loff_t alloc_blks;
8152 u64 alloc_size;
8153 struct inode *inode;
8154 struct kstat stat;
8155 int rc;
8156
8157 if (!(fp->daccess & FILE_WRITE_DATA_LE))
8158 return -EACCES;
8159
8160 if (ksmbd_stream_fd(fp) == true)
8161 return 0;
8162
8163 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
8164 AT_STATX_SYNC_AS_STAT);
8165 if (rc)
8166 return rc;
8167
8168 /*
8169 * AllocationSize is fully client-controlled (the caller only
8170 * validates the fixed 8-byte buffer length). Reject values that
8171 * would overflow the "round up to 512-byte blocks" conversion
8172 * below instead of silently wrapping it to a tiny block count,
8173 * which would truncate the file to a size the client never
8174 * asked for.
8175 */
8176 alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
8177 if (alloc_size > MAX_LFS_FILESIZE - 511)
8178 return -EINVAL;
8179
8180 alloc_blks = (alloc_size + 511) >> 9;
8181 inode = file_inode(fp->filp);
8182
8183 if (alloc_blks > stat.blocks) {
8184 smb_break_all_levII_oplock(work, fp, 1);
8185 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
8186 alloc_blks * 512);
8187 if (rc && rc != -EOPNOTSUPP) {
8188 pr_err("vfs_fallocate is failed : %d\n", rc);
8189 return rc;
8190 }
8191 } else if (alloc_blks < stat.blocks) {
8192 loff_t size;
8193
8194 /*
8195 * Allocation size could be smaller than original one
8196 * which means allocated blocks in file should be
8197 * deallocated. use truncate to cut out it, but inode
8198 * size is also updated with truncate offset.
8199 * inode size is retained by backup inode size.
8200 */
8201 size = i_size_read(inode);
8202 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
8203 if (rc) {
8204 pr_err("truncate failed!, err %d\n", rc);
8205 return rc;
8206 }
8207 if (size < alloc_blks * 512)
8208 i_size_write(inode, size);
8209 }
8210
8211 fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
8212 fp->allocation_size_set = true;
8213 return 0;
8214 }
8215
set_end_of_file_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_eof_info * file_eof_info)8216 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8217 struct smb2_file_eof_info *file_eof_info)
8218 {
8219 loff_t newsize;
8220 struct inode *inode;
8221 int rc;
8222
8223 if (!(fp->daccess & FILE_WRITE_DATA_LE))
8224 return -EACCES;
8225
8226 newsize = le64_to_cpu(file_eof_info->EndOfFile);
8227 inode = file_inode(fp->filp);
8228
8229 /*
8230 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
8231 * on FAT32 shared device, truncate execution time is too long
8232 * and network error could cause from windows client. because
8233 * truncate of some filesystem like FAT32 fill zero data in
8234 * truncated range.
8235 */
8236 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
8237 ksmbd_stream_fd(fp) == false) {
8238 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
8239 rc = ksmbd_vfs_truncate(work, fp, newsize);
8240 if (rc) {
8241 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
8242 if (rc != -EAGAIN)
8243 rc = -EBADF;
8244 return rc;
8245 }
8246 }
8247 return 0;
8248 }
8249
set_rename_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_rename_info * rename_info,unsigned int buf_len)8250 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8251 struct smb2_file_rename_info *rename_info,
8252 unsigned int buf_len)
8253 {
8254 if (!(fp->daccess & FILE_DELETE_LE)) {
8255 pr_err("no right to delete : 0x%x\n", fp->daccess);
8256 return -EACCES;
8257 }
8258
8259 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
8260 le32_to_cpu(rename_info->FileNameLength))
8261 return -EINVAL;
8262
8263 if (!le32_to_cpu(rename_info->FileNameLength))
8264 return -EINVAL;
8265
8266 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
8267 }
8268
set_file_disposition_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_disposition_info * file_info)8269 static int set_file_disposition_info(struct ksmbd_work *work,
8270 struct ksmbd_file *fp,
8271 struct smb2_file_disposition_info *file_info)
8272 {
8273 struct inode *inode;
8274
8275 if (!(fp->daccess & FILE_DELETE_LE)) {
8276 pr_err("no right to delete : 0x%x\n", fp->daccess);
8277 return -EACCES;
8278 }
8279
8280 if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
8281 return -EACCES;
8282
8283 inode = file_inode(fp->filp);
8284 if (file_info->DeletePending) {
8285 if (ksmbd_has_stream_without_delete_share(fp))
8286 return -ESHARE;
8287
8288 if (S_ISDIR(inode->i_mode) && !ksmbd_stream_fd(fp) &&
8289 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
8290 return -EBUSY;
8291 smb_break_all_levII_oplock_for_delete(work, fp);
8292 ksmbd_fd_set_delete_pending(fp);
8293 } else {
8294 ksmbd_fd_clear_delete_pending(fp);
8295 }
8296 return 0;
8297 }
8298
set_file_position_info(struct ksmbd_file * fp,struct smb2_file_pos_info * file_info)8299 static int set_file_position_info(struct ksmbd_file *fp,
8300 struct smb2_file_pos_info *file_info)
8301 {
8302 loff_t current_byte_offset;
8303 unsigned long sector_size;
8304 struct inode *inode;
8305
8306 inode = file_inode(fp->filp);
8307 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
8308 sector_size = inode->i_sb->s_blocksize;
8309
8310 if (current_byte_offset < 0 ||
8311 (fp->coption & FILE_NO_INTERMEDIATE_BUFFERING_LE &&
8312 current_byte_offset & (sector_size - 1))) {
8313 pr_err("CurrentByteOffset is not valid : %llu\n",
8314 current_byte_offset);
8315 return -EINVAL;
8316 }
8317
8318 if (ksmbd_stream_fd(fp) == false)
8319 fp->filp->f_pos = current_byte_offset;
8320 else {
8321 if (current_byte_offset > XATTR_SIZE_MAX)
8322 current_byte_offset = XATTR_SIZE_MAX;
8323 fp->stream.pos = current_byte_offset;
8324 }
8325 return 0;
8326 }
8327
set_file_mode_info(struct ksmbd_file * fp,struct smb2_file_mode_info * file_info)8328 static int set_file_mode_info(struct ksmbd_file *fp,
8329 struct smb2_file_mode_info *file_info)
8330 {
8331 __le32 mode;
8332
8333 mode = file_info->Mode;
8334
8335 if ((mode & ~FILE_MODE_INFO_MASK)) {
8336 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
8337 return -EINVAL;
8338 }
8339
8340 /*
8341 * TODO : need to implement consideration for
8342 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
8343 */
8344 ksmbd_vfs_set_fadvise(fp->filp, mode);
8345 fp->coption = mode;
8346 return 0;
8347 }
8348
8349 /**
8350 * smb2_set_info_file() - handler for smb2 set info command
8351 * @work: smb work containing set info command buffer
8352 * @fp: ksmbd_file pointer
8353 * @req: request buffer pointer
8354 * @share: ksmbd_share_config pointer
8355 *
8356 * Return: 0 on success, otherwise error
8357 */
smb2_set_info_file(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_set_info_req * req,struct ksmbd_share_config * share)8358 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
8359 struct smb2_set_info_req *req,
8360 struct ksmbd_share_config *share)
8361 {
8362 unsigned int buf_len = le32_to_cpu(req->BufferLength);
8363 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
8364
8365 switch (req->FileInfoClass) {
8366 case FILE_BASIC_INFORMATION:
8367 {
8368 if (buf_len < sizeof(struct file_basic_info))
8369 return -EMSGSIZE;
8370
8371 return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
8372 }
8373 case FILE_ALLOCATION_INFORMATION:
8374 {
8375 if (buf_len < sizeof(struct smb2_file_alloc_info))
8376 return -EMSGSIZE;
8377
8378 return set_file_allocation_info(work, fp,
8379 (struct smb2_file_alloc_info *)buffer);
8380 }
8381 case FILE_END_OF_FILE_INFORMATION:
8382 {
8383 if (buf_len < sizeof(struct smb2_file_eof_info))
8384 return -EMSGSIZE;
8385
8386 return set_end_of_file_info(work, fp,
8387 (struct smb2_file_eof_info *)buffer);
8388 }
8389 case FILE_RENAME_INFORMATION:
8390 {
8391 if (buf_len < sizeof(struct smb2_file_rename_info))
8392 return -EMSGSIZE;
8393
8394 return set_rename_info(work, fp,
8395 (struct smb2_file_rename_info *)buffer,
8396 buf_len);
8397 }
8398 case FILE_LINK_INFORMATION:
8399 {
8400 struct smb2_file_link_info *file_info;
8401
8402 if (buf_len < sizeof(struct smb2_file_link_info))
8403 return -EMSGSIZE;
8404
8405 file_info = (struct smb2_file_link_info *)buffer;
8406 if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
8407 pr_err("no right to delete : 0x%x\n", fp->daccess);
8408 return -EACCES;
8409 }
8410
8411 return smb2_create_link(work, work->tcon->share_conf, file_info,
8412 buf_len, fp->filp,
8413 work->conn->local_nls);
8414 }
8415 case FILE_DISPOSITION_INFORMATION:
8416 {
8417 if (buf_len < sizeof(struct smb2_file_disposition_info))
8418 return -EMSGSIZE;
8419
8420 return set_file_disposition_info(work, fp,
8421 (struct smb2_file_disposition_info *)buffer);
8422 }
8423 case FILE_FULL_EA_INFORMATION:
8424 {
8425 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
8426 pr_err("Not permitted to write ext attr: 0x%x\n",
8427 fp->daccess);
8428 return -EACCES;
8429 }
8430
8431 if (buf_len < sizeof(struct smb2_ea_info))
8432 return -EMSGSIZE;
8433
8434 return smb2_set_ea((struct smb2_ea_info *)buffer,
8435 buf_len, &fp->filp->f_path, true);
8436 }
8437 case FILE_POSITION_INFORMATION:
8438 {
8439 if (buf_len < sizeof(struct smb2_file_pos_info))
8440 return -EMSGSIZE;
8441
8442 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
8443 }
8444 case FILE_MODE_INFORMATION:
8445 {
8446 if (buf_len < sizeof(struct smb2_file_mode_info))
8447 return -EMSGSIZE;
8448
8449 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
8450 }
8451 }
8452
8453 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
8454 return -EOPNOTSUPP;
8455 }
8456
smb2_set_info_sec(struct ksmbd_file * fp,int addition_info,char * buffer,int buf_len)8457 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
8458 char *buffer, int buf_len)
8459 {
8460 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
8461
8462 fp->saccess |= FILE_SHARE_DELETE_LE;
8463
8464 if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
8465 return -EACCES;
8466
8467 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
8468 buf_len, false, true);
8469 }
8470
8471 /**
8472 * smb2_set_info() - handler for smb2 set info command handler
8473 * @work: smb work containing set info request buffer
8474 *
8475 * Return: 0 on success, otherwise error
8476 */
smb2_set_info(struct ksmbd_work * work)8477 int smb2_set_info(struct ksmbd_work *work)
8478 {
8479 const struct cred *saved_cred;
8480 struct smb2_set_info_req *req;
8481 struct smb2_set_info_rsp *rsp;
8482 struct ksmbd_file *fp = NULL;
8483 int rc = 0;
8484 bool chseq_err = false;
8485 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8486
8487 ksmbd_debug(SMB, "Received smb2 set info request\n");
8488
8489 if (work->next_smb2_rcv_hdr_off) {
8490 req = ksmbd_req_buf_next(work);
8491 rsp = ksmbd_resp_buf_next(work);
8492 if (smb2_compound_has_failed(work, &rsp->hdr))
8493 return -EACCES;
8494 if (!has_file_id(req->VolatileFileId)) {
8495 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8496 work->compound_fid);
8497 id = work->compound_fid;
8498 pid = work->compound_pfid;
8499 }
8500 } else {
8501 req = smb_get_msg(work->request_buf);
8502 rsp = smb_get_msg(work->response_buf);
8503 }
8504
8505 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8506 ksmbd_debug(SMB, "User does not have write permission\n");
8507 pr_err("User does not have write permission\n");
8508 rc = -EACCES;
8509 goto err_out;
8510 }
8511
8512 if (!has_file_id(id)) {
8513 id = req->VolatileFileId;
8514 pid = req->PersistentFileId;
8515 }
8516
8517 fp = ksmbd_lookup_fd_slow(work, id, pid);
8518 if (!fp) {
8519 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
8520 rc = -ENOENT;
8521 goto err_out;
8522 }
8523
8524 rc = smb2_set_request_open(work, fp, &req->hdr, true, false);
8525 if (rc) {
8526 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
8527 chseq_err = true;
8528 goto err_out;
8529 }
8530
8531 saved_cred = override_creds(fp->filp->f_cred);
8532 switch (req->InfoType) {
8533 case SMB2_O_INFO_FILE:
8534 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
8535 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
8536 break;
8537 case SMB2_O_INFO_SECURITY:
8538 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
8539 rc = smb2_set_info_sec(fp,
8540 le32_to_cpu(req->AdditionalInformation),
8541 (char *)req + le16_to_cpu(req->BufferOffset),
8542 le32_to_cpu(req->BufferLength));
8543 break;
8544 default:
8545 rc = -EOPNOTSUPP;
8546 }
8547 revert_creds(saved_cred);
8548
8549 if (rc < 0)
8550 goto err_out;
8551
8552 rsp->StructureSize = cpu_to_le16(2);
8553 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
8554 sizeof(struct smb2_set_info_rsp));
8555 if (rc)
8556 goto err_out;
8557 ksmbd_fd_put(work, fp);
8558 return 0;
8559
8560 err_out:
8561 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV) {
8562 if (fp && req->InfoType == SMB2_O_INFO_FILE &&
8563 req->FileInfoClass == FILE_DISPOSITION_INFORMATION &&
8564 fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
8565 rsp->hdr.Status = STATUS_CANNOT_DELETE;
8566 else
8567 rsp->hdr.Status = STATUS_ACCESS_DENIED;
8568 }
8569 else if (rc == -EINVAL)
8570 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8571 else if (rc == -EMSGSIZE)
8572 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
8573 else if (rc == -ENOSPC || rc == -EFBIG)
8574 rsp->hdr.Status = STATUS_DISK_FULL;
8575 else if (rc == -ESHARE)
8576 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
8577 else if (rc == -ENOENT)
8578 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
8579 else if (rc == -EBUSY || rc == -ENOTEMPTY)
8580 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
8581 else if (rc == -EAGAIN && !chseq_err)
8582 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
8583 else if (rc == -EBADF || rc == -ESTALE)
8584 rsp->hdr.Status = STATUS_INVALID_HANDLE;
8585 else if (rc == -EEXIST)
8586 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
8587 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
8588 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
8589 smb2_set_err_rsp(work);
8590 ksmbd_fd_put(work, fp);
8591 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
8592 return rc;
8593 }
8594
8595 /**
8596 * smb2_read_pipe() - handler for smb2 read from IPC pipe
8597 * @work: smb work containing read IPC pipe command buffer
8598 *
8599 * Return: 0 on success, otherwise error
8600 */
smb2_read_pipe(struct ksmbd_work * work)8601 static noinline int smb2_read_pipe(struct ksmbd_work *work)
8602 {
8603 int nbytes = 0, err;
8604 u64 id;
8605 struct ksmbd_rpc_command *rpc_resp;
8606 struct smb2_read_req *req;
8607 struct smb2_read_rsp *rsp;
8608
8609 WORK_BUFFERS(work, req, rsp);
8610
8611 id = req->VolatileFileId;
8612
8613 rpc_resp = ksmbd_rpc_read(work->sess, id);
8614 if (rpc_resp) {
8615 void *aux_payload_buf;
8616
8617 if (rpc_resp->flags != KSMBD_RPC_OK) {
8618 err = -EINVAL;
8619 goto out;
8620 }
8621
8622 aux_payload_buf =
8623 kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
8624 if (!aux_payload_buf) {
8625 err = -ENOMEM;
8626 goto out;
8627 }
8628
8629 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
8630
8631 nbytes = rpc_resp->payload_sz;
8632 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
8633 offsetof(struct smb2_read_rsp, Buffer),
8634 aux_payload_buf, nbytes);
8635 if (err) {
8636 kvfree(aux_payload_buf);
8637 goto out;
8638 }
8639 kvfree(rpc_resp);
8640 } else {
8641 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
8642 offsetof(struct smb2_read_rsp, Buffer));
8643 if (err)
8644 goto out;
8645 }
8646
8647 rsp->StructureSize = cpu_to_le16(17);
8648 rsp->DataOffset = 80;
8649 rsp->Reserved = 0;
8650 rsp->DataLength = cpu_to_le32(nbytes);
8651 rsp->DataRemaining = 0;
8652 rsp->Flags = 0;
8653 return 0;
8654
8655 out:
8656 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
8657 smb2_set_err_rsp(work);
8658 kvfree(rpc_resp);
8659 return err;
8660 }
8661
8662 /**
8663 * smb2_set_rdma_key() - validate descriptors and save invalidation state
8664 * @work: request work item
8665 * @desc: first RDMA buffer descriptor
8666 * @Channel: nested RDMA channel type
8667 * @channel_info_len: descriptor array length
8668 *
8669 * Return: 0 on success, otherwise -EINVAL
8670 */
smb2_set_rdma_key(struct ksmbd_work * work,struct smbdirect_buffer_descriptor_v1 * desc,__le32 Channel,__le16 channel_info_len)8671 static int smb2_set_rdma_key(struct ksmbd_work *work,
8672 struct smbdirect_buffer_descriptor_v1 *desc,
8673 __le32 Channel, __le16 channel_info_len)
8674 {
8675 unsigned int i, ch_count;
8676
8677 if (Channel != SMB2_CHANNEL_RDMA_V1 &&
8678 Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE)
8679 return -EINVAL;
8680 if (work->conn->dialect == SMB30_PROT_ID &&
8681 Channel != SMB2_CHANNEL_RDMA_V1)
8682 return -EINVAL;
8683 if (le16_to_cpu(channel_info_len) % sizeof(*desc))
8684 return -EINVAL;
8685
8686 ch_count = le16_to_cpu(channel_info_len) / sizeof(*desc);
8687 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
8688 for (i = 0; i < ch_count; i++) {
8689 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
8690 i,
8691 le32_to_cpu(desc[i].token),
8692 le32_to_cpu(desc[i].length));
8693 }
8694 }
8695 if (!ch_count)
8696 return -EINVAL;
8697
8698 work->need_invalidate_rkey =
8699 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
8700 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
8701 work->remote_key = le32_to_cpu(desc->token);
8702 return 0;
8703 }
8704
8705 /**
8706 * smb2_prep_rdma_read() - transform an RDMA READ payload
8707 * @work: request work item
8708 * @req: READ request controlling encryption or signing
8709 * @rsp: READ response receiving transform metadata
8710 * @data: data that will be transferred through RDMA
8711 * @datalen: data length
8712 *
8713 * Encrypt the payload in place and encode the detached crypto metadata in
8714 * the response buffer.
8715 *
8716 * Return: metadata length, zero when no transform applies, or negative errno
8717 */
smb2_prep_rdma_read(struct ksmbd_work * work,struct smb2_read_req * req,struct smb2_read_rsp * rsp,void * data,unsigned int datalen)8718 static int smb2_prep_rdma_read(struct ksmbd_work *work,
8719 struct smb2_read_req *req,
8720 struct smb2_read_rsp *rsp,
8721 void *data, unsigned int datalen)
8722 {
8723 struct ksmbd_conn *conn = work->conn;
8724 struct smb2_rdma_transform *transform;
8725 struct smb2_rdma_crypto_transform *crypto;
8726 u8 *nonce;
8727 unsigned int nonce_len = 0, transform_len;
8728 u16 transform_type;
8729 int err;
8730
8731 if (!work->encrypted ||
8732 !(conn->rdma_transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)))
8733 return 0;
8734
8735 transform_type = SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION;
8736 nonce_len = (conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8737 conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
8738 SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
8739
8740 transform = (struct smb2_rdma_transform *)rsp->Buffer;
8741 crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
8742 memset(transform, 0, sizeof(*transform) + sizeof(*crypto) +
8743 SMB2_SIGNATURE_SIZE + nonce_len);
8744 transform->Channel = SMB2_CHANNEL_NONE;
8745 transform->TransformCount = cpu_to_le16(1);
8746
8747 crypto->TransformType = cpu_to_le16(transform_type);
8748 crypto->SignatureLength = cpu_to_le16(SMB2_SIGNATURE_SIZE);
8749 crypto->NonceLength = cpu_to_le16(nonce_len);
8750 nonce = crypto->Signature + SMB2_SIGNATURE_SIZE;
8751
8752 get_random_bytes(nonce, nonce_len);
8753 err = ksmbd_crypt_rdma(conn,
8754 work->sess->smb3encryptionkey,
8755 data, datalen, nonce, nonce_len,
8756 crypto->Signature,
8757 SMB2_SIGNATURE_SIZE, true);
8758 if (err) {
8759 pr_err("RDMA READ encryption failed: session=%llu payload=%u rc=%d\n",
8760 work->sess->id, datalen, err);
8761 return err;
8762 }
8763
8764 transform_len = sizeof(*transform) + sizeof(*crypto) +
8765 SMB2_SIGNATURE_SIZE + nonce_len;
8766 rsp->Flags = SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM;
8767 rsp->DataLength = cpu_to_le32(transform_len);
8768 ksmbd_debug(RDMA,
8769 "RDMA READ encryption prepared: session=%llu cipher=0x%04x payload=%u transform=%u nonce=%u tag=%u\n",
8770 work->sess->id, le16_to_cpu(conn->cipher_type), datalen,
8771 transform_len, nonce_len, SMB2_SIGNATURE_SIZE);
8772 return transform_len;
8773 }
8774
8775 struct smb2_rdma_write_transform {
8776 struct smbdirect_buffer_descriptor_v1 *desc;
8777 struct smb2_rdma_crypto_transform *crypto;
8778 u8 *nonce;
8779 unsigned int desc_len;
8780 unsigned int nonce_len;
8781 unsigned int signature_len;
8782 u16 type;
8783 __le32 channel;
8784 };
8785
8786 /**
8787 * smb2_current_req_len() - return the current compound request element size
8788 * @work: request work item
8789 * @hdr: current SMB2 header
8790 *
8791 * Return: current request element length measured from the SMB2 header
8792 */
smb2_current_req_len(struct ksmbd_work * work,struct smb2_hdr * hdr)8793 static unsigned int smb2_current_req_len(struct ksmbd_work *work,
8794 struct smb2_hdr *hdr)
8795 {
8796 if (hdr->NextCommand)
8797 return le32_to_cpu(hdr->NextCommand);
8798 return get_rfc1002_len(work->request_buf) -
8799 work->next_smb2_rcv_hdr_off;
8800 }
8801
8802 /**
8803 * check_rdma_desc() - validate an RDMA descriptor array
8804 * @desc: descriptor array
8805 * @desc_len: descriptor array length
8806 * @required_len: minimum aggregate buffer length
8807 *
8808 * Return: 0 when the descriptors cover the transfer, otherwise -EINVAL
8809 */
check_rdma_desc(struct smbdirect_buffer_descriptor_v1 * desc,unsigned int desc_len,unsigned int required_len)8810 static int check_rdma_desc(struct smbdirect_buffer_descriptor_v1 *desc,
8811 unsigned int desc_len,
8812 unsigned int required_len)
8813 {
8814 unsigned int i, count;
8815 u64 described_len = 0;
8816
8817 if (!desc_len || desc_len % sizeof(*desc))
8818 return -EINVAL;
8819 count = desc_len / sizeof(*desc);
8820 if (!le32_to_cpu(desc[0].length))
8821 return -EINVAL;
8822 for (i = 0; i < count; i++)
8823 described_len += le32_to_cpu(desc[i].length);
8824 return described_len < required_len ? -EINVAL : 0;
8825 }
8826
8827 /**
8828 * smb2_parse_rdma_write_transform() - validate RDMA WRITE transform metadata
8829 * @work: request work item
8830 * @req: WRITE request containing the transform
8831 * @info: parsed transform information
8832 *
8833 * Validate transform counts, crypto fields, descriptor alignment and bounds,
8834 * negotiated algorithms, and the nested RDMA channel.
8835 *
8836 * Return: 0 on success, otherwise a negative errno
8837 */
smb2_parse_rdma_write_transform(struct ksmbd_work * work,struct smb2_write_req * req,struct smb2_rdma_write_transform * info)8838 static int smb2_parse_rdma_write_transform(struct ksmbd_work *work,
8839 struct smb2_write_req *req,
8840 struct smb2_rdma_write_transform *info)
8841 {
8842 struct smb2_rdma_transform *transform;
8843 struct smb2_rdma_crypto_transform *crypto;
8844 unsigned int req_len = smb2_current_req_len(work, &req->hdr);
8845 unsigned int offset = le16_to_cpu(req->WriteChannelInfoOffset);
8846 unsigned int length = le16_to_cpu(req->WriteChannelInfoLength);
8847 unsigned int desc_offset, desc_len, crypto_len, expected_desc_offset;
8848 int err;
8849
8850 if (!work->conn->rdma_transform_ids ||
8851 offset < offsetof(struct smb2_write_req, Buffer) ||
8852 length < sizeof(*transform) || offset > req_len ||
8853 length > req_len - offset)
8854 return -EINVAL;
8855
8856 transform = (struct smb2_rdma_transform *)((char *)req + offset);
8857 if (le16_to_cpu(transform->TransformCount) != 1 ||
8858 (transform->Channel != SMB2_CHANNEL_RDMA_V1 &&
8859 transform->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE))
8860 return -EINVAL;
8861
8862 desc_offset = le16_to_cpu(transform->RdmaDescriptorOffset);
8863 desc_len = le16_to_cpu(transform->RdmaDescriptorLength);
8864 if (!desc_len || desc_len % sizeof(*info->desc) ||
8865 desc_offset < sizeof(*transform) || desc_offset > length ||
8866 desc_len > length - desc_offset)
8867 return -EINVAL;
8868
8869 crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
8870 if (length - sizeof(*transform) < sizeof(*crypto))
8871 return -EINVAL;
8872 info->type = le16_to_cpu(crypto->TransformType);
8873 info->signature_len = le16_to_cpu(crypto->SignatureLength);
8874 info->nonce_len = le16_to_cpu(crypto->NonceLength);
8875 if (!info->signature_len)
8876 return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
8877 -EBADMSG : -EINVAL;
8878 if (info->signature_len > SMB2_SIGNATURE_SIZE)
8879 return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
8880 -EBADMSG : -EINVAL;
8881 if (info->signature_len > length - sizeof(*transform) - sizeof(*crypto) ||
8882 info->nonce_len > length - sizeof(*transform) - sizeof(*crypto) -
8883 info->signature_len)
8884 return -EINVAL;
8885
8886 crypto_len = sizeof(*crypto) + info->signature_len + info->nonce_len;
8887 expected_desc_offset = ALIGN(sizeof(*transform) + crypto_len, 8);
8888 if (desc_offset != expected_desc_offset)
8889 return -EINVAL;
8890
8891 if (info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
8892 unsigned int expected_nonce_len;
8893
8894 if (!(work->conn->rdma_transform_ids &
8895 BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) || !work->encrypted)
8896 return -EINVAL;
8897 expected_nonce_len =
8898 (work->conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8899 work->conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
8900 SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
8901 if (info->nonce_len != expected_nonce_len)
8902 return -EBADMSG;
8903 } else {
8904 return -EINVAL;
8905 }
8906
8907 info->desc = (struct smbdirect_buffer_descriptor_v1 *)
8908 ((char *)transform + desc_offset);
8909 info->desc_len = desc_len;
8910 info->crypto = crypto;
8911 info->nonce = crypto->Signature + info->signature_len;
8912 info->channel = transform->Channel;
8913 err = check_rdma_desc(info->desc, info->desc_len,
8914 le32_to_cpu(req->RemainingBytes));
8915 if (err)
8916 return err;
8917
8918 ksmbd_debug(RDMA,
8919 "RDMA WRITE encryption metadata: session=%llu cipher=0x%04x payload=%u channel=0x%x descriptors=%zu nonce=%u tag=%u\n",
8920 work->sess->id, le16_to_cpu(work->conn->cipher_type),
8921 le32_to_cpu(req->RemainingBytes), le32_to_cpu(info->channel),
8922 info->desc_len / sizeof(*info->desc), info->nonce_len,
8923 info->signature_len);
8924 return 0;
8925 }
8926
8927 /**
8928 * smb2_read_rdma() - transfer READ data to client RDMA buffers
8929 * @work: request work item
8930 * @req: READ request containing client descriptors
8931 * @data_buf: data to transfer
8932 * @length: data length
8933 *
8934 * Return: transferred length on success, otherwise a negative errno
8935 */
smb2_read_rdma(struct ksmbd_work * work,struct smb2_read_req * req,void * data_buf,size_t length)8936 static ssize_t smb2_read_rdma(struct ksmbd_work *work,
8937 struct smb2_read_req *req, void *data_buf,
8938 size_t length)
8939 {
8940 int err;
8941
8942 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
8943 (struct smbdirect_buffer_descriptor_v1 *)
8944 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
8945 le16_to_cpu(req->ReadChannelInfoLength));
8946 if (err)
8947 return err;
8948
8949 return length;
8950 }
8951
8952 /**
8953 * smb2_read() - handler for smb2 read from file
8954 * @work: smb work containing read command buffer
8955 *
8956 * Return: 0 on success, otherwise error
8957 */
smb2_read(struct ksmbd_work * work)8958 int smb2_read(struct ksmbd_work *work)
8959 {
8960 struct ksmbd_conn *conn = work->conn;
8961 struct smb2_read_req *req;
8962 struct smb2_read_rsp *rsp;
8963 struct ksmbd_file *fp = NULL;
8964 loff_t offset;
8965 size_t length, mincount;
8966 ssize_t nbytes = 0, remain_bytes = 0;
8967 int err = 0;
8968 int rdma_transform_len = 0;
8969 bool is_rdma_channel = false, async_interim = false;
8970 unsigned int max_read_size = conn->vals->max_read_size;
8971 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8972 void *aux_payload_buf;
8973
8974 ksmbd_debug(SMB, "Received smb2 read request\n");
8975
8976 if (test_share_config_flag(work->tcon->share_conf,
8977 KSMBD_SHARE_FLAG_PIPE)) {
8978 ksmbd_debug(SMB, "IPC pipe read request\n");
8979 return smb2_read_pipe(work);
8980 }
8981
8982 if (work->next_smb2_rcv_hdr_off) {
8983 req = ksmbd_req_buf_next(work);
8984 rsp = ksmbd_resp_buf_next(work);
8985 if (smb2_compound_has_failed(work, &rsp->hdr))
8986 return -EACCES;
8987 if (!has_file_id(req->VolatileFileId)) {
8988 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8989 work->compound_fid);
8990 id = work->compound_fid;
8991 pid = work->compound_pfid;
8992 }
8993 } else {
8994 req = smb_get_msg(work->request_buf);
8995 rsp = smb_get_msg(work->response_buf);
8996 }
8997
8998 if (!has_file_id(id)) {
8999 id = req->VolatileFileId;
9000 pid = req->PersistentFileId;
9001 }
9002
9003 if (req->Channel != SMB2_CHANNEL_NONE &&
9004 req->Channel != SMB2_CHANNEL_RDMA_V1 &&
9005 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
9006 err = -EINVAL;
9007 goto out;
9008 }
9009 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
9010 req->Channel == SMB2_CHANNEL_RDMA_V1) {
9011 is_rdma_channel = true;
9012 max_read_size = get_smbd_max_read_write_size(work->conn->transport);
9013 if (max_read_size == 0) {
9014 err = -EINVAL;
9015 goto out;
9016 }
9017 }
9018
9019 if (is_rdma_channel == true) {
9020 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
9021 unsigned int ch_len = le16_to_cpu(req->ReadChannelInfoLength);
9022 unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9023 struct smbdirect_buffer_descriptor_v1 *desc;
9024
9025 if (!le32_to_cpu(req->Length) ||
9026 ch_offset < offsetof(struct smb2_read_req, Buffer) ||
9027 ch_offset > req_len || ch_len > req_len - ch_offset) {
9028 err = -EINVAL;
9029 goto out;
9030 }
9031 desc = (struct smbdirect_buffer_descriptor_v1 *)
9032 ((char *)req + ch_offset);
9033 err = check_rdma_desc(desc, ch_len, le32_to_cpu(req->Length));
9034 if (err)
9035 goto out;
9036 err = smb2_set_rdma_key(work, desc,
9037 req->Channel,
9038 req->ReadChannelInfoLength);
9039 if (err)
9040 goto out;
9041 }
9042
9043 fp = ksmbd_lookup_fd_slow(work, id, pid);
9044 if (!fp) {
9045 err = -ENOENT;
9046 goto out;
9047 }
9048
9049 err = smb2_set_request_open(work, fp, &req->hdr, true, true);
9050 if (err)
9051 goto out;
9052
9053 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
9054 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
9055 err = -EACCES;
9056 goto out;
9057 }
9058
9059 if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
9060 err = setup_async_work(work, NULL, NULL);
9061 if (err)
9062 goto out;
9063 smb2_send_interim_resp(work, STATUS_PENDING);
9064 async_interim = true;
9065 }
9066
9067 offset = le64_to_cpu(req->Offset);
9068 if (offset < 0) {
9069 err = -EINVAL;
9070 goto out;
9071 }
9072 length = le32_to_cpu(req->Length);
9073 mincount = le32_to_cpu(req->MinimumCount);
9074
9075 if (length > max_read_size) {
9076 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
9077 max_read_size);
9078 err = -EINVAL;
9079 goto out;
9080 }
9081
9082 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
9083 fp->filp, offset, length);
9084
9085 aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
9086 if (!aux_payload_buf) {
9087 err = -ENOMEM;
9088 goto out;
9089 }
9090
9091 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
9092 if (nbytes < 0) {
9093 kvfree(aux_payload_buf);
9094 err = nbytes;
9095 goto out;
9096 }
9097
9098 /*
9099 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
9100 * tail of the un-zeroed buffer is transmitted as compound-response
9101 * alignment padding, leaking uninitialized kernel memory to the
9102 * client. Zero just that tail.
9103 */
9104 if (nbytes & 7)
9105 memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
9106
9107 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
9108 kvfree(aux_payload_buf);
9109 rsp->hdr.Status = STATUS_END_OF_FILE;
9110 smb2_set_err_rsp(work);
9111 if (async_interim)
9112 release_async_work(work);
9113 ksmbd_fd_put(work, fp);
9114 return -ENODATA;
9115 }
9116
9117 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
9118 nbytes, offset, mincount);
9119
9120 if (is_rdma_channel == true) {
9121 rdma_transform_len = smb2_prep_rdma_read(work, req,
9122 rsp,
9123 aux_payload_buf,
9124 nbytes);
9125 if (rdma_transform_len < 0) {
9126 kvfree(aux_payload_buf);
9127 err = rdma_transform_len;
9128 goto out;
9129 }
9130 /* write data to the client using rdma channel */
9131 remain_bytes = smb2_read_rdma(work, req,
9132 aux_payload_buf,
9133 nbytes);
9134 if (remain_bytes < 0)
9135 pr_err("RDMA READ transfer failed: session=%llu payload=%zu transform=%d rc=%zd\n",
9136 work->sess ? work->sess->id : 0, nbytes,
9137 rdma_transform_len, remain_bytes);
9138 else
9139 ksmbd_debug(RDMA,
9140 "RDMA READ transfer completed: session=%llu payload=%zu transform=%d\n",
9141 work->sess ? work->sess->id : 0, nbytes,
9142 rdma_transform_len);
9143 kvfree(aux_payload_buf);
9144 aux_payload_buf = NULL;
9145 nbytes = 0;
9146 if (remain_bytes < 0) {
9147 err = (int)remain_bytes;
9148 goto out;
9149 }
9150 }
9151
9152 rsp->StructureSize = cpu_to_le16(17);
9153 rsp->DataOffset = 80;
9154 rsp->Reserved = 0;
9155 rsp->DataLength = cpu_to_le32(rdma_transform_len ?: nbytes);
9156 rsp->DataRemaining = cpu_to_le32(remain_bytes);
9157 rsp->Flags = rdma_transform_len ?
9158 SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM : 0;
9159 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
9160 offsetof(struct smb2_read_rsp, Buffer) +
9161 rdma_transform_len,
9162 aux_payload_buf, nbytes);
9163 if (err) {
9164 kvfree(aux_payload_buf);
9165 goto out;
9166 }
9167 if (async_interim)
9168 release_async_work(work);
9169 /*
9170 * RDMA responses are transferred through channel buffers and encrypted
9171 * responses use the encryption transform, so only normal SMB transport
9172 * responses are candidates for compression.
9173 */
9174 if (!is_rdma_channel && nbytes &&
9175 (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
9176 conn->compress_algorithm != SMB3_COMPRESS_NONE)
9177 work->compress_response = true;
9178 ksmbd_fd_put(work, fp);
9179 return 0;
9180
9181 out:
9182 if (async_interim)
9183 release_async_work(work);
9184 if (err) {
9185 if (err == -EISDIR)
9186 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
9187 else if (err == -EAGAIN)
9188 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9189 else if (err == -ENOENT)
9190 rsp->hdr.Status = STATUS_FILE_CLOSED;
9191 else if (err == -EACCES)
9192 rsp->hdr.Status = STATUS_ACCESS_DENIED;
9193 else if (err == -ESHARE)
9194 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9195 else if (err == -EINVAL)
9196 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9197 else
9198 rsp->hdr.Status = STATUS_INVALID_HANDLE;
9199
9200 smb2_set_err_rsp(work);
9201 }
9202 ksmbd_fd_put(work, fp);
9203 return err;
9204 }
9205
9206 /**
9207 * smb2_write_pipe() - handler for smb2 write on IPC pipe
9208 * @work: smb work containing write IPC pipe command buffer
9209 *
9210 * Return: 0 on success, otherwise error
9211 */
smb2_write_pipe(struct ksmbd_work * work)9212 static noinline int smb2_write_pipe(struct ksmbd_work *work)
9213 {
9214 struct smb2_write_req *req;
9215 struct smb2_write_rsp *rsp;
9216 struct ksmbd_rpc_command *rpc_resp;
9217 u64 id = 0;
9218 int err = 0, ret = 0;
9219 char *data_buf;
9220 size_t length;
9221
9222 WORK_BUFFERS(work, req, rsp);
9223
9224 length = le32_to_cpu(req->Length);
9225 id = req->VolatileFileId;
9226
9227 if ((u64)le16_to_cpu(req->DataOffset) + length >
9228 get_rfc1002_len(work->request_buf)) {
9229 pr_err("invalid write data offset %u, smb_len %u\n",
9230 le16_to_cpu(req->DataOffset),
9231 get_rfc1002_len(work->request_buf));
9232 err = -EINVAL;
9233 goto out;
9234 }
9235
9236 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
9237 le16_to_cpu(req->DataOffset));
9238
9239 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
9240 if (rpc_resp) {
9241 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
9242 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
9243 kvfree(rpc_resp);
9244 smb2_set_err_rsp(work);
9245 return -EOPNOTSUPP;
9246 }
9247 if (rpc_resp->flags != KSMBD_RPC_OK) {
9248 rsp->hdr.Status = STATUS_INVALID_HANDLE;
9249 smb2_set_err_rsp(work);
9250 kvfree(rpc_resp);
9251 return ret;
9252 }
9253 kvfree(rpc_resp);
9254 }
9255
9256 rsp->StructureSize = cpu_to_le16(17);
9257 rsp->DataOffset = 0;
9258 rsp->Reserved = 0;
9259 rsp->DataLength = cpu_to_le32(length);
9260 rsp->DataRemaining = 0;
9261 rsp->Reserved2 = 0;
9262 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
9263 offsetof(struct smb2_write_rsp, Buffer));
9264 out:
9265 if (err) {
9266 rsp->hdr.Status = STATUS_INVALID_HANDLE;
9267 smb2_set_err_rsp(work);
9268 }
9269
9270 return err;
9271 }
9272
9273 /**
9274 * smb2_write_rdma() - receive and store an RDMA WRITE payload
9275 * @work: request work item
9276 * @desc: client RDMA buffer descriptors
9277 * @desc_len: descriptor array length
9278 * @transform: parsed transform, or NULL for an untransformed transfer
9279 * @fp: target open file
9280 * @offset: target file offset
9281 * @length: transfer length
9282 * @sync: request synchronous storage completion
9283 *
9284 * Receive the payload, authenticate or decrypt it when required, and write it
9285 * to the target file.
9286 *
9287 * Return: written byte count on success, otherwise a negative errno
9288 */
smb2_write_rdma(struct ksmbd_work * work,struct smbdirect_buffer_descriptor_v1 * desc,unsigned int desc_len,struct smb2_rdma_write_transform * transform,struct ksmbd_file * fp,loff_t offset,size_t length,bool sync)9289 static ssize_t smb2_write_rdma(struct ksmbd_work *work,
9290 struct smbdirect_buffer_descriptor_v1 *desc,
9291 unsigned int desc_len,
9292 struct smb2_rdma_write_transform *transform,
9293 struct ksmbd_file *fp, loff_t offset,
9294 size_t length, bool sync)
9295 {
9296 char *data_buf;
9297 int ret;
9298 ssize_t nbytes;
9299
9300 data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
9301 if (!data_buf)
9302 return -ENOMEM;
9303
9304 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length, desc,
9305 desc_len);
9306 if (ret < 0) {
9307 if (transform)
9308 pr_err("RDMA WRITE encrypted transfer failed: session=%llu payload=%zu rdma_read_rc=%d\n",
9309 work->sess->id, length, ret);
9310 kvfree(data_buf);
9311 return ret;
9312 }
9313 if (transform &&
9314 transform->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
9315 ret = ksmbd_crypt_rdma(work->conn,
9316 work->sess->smb3decryptionkey,
9317 data_buf, length, transform->nonce,
9318 transform->nonce_len,
9319 transform->crypto->Signature,
9320 transform->signature_len, false);
9321 if (ret) {
9322 pr_err("RDMA WRITE decryption failed: session=%llu payload=%zu rc=%d\n",
9323 work->sess->id, length, ret);
9324 kvfree(data_buf);
9325 return ret == -ENOMEM ? ret : -EBADMSG;
9326 }
9327 }
9328
9329 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
9330 kvfree(data_buf);
9331 if (ret < 0) {
9332 if (transform)
9333 pr_err("RDMA WRITE encrypted file write failed: session=%llu payload=%zu rc=%d\n",
9334 work->sess->id, length, ret);
9335 return ret;
9336 }
9337 ksmbd_debug(RDMA,
9338 "RDMA WRITE transfer completed: session=%llu payload=%zu transformed=%u written=%zd\n",
9339 work->sess ? work->sess->id : 0, length, !!transform, nbytes);
9340
9341 return nbytes;
9342 }
9343
9344 /**
9345 * smb2_write() - handler for smb2 write from file
9346 * @work: smb work containing write command buffer
9347 *
9348 * Return: 0 on success, otherwise error
9349 */
smb2_write(struct ksmbd_work * work)9350 int smb2_write(struct ksmbd_work *work)
9351 {
9352 struct smb2_write_req *req;
9353 struct smb2_write_rsp *rsp;
9354 struct smb2_rdma_write_transform rdma_transform = {};
9355 struct smb2_rdma_write_transform *rdma_info = NULL;
9356 struct smbdirect_buffer_descriptor_v1 *rdma_desc = NULL;
9357 unsigned int rdma_desc_len = 0;
9358 struct ksmbd_file *fp = NULL;
9359 loff_t offset;
9360 size_t length;
9361 ssize_t nbytes;
9362 char *data_buf;
9363 bool writethrough = false, is_rdma_channel = false;
9364 bool async_interim = false;
9365 bool chseq_err = false;
9366 int err = 0;
9367 unsigned int max_write_size = work->conn->vals->max_write_size;
9368 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9369
9370 ksmbd_debug(SMB, "Received smb2 write request\n");
9371
9372 WORK_BUFFERS(work, req, rsp);
9373
9374 if (smb2_compound_has_failed(work, &rsp->hdr))
9375 return -EACCES;
9376
9377 if (work->next_smb2_rcv_hdr_off &&
9378 !has_file_id(req->VolatileFileId)) {
9379 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9380 work->compound_fid);
9381 id = work->compound_fid;
9382 pid = work->compound_pfid;
9383 }
9384
9385 if (!has_file_id(id)) {
9386 id = req->VolatileFileId;
9387 pid = req->PersistentFileId;
9388 }
9389
9390 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
9391 ksmbd_debug(SMB, "IPC pipe write request\n");
9392 return smb2_write_pipe(work);
9393 }
9394
9395 offset = le64_to_cpu(req->Offset);
9396 if (offset < 0) {
9397 err = -EINVAL;
9398 goto out;
9399 }
9400 length = le32_to_cpu(req->Length);
9401
9402 if (req->Channel != SMB2_CHANNEL_NONE &&
9403 req->Channel != SMB2_CHANNEL_RDMA_V1 &&
9404 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE &&
9405 req->Channel != SMB2_CHANNEL_RDMA_TRANSFORM) {
9406 err = -EINVAL;
9407 goto out;
9408 }
9409 if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM &&
9410 work->conn->dialect != SMB311_PROT_ID) {
9411 err = -EINVAL;
9412 goto out;
9413 }
9414 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
9415 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
9416 req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
9417 is_rdma_channel = true;
9418 max_write_size = get_smbd_max_read_write_size(work->conn->transport);
9419 if (max_write_size == 0) {
9420 err = -EINVAL;
9421 goto out;
9422 }
9423 length = le32_to_cpu(req->RemainingBytes);
9424 }
9425
9426 if (length) {
9427 u64 end = (u64)offset + length;
9428
9429 if (end > SMB2_MAX_FILE_SIZE) {
9430 err = -EINVAL;
9431 goto out;
9432 }
9433 if (end == SMB2_MAX_FILE_SIZE) {
9434 err = -EFBIG;
9435 goto out;
9436 }
9437 }
9438
9439 if (is_rdma_channel == true) {
9440 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
9441 unsigned int ch_len = le16_to_cpu(req->WriteChannelInfoLength);
9442 unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9443
9444 if (!length || req->Length != 0 || req->DataOffset != 0 ||
9445 ch_offset < offsetof(struct smb2_write_req, Buffer) ||
9446 ch_offset > req_len || ch_len > req_len - ch_offset) {
9447 err = -EINVAL;
9448 goto out;
9449 }
9450 if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
9451 err = smb2_parse_rdma_write_transform(work, req,
9452 &rdma_transform);
9453 if (err) {
9454 pr_err("RDMA WRITE encryption metadata rejected: session=%llu rc=%d\n",
9455 work->sess ? work->sess->id : 0, err);
9456 goto out;
9457 }
9458 rdma_desc = rdma_transform.desc;
9459 rdma_desc_len = rdma_transform.desc_len;
9460 rdma_info = &rdma_transform;
9461 err = smb2_set_rdma_key(work, rdma_desc,
9462 rdma_transform.channel,
9463 cpu_to_le16(rdma_desc_len));
9464 } else {
9465 rdma_desc = (struct smbdirect_buffer_descriptor_v1 *)
9466 ((char *)req + ch_offset);
9467 rdma_desc_len = ch_len;
9468 err = check_rdma_desc(rdma_desc, rdma_desc_len, length);
9469 if (err)
9470 goto out;
9471 err = smb2_set_rdma_key(work, rdma_desc,
9472 req->Channel,
9473 req->WriteChannelInfoLength);
9474 }
9475 if (err)
9476 goto out;
9477 }
9478
9479 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9480 ksmbd_debug(SMB, "User does not have write permission\n");
9481 err = -EACCES;
9482 goto out;
9483 }
9484
9485 fp = ksmbd_lookup_fd_slow(work, id, pid);
9486 if (!fp) {
9487 err = -ENOENT;
9488 goto out;
9489 }
9490
9491 err = smb2_set_request_open(work, fp, &req->hdr, true, false);
9492 if (err) {
9493 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
9494 chseq_err = true;
9495 goto out;
9496 }
9497
9498 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
9499 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
9500 err = -EACCES;
9501 goto out;
9502 }
9503
9504 if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
9505 err = setup_async_work(work, NULL, NULL);
9506 if (err)
9507 goto out;
9508 smb2_send_interim_resp(work, STATUS_PENDING);
9509 async_interim = true;
9510 }
9511
9512 if (length > max_write_size) {
9513 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
9514 max_write_size);
9515 err = -EINVAL;
9516 goto out;
9517 }
9518
9519 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
9520 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
9521 writethrough = true;
9522
9523 if (is_rdma_channel == false) {
9524 if (le16_to_cpu(req->DataOffset) <
9525 offsetof(struct smb2_write_req, Buffer)) {
9526 err = -EINVAL;
9527 goto out;
9528 }
9529
9530 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
9531 le16_to_cpu(req->DataOffset));
9532
9533 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
9534 fp->filp, offset, length);
9535 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
9536 writethrough, &nbytes);
9537 if (err < 0)
9538 goto out;
9539 } else {
9540 /* read data from the client using rdma channel, and
9541 * write the data.
9542 */
9543 nbytes = smb2_write_rdma(work, rdma_desc, rdma_desc_len,
9544 rdma_info, fp, offset, length,
9545 writethrough);
9546 if (nbytes < 0) {
9547 err = (int)nbytes;
9548 goto out;
9549 }
9550 }
9551
9552 rsp->StructureSize = cpu_to_le16(17);
9553 rsp->DataOffset = 0;
9554 rsp->Reserved = 0;
9555 rsp->DataLength = cpu_to_le32(nbytes);
9556 rsp->DataRemaining = 0;
9557 rsp->Reserved2 = 0;
9558 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
9559 if (err)
9560 goto out;
9561 if (async_interim)
9562 release_async_work(work);
9563 ksmbd_fd_put(work, fp);
9564 return 0;
9565
9566 out:
9567 if (async_interim)
9568 release_async_work(work);
9569
9570 if (err == -EAGAIN && !chseq_err)
9571 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9572 else if (err == -ENOSPC || err == -EFBIG)
9573 rsp->hdr.Status = STATUS_DISK_FULL;
9574 else if (err == -ENOENT)
9575 rsp->hdr.Status = STATUS_FILE_CLOSED;
9576 else if (err == -EACCES)
9577 rsp->hdr.Status = STATUS_ACCESS_DENIED;
9578 else if (err == -ESHARE)
9579 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9580 else if (err == -EINVAL)
9581 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9582 else if (err == -EBADMSG)
9583 rsp->hdr.Status = STATUS_AUTH_TAG_MISMATCH;
9584 else if (err == -EKEYREJECTED)
9585 rsp->hdr.Status = STATUS_INVALID_SIGNATURE;
9586 else if (rsp->hdr.Status == 0)
9587 rsp->hdr.Status = STATUS_INVALID_HANDLE;
9588
9589 smb2_set_err_rsp(work);
9590 ksmbd_fd_put(work, fp);
9591 return err;
9592 }
9593
9594 /**
9595 * smb2_flush() - handler for smb2 flush file - fsync
9596 * @work: smb work containing flush command buffer
9597 *
9598 * Return: 0 on success, otherwise error
9599 */
smb2_flush(struct ksmbd_work * work)9600 int smb2_flush(struct ksmbd_work *work)
9601 {
9602 struct smb2_flush_req *req;
9603 struct smb2_flush_rsp *rsp;
9604 u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9605 int err;
9606
9607 WORK_BUFFERS(work, req, rsp);
9608
9609 ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
9610
9611 if (smb2_compound_has_failed(work, &rsp->hdr))
9612 return -EACCES;
9613
9614 if (work->next_smb2_rcv_hdr_off &&
9615 !has_file_id(req->VolatileFileId)) {
9616 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9617 work->compound_fid);
9618 id = work->compound_fid;
9619 pid = work->compound_pfid;
9620 }
9621
9622 if (!has_file_id(id)) {
9623 id = req->VolatileFileId;
9624 pid = req->PersistentFileId;
9625 }
9626
9627 err = ksmbd_vfs_fsync(work, id, pid);
9628 if (err)
9629 goto out;
9630
9631 rsp->StructureSize = cpu_to_le16(4);
9632 rsp->Reserved = 0;
9633 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
9634
9635 out:
9636 rsp->hdr.Status = STATUS_INVALID_HANDLE;
9637 smb2_set_err_rsp(work);
9638 return err;
9639 }
9640
9641 /**
9642 * smb2_cancel() - handler for smb2 cancel command
9643 * @work: smb work containing cancel command buffer
9644 *
9645 * Return: 0 on success, otherwise error
9646 */
smb2_cancel(struct ksmbd_work * work)9647 int smb2_cancel(struct ksmbd_work *work)
9648 {
9649 struct ksmbd_conn *conn = work->conn;
9650 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
9651 struct smb2_hdr *chdr;
9652 struct ksmbd_work *iter;
9653 struct ksmbd_work *cancelled_notify = NULL;
9654 struct list_head *command_list;
9655
9656 if (work->next_smb2_rcv_hdr_off)
9657 hdr = ksmbd_resp_buf_next(work);
9658
9659 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
9660 le64_to_cpu(hdr->MessageId),
9661 le32_to_cpu(hdr->Flags));
9662
9663 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
9664 command_list = &conn->async_requests;
9665
9666 spin_lock(&conn->request_lock);
9667 list_for_each_entry(iter, command_list,
9668 async_request_entry) {
9669 chdr = smb_get_msg(iter->request_buf);
9670
9671 if (iter->async_id !=
9672 le64_to_cpu(hdr->Id.AsyncId))
9673 continue;
9674
9675 /*
9676 * Only an ACTIVE deferred work may have its cancel_fn
9677 * fired. A CANCELLED or CLOSED work already took the
9678 * smb2_lock() non-ACTIVE early-exit that frees the
9679 * file_lock and skips release_async_work(), so it is
9680 * still on conn->async_requests with a live cancel_fn
9681 * pointing at the freed file_lock.
9682 */
9683 if (iter->state != KSMBD_WORK_ACTIVE)
9684 break;
9685
9686 ksmbd_debug(SMB,
9687 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
9688 le64_to_cpu(hdr->Id.AsyncId),
9689 le16_to_cpu(chdr->Command));
9690 iter->state = KSMBD_WORK_CANCELLED;
9691 if (iter->cancel_fn == smb2_notify_cancel_fn)
9692 cancelled_notify =
9693 smb2_notify_cancel_claim(iter->cancel_argv);
9694 else if (iter->cancel_fn)
9695 iter->cancel_fn(iter->cancel_argv);
9696 break;
9697 }
9698 spin_unlock(&conn->request_lock);
9699
9700 /*
9701 * Complete a cancelled notify before this CANCEL handler returns.
9702 * Deferring it to the system workqueue lets a following request and
9703 * its response overtake STATUS_CANCELLED, leaving clients waiting
9704 * for the original notify even though the cancellation was accepted.
9705 */
9706 if (cancelled_notify)
9707 smb2_complete_notify_cancel(cancelled_notify);
9708 } else {
9709 command_list = &conn->requests;
9710
9711 spin_lock(&conn->request_lock);
9712 list_for_each_entry(iter, command_list, request_entry) {
9713 chdr = smb_get_msg(iter->request_buf);
9714
9715 if (chdr->MessageId != hdr->MessageId ||
9716 iter == work)
9717 continue;
9718
9719 ksmbd_debug(SMB,
9720 "smb2 with mid %llu cancelled command = 0x%x\n",
9721 le64_to_cpu(hdr->MessageId),
9722 le16_to_cpu(chdr->Command));
9723 iter->state = KSMBD_WORK_CANCELLED;
9724 break;
9725 }
9726 spin_unlock(&conn->request_lock);
9727 }
9728
9729 /* For SMB2_CANCEL command itself send no response*/
9730 work->send_no_response = 1;
9731 return 0;
9732 }
9733
smb_flock_init(struct file * f)9734 struct file_lock *smb_flock_init(struct file *f)
9735 {
9736 struct file_lock *fl;
9737
9738 fl = locks_alloc_lock();
9739 if (!fl)
9740 goto out;
9741
9742 locks_init_lock(fl);
9743
9744 fl->c.flc_owner = f;
9745 fl->c.flc_pid = current->tgid;
9746 fl->c.flc_file = f;
9747 fl->c.flc_flags = FL_POSIX;
9748 fl->fl_ops = NULL;
9749 fl->fl_lmops = NULL;
9750
9751 out:
9752 return fl;
9753 }
9754
smb2_set_flock_flags(struct file_lock * flock,int flags)9755 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
9756 {
9757 int cmd = -EINVAL;
9758
9759 /* Checking for wrong flag combination during lock request*/
9760 switch (flags) {
9761 case SMB2_LOCKFLAG_SHARED:
9762 ksmbd_debug(SMB, "received shared request\n");
9763 cmd = F_SETLKW;
9764 flock->c.flc_type = F_RDLCK;
9765 flock->c.flc_flags |= FL_SLEEP;
9766 break;
9767 case SMB2_LOCKFLAG_EXCLUSIVE:
9768 ksmbd_debug(SMB, "received exclusive request\n");
9769 cmd = F_SETLKW;
9770 flock->c.flc_type = F_WRLCK;
9771 flock->c.flc_flags |= FL_SLEEP;
9772 break;
9773 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
9774 ksmbd_debug(SMB,
9775 "received shared & fail immediately request\n");
9776 cmd = F_SETLK;
9777 flock->c.flc_type = F_RDLCK;
9778 break;
9779 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
9780 ksmbd_debug(SMB,
9781 "received exclusive & fail immediately request\n");
9782 cmd = F_SETLK;
9783 flock->c.flc_type = F_WRLCK;
9784 break;
9785 case SMB2_LOCKFLAG_UNLOCK:
9786 ksmbd_debug(SMB, "received unlock request\n");
9787 flock->c.flc_type = F_UNLCK;
9788 cmd = F_SETLK;
9789 break;
9790 }
9791
9792 return cmd;
9793 }
9794
smb2_lock_init(struct file_lock * flock,unsigned int cmd,int flags,bool zero_len,struct list_head * lock_list)9795 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
9796 unsigned int cmd, int flags, bool zero_len,
9797 struct list_head *lock_list)
9798 {
9799 struct ksmbd_lock *lock;
9800
9801 lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
9802 if (!lock)
9803 return NULL;
9804
9805 lock->cmd = cmd;
9806 lock->fl = flock;
9807 lock->start = flock->fl_start;
9808 lock->end = flock->fl_end;
9809 lock->flags = flags;
9810 lock->zero_len = zero_len;
9811 INIT_LIST_HEAD(&lock->clist);
9812 INIT_LIST_HEAD(&lock->flist);
9813 INIT_LIST_HEAD(&lock->llist);
9814 list_add_tail(&lock->llist, lock_list);
9815
9816 return lock;
9817 }
9818
smb2_remove_blocked_lock(void ** argv)9819 static void smb2_remove_blocked_lock(void **argv)
9820 {
9821 struct file_lock *flock = (struct file_lock *)argv[0];
9822
9823 ksmbd_vfs_posix_lock_unblock(flock);
9824 locks_wake_up(flock);
9825 }
9826
smb2_free_lock(struct file_lock * flock)9827 static void smb2_free_lock(struct file_lock *flock)
9828 {
9829 ksmbd_vfs_posix_lock_unblock(flock);
9830 locks_free_lock(flock);
9831 }
9832
smb2_free_blocked_lock(struct file_lock * flock)9833 static void smb2_free_blocked_lock(struct file_lock *flock)
9834 {
9835 ksmbd_vfs_posix_lock_unblock(flock);
9836 locks_wake_up(flock);
9837 locks_free_lock(flock);
9838 }
9839
lock_defer_pending(struct file_lock * fl)9840 static inline bool lock_defer_pending(struct file_lock *fl)
9841 {
9842 /* check pending lock waiters */
9843 return waitqueue_active(&fl->c.flc_wait);
9844 }
9845
9846 /**
9847 * smb2_lock() - handler for smb2 file lock command
9848 * @work: smb work containing lock command buffer
9849 *
9850 * Return: 0 on success, otherwise error
9851 */
smb2_lock(struct ksmbd_work * work)9852 int smb2_lock(struct ksmbd_work *work)
9853 {
9854 struct smb2_lock_req *req;
9855 struct smb2_lock_rsp *rsp;
9856 struct smb2_lock_element *lock_ele;
9857 struct ksmbd_file *fp = NULL;
9858 struct file_lock *flock = NULL;
9859 struct file *filp = NULL;
9860 int lock_count;
9861 int flags = 0;
9862 int cmd = 0;
9863 int err = -EIO, i, rc = 0;
9864 u64 lock_start, lock_length;
9865 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
9866 struct ksmbd_conn *conn;
9867 int nolock = 0;
9868 LIST_HEAD(lock_list);
9869 LIST_HEAD(rollback_list);
9870 int prior_lock = 0, bkt;
9871 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9872 bool lock_replayed;
9873
9874 WORK_BUFFERS(work, req, rsp);
9875
9876 ksmbd_debug(SMB, "Received smb2 lock request\n");
9877
9878 if (smb2_compound_has_failed(work, &rsp->hdr))
9879 return -EACCES;
9880
9881 if (work->next_smb2_rcv_hdr_off &&
9882 !has_file_id(req->VolatileFileId)) {
9883 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9884 work->compound_fid);
9885 id = work->compound_fid;
9886 pid = work->compound_pfid;
9887 }
9888
9889 if (!has_file_id(id)) {
9890 id = req->VolatileFileId;
9891 pid = req->PersistentFileId;
9892 }
9893
9894 fp = ksmbd_lookup_fd_slow(work, id, pid);
9895 if (!fp) {
9896 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
9897 err = -ENOENT;
9898 goto out2;
9899 }
9900
9901 err = smb2_set_request_open(work, fp, &req->hdr, false, false);
9902 if (err)
9903 goto out2;
9904
9905 lock_replayed = smb2_verify_lock_sequence(work, fp, req);
9906 if (lock_replayed)
9907 goto lock_success;
9908
9909 filp = fp->filp;
9910 lock_count = le16_to_cpu(req->LockCount);
9911 lock_ele = req->locks;
9912
9913 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
9914 /*
9915 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
9916 * as exactly 64 entries so 64 is the intended ceiling. No real workload
9917 * comes close to this in a single request.
9918 */
9919 if (!lock_count || lock_count > 64) {
9920 err = -EINVAL;
9921 goto out2;
9922 }
9923
9924 for (i = 0; i < lock_count; i++) {
9925 flags = le32_to_cpu(lock_ele[i].Flags);
9926
9927 flock = smb_flock_init(filp);
9928 if (!flock)
9929 goto out;
9930
9931 cmd = smb2_set_flock_flags(flock, flags);
9932
9933 lock_start = le64_to_cpu(lock_ele[i].Offset);
9934 lock_length = le64_to_cpu(lock_ele[i].Length);
9935 if (lock_start > OFFSET_MAX ||
9936 (lock_length &&
9937 lock_length - 1 > OFFSET_MAX - lock_start)) {
9938 pr_err("Invalid lock range requested\n");
9939 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
9940 locks_free_lock(flock);
9941 goto out;
9942 }
9943
9944 flock->fl_start = lock_start;
9945 flock->fl_end = lock_length ?
9946 flock->fl_start + lock_length - 1 : flock->fl_start;
9947
9948 /* Check conflict locks in one request */
9949 list_for_each_entry(cmp_lock, &lock_list, llist) {
9950 if (cmp_lock->fl->fl_start <= flock->fl_start &&
9951 cmp_lock->fl->fl_end >= flock->fl_end) {
9952 if (cmp_lock->fl->c.flc_type != F_UNLCK &&
9953 flock->c.flc_type != F_UNLCK) {
9954 pr_err("conflict two locks in one request\n");
9955 err = -EINVAL;
9956 locks_free_lock(flock);
9957 goto out;
9958 }
9959 }
9960 }
9961
9962 smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length,
9963 &lock_list);
9964 if (!smb_lock) {
9965 err = -EINVAL;
9966 locks_free_lock(flock);
9967 goto out;
9968 }
9969 }
9970
9971 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
9972 if (lock_count > 1 &&
9973 !(le32_to_cpu(lock_ele[0].Flags) & SMB2_LOCKFLAG_UNLOCK) &&
9974 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) {
9975 err = -EINVAL;
9976 goto out;
9977 }
9978
9979 if (smb_lock->cmd < 0) {
9980 err = -EINVAL;
9981 goto out;
9982 }
9983
9984 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
9985 err = -EINVAL;
9986 goto out;
9987 }
9988
9989 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
9990 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
9991 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
9992 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
9993 err = -EINVAL;
9994 goto out;
9995 }
9996
9997 prior_lock = smb_lock->flags;
9998
9999 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
10000 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
10001 goto no_check_cl;
10002
10003 nolock = 1;
10004 /* check locks in connection list */
10005 down_read(&conn_list_lock);
10006 hash_for_each(conn_list, bkt, conn, hlist) {
10007 spin_lock(&conn->llist_lock);
10008 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
10009 if (file_inode(cmp_lock->fl->c.flc_file) !=
10010 file_inode(smb_lock->fl->c.flc_file))
10011 continue;
10012
10013 if (lock_is_unlock(smb_lock->fl)) {
10014 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
10015 cmp_lock->start == smb_lock->start &&
10016 cmp_lock->end == smb_lock->end &&
10017 !lock_defer_pending(cmp_lock->fl)) {
10018 nolock = 0;
10019 list_del_init(&cmp_lock->flist);
10020 list_del_init(&cmp_lock->clist);
10021 cmp_lock->conn = NULL;
10022 spin_unlock(&conn->llist_lock);
10023 up_read(&conn_list_lock);
10024
10025 ksmbd_conn_put(conn);
10026 smb2_free_lock(cmp_lock->fl);
10027 kfree(cmp_lock);
10028 goto out_check_cl;
10029 }
10030 continue;
10031 }
10032
10033 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
10034 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
10035 continue;
10036 } else {
10037 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
10038 continue;
10039 }
10040
10041 /* check zero byte lock range */
10042 if (cmp_lock->zero_len && !smb_lock->zero_len &&
10043 cmp_lock->start > smb_lock->start &&
10044 cmp_lock->start <= smb_lock->end) {
10045 spin_unlock(&conn->llist_lock);
10046 up_read(&conn_list_lock);
10047 pr_err("previous lock conflict with zero byte lock range\n");
10048 goto out;
10049 }
10050
10051 if (smb_lock->zero_len && !cmp_lock->zero_len &&
10052 smb_lock->start > cmp_lock->start &&
10053 smb_lock->start <= cmp_lock->end) {
10054 spin_unlock(&conn->llist_lock);
10055 up_read(&conn_list_lock);
10056 pr_err("current lock conflict with zero byte lock range\n");
10057 goto out;
10058 }
10059
10060 if (cmp_lock->start <= smb_lock->end &&
10061 smb_lock->start <= cmp_lock->end &&
10062 !cmp_lock->zero_len && !smb_lock->zero_len) {
10063 spin_unlock(&conn->llist_lock);
10064 up_read(&conn_list_lock);
10065 pr_err("Not allow lock operation on exclusive lock range\n");
10066 goto out;
10067 }
10068 }
10069 spin_unlock(&conn->llist_lock);
10070 }
10071 up_read(&conn_list_lock);
10072 out_check_cl:
10073 if (lock_is_unlock(smb_lock->fl) && nolock) {
10074 pr_err("Try to unlock nolocked range\n");
10075 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10076 goto out;
10077 }
10078
10079 no_check_cl:
10080 flock = smb_lock->fl;
10081 list_del(&smb_lock->llist);
10082
10083 if (smb_lock->zero_len) {
10084 err = 0;
10085 goto skip;
10086 }
10087 retry:
10088 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
10089 skip:
10090 if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
10091 locks_free_lock(flock);
10092 kfree(smb_lock);
10093 if (!rc) {
10094 ksmbd_debug(SMB, "File unlocked\n");
10095 } else if (rc == -ENOENT) {
10096 rsp->hdr.Status = STATUS_NOT_LOCKED;
10097 err = rc;
10098 goto out;
10099 }
10100 } else {
10101 if (rc == FILE_LOCK_DEFERRED) {
10102 void **argv;
10103
10104 ksmbd_debug(SMB,
10105 "would have to wait for getting lock\n");
10106
10107 argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
10108 if (!argv) {
10109 err = -ENOMEM;
10110 smb2_free_blocked_lock(flock);
10111 kfree(smb_lock);
10112 goto out;
10113 }
10114 argv[0] = flock;
10115
10116 rc = setup_async_work(work,
10117 smb2_remove_blocked_lock,
10118 argv);
10119 if (rc) {
10120 kfree(argv);
10121 err = -ENOMEM;
10122 smb2_free_blocked_lock(flock);
10123 kfree(smb_lock);
10124 goto out;
10125 }
10126 list_add(&smb_lock->llist, &rollback_list);
10127 spin_lock(&fp->f_lock);
10128 list_add(&work->fp_entry, &fp->blocked_works);
10129 spin_unlock(&fp->f_lock);
10130
10131 smb2_send_interim_resp(work, STATUS_PENDING);
10132
10133 ksmbd_vfs_posix_lock_wait(flock);
10134
10135 spin_lock(&fp->f_lock);
10136 list_del(&work->fp_entry);
10137 spin_unlock(&fp->f_lock);
10138
10139 list_del(&smb_lock->llist);
10140
10141 if (work->state == KSMBD_WORK_CANCELLED) {
10142 rsp->hdr.Status = STATUS_CANCELLED;
10143 kfree(smb_lock);
10144 smb2_send_interim_resp(work,
10145 STATUS_CANCELLED);
10146 release_async_work(work);
10147 locks_free_lock(flock);
10148 work->send_no_response = 1;
10149 goto out;
10150 }
10151
10152 release_async_work(work);
10153
10154 if (work->state == KSMBD_WORK_ACTIVE)
10155 goto retry;
10156
10157 locks_free_lock(flock);
10158
10159 rsp->hdr.Status =
10160 STATUS_RANGE_NOT_LOCKED;
10161 kfree(smb_lock);
10162 /* rollback_list may still hold earlier grants */
10163 goto out;
10164 } else if (!rc) {
10165 list_add(&smb_lock->llist, &rollback_list);
10166 ksmbd_debug(SMB, "successful in taking lock\n");
10167 } else {
10168 locks_free_lock(flock);
10169 kfree(smb_lock);
10170 err = rc;
10171 goto out;
10172 }
10173 }
10174 }
10175
10176 if (atomic_read(&fp->f_ci->op_count) > 1)
10177 smb_break_all_oplock(work, fp);
10178
10179 lock_success:
10180 rsp->StructureSize = cpu_to_le16(4);
10181 ksmbd_debug(SMB, "successful in taking lock\n");
10182 rsp->hdr.Status = STATUS_SUCCESS;
10183 rsp->Reserved = 0;
10184 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
10185 if (err)
10186 goto out;
10187
10188 /* publish only once the whole batch has committed */
10189 if (!list_empty(&rollback_list)) {
10190 spin_lock(&work->conn->llist_lock);
10191 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
10192 list_del_init(&smb_lock->llist);
10193 smb_lock->conn = ksmbd_conn_get(work->conn);
10194 list_add_tail(&smb_lock->clist,
10195 &work->conn->lock_list);
10196 list_add_tail(&smb_lock->flist,
10197 &fp->lock_list);
10198 }
10199 spin_unlock(&work->conn->llist_lock);
10200 }
10201
10202 if (!lock_replayed)
10203 smb2_update_lock_sequence(work, fp, req);
10204
10205 ksmbd_fd_put(work, fp);
10206 return 0;
10207
10208 out:
10209 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
10210 locks_free_lock(smb_lock->fl);
10211 list_del(&smb_lock->llist);
10212 kfree(smb_lock);
10213 }
10214
10215 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
10216 struct file_lock *rlock = NULL;
10217
10218 rlock = smb_flock_init(filp);
10219 if (rlock) {
10220 rlock->c.flc_type = F_UNLCK;
10221 rlock->fl_start = smb_lock->start;
10222 rlock->fl_end = smb_lock->end;
10223
10224 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
10225 if (rc)
10226 pr_err("rollback unlock fail : %d\n", rc);
10227 } else {
10228 pr_err("rollback unlock alloc failed\n");
10229 }
10230
10231 list_del(&smb_lock->llist);
10232 smb2_free_lock(smb_lock->fl);
10233 if (rlock)
10234 locks_free_lock(rlock);
10235 kfree(smb_lock);
10236 }
10237 out2:
10238 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
10239
10240 if (!rsp->hdr.Status) {
10241 if (err == -EINVAL)
10242 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10243 else if (err == -ENOMEM)
10244 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
10245 else if (err == -ENOENT)
10246 rsp->hdr.Status = STATUS_FILE_CLOSED;
10247 else
10248 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
10249 }
10250
10251 smb2_set_err_rsp(work);
10252 ksmbd_fd_put(work, fp);
10253 return err;
10254 }
10255
fsctl_copychunk(struct ksmbd_work * work,struct copychunk_ioctl_req * ci_req,unsigned int cnt_code,unsigned int input_count,unsigned long long volatile_id,unsigned long long persistent_id,struct smb2_ioctl_rsp * rsp)10256 static int fsctl_copychunk(struct ksmbd_work *work,
10257 struct copychunk_ioctl_req *ci_req,
10258 unsigned int cnt_code,
10259 unsigned int input_count,
10260 unsigned long long volatile_id,
10261 unsigned long long persistent_id,
10262 struct smb2_ioctl_rsp *rsp)
10263 {
10264 struct copychunk_ioctl_rsp *ci_rsp;
10265 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
10266 struct srv_copychunk *chunks;
10267 unsigned int i, chunk_count, chunk_count_written = 0;
10268 unsigned int chunk_size_written = 0;
10269 loff_t total_size_written = 0;
10270 int ret = 0;
10271
10272 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
10273
10274 rsp->VolatileFileId = volatile_id;
10275 rsp->PersistentFileId = persistent_id;
10276 ci_rsp->ChunksWritten =
10277 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
10278 ci_rsp->ChunkBytesWritten =
10279 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
10280 ci_rsp->TotalBytesWritten =
10281 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
10282
10283 chunk_count = le32_to_cpu(ci_req->ChunkCount);
10284 /*
10285 * ChunkCount=0 is the standard SMB2 "query my copy limits" request
10286 * (no data copied) -- but macOS Finder's Cmd+D duplicate sends
10287 * FSCTL_SRV_COPYCHUNK with ChunkCount=0 meaning "copy the whole
10288 * file", relying on the AAPL-negotiated server to do a full copy
10289 * instead. Keep the standard no-op behavior for everyone else.
10290 *
10291 * Gate on the TIME_MACHINE share flag, not just conn->is_aapl:
10292 * that flag alone has ambiguous provenance -- the pre-existing
10293 * narrow UniqueId=0 path can also set it on ordinary,
10294 * non-Time-Machine shares, and this series' stated design keeps
10295 * every AAPL-driven behavior opt-in per share.
10296 */
10297 if (chunk_count == 0 &&
10298 !(work->conn->is_aapl &&
10299 test_share_config_flag(work->tcon->share_conf,
10300 KSMBD_SHARE_FLAG_TIME_MACHINE)))
10301 goto out;
10302 total_size_written = 0;
10303 i = 0;
10304
10305 if (chunk_count) {
10306 /* verify the SRV_COPYCHUNK_COPY packet */
10307 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
10308 input_count < struct_size(ci_req, Chunks, chunk_count)) {
10309 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10310 return -EINVAL;
10311 }
10312
10313 chunks = &ci_req->Chunks[0];
10314 for (i = 0; i < chunk_count; i++) {
10315 if (le32_to_cpu(chunks[i].Length) == 0 ||
10316 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
10317 break;
10318 total_size_written += le32_to_cpu(chunks[i].Length);
10319 }
10320 } else {
10321 chunks = &ci_req->Chunks[0];
10322 }
10323
10324 if (i < chunk_count ||
10325 total_size_written > ksmbd_server_side_copy_max_total_size()) {
10326 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10327 return -EINVAL;
10328 }
10329
10330 src_fp = ksmbd_lookup_foreign_fd(work,
10331 le64_to_cpu(ci_req->SourceKeyU64[0]));
10332 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
10333 ret = -EINVAL;
10334 if (!src_fp ||
10335 src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
10336 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
10337 goto out;
10338 }
10339
10340 if (!dst_fp) {
10341 rsp->hdr.Status = STATUS_FILE_CLOSED;
10342 goto out;
10343 }
10344
10345 /*
10346 * FILE_READ_DATA should only be included in
10347 * the FSCTL_SRV_COPYCHUNK case
10348 */
10349 if (cnt_code == FSCTL_SRV_COPYCHUNK &&
10350 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
10351 rsp->hdr.Status = STATUS_ACCESS_DENIED;
10352 goto out;
10353 }
10354
10355 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
10356 chunks, chunk_count,
10357 &chunk_count_written,
10358 &chunk_size_written,
10359 &total_size_written);
10360 if (ret < 0) {
10361 if (ret == -EACCES)
10362 rsp->hdr.Status = STATUS_ACCESS_DENIED;
10363 else if (ret == -EAGAIN)
10364 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
10365 else if (ret == -EBADF)
10366 rsp->hdr.Status = STATUS_INVALID_HANDLE;
10367 else if (ret == -EFBIG || ret == -ENOSPC)
10368 rsp->hdr.Status = STATUS_DISK_FULL;
10369 else if (ret == -EINVAL)
10370 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10371 else if (ret == -EISDIR)
10372 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
10373 else if (ret == -E2BIG)
10374 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
10375 else
10376 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
10377 }
10378
10379 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
10380 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
10381 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
10382 out:
10383 ksmbd_fd_put(work, src_fp);
10384 ksmbd_fd_put(work, dst_fp);
10385 return ret;
10386 }
10387
idev_ipv4_address(struct in_device * idev)10388 static __be32 idev_ipv4_address(struct in_device *idev)
10389 {
10390 __be32 addr = 0;
10391
10392 struct in_ifaddr *ifa;
10393
10394 rcu_read_lock();
10395 in_dev_for_each_ifa_rcu(ifa, idev) {
10396 if (ifa->ifa_flags & IFA_F_SECONDARY)
10397 continue;
10398
10399 addr = ifa->ifa_address;
10400 break;
10401 }
10402 rcu_read_unlock();
10403 return addr;
10404 }
10405
fsctl_query_iface_info_ioctl(struct ksmbd_conn * conn,struct smb2_ioctl_rsp * rsp,unsigned int out_buf_len)10406 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
10407 struct smb2_ioctl_rsp *rsp,
10408 unsigned int out_buf_len)
10409 {
10410 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
10411 int nbytes = 0;
10412 struct net_device *netdev;
10413 struct sockaddr_storage_rsp *sockaddr_storage;
10414 unsigned int flags;
10415 unsigned long long speed;
10416
10417 rtnl_lock();
10418 for_each_netdev(&init_net, netdev) {
10419 bool ipv4_set = false;
10420
10421 if (netdev->type == ARPHRD_LOOPBACK)
10422 continue;
10423
10424 if (!ksmbd_find_netdev_name_iface_list(netdev->name))
10425 continue;
10426
10427 flags = netif_get_flags(netdev);
10428 if (!(flags & IFF_RUNNING))
10429 continue;
10430 ipv6_retry:
10431 if (out_buf_len <
10432 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
10433 rtnl_unlock();
10434 return -ENOSPC;
10435 }
10436
10437 nii_rsp = (struct network_interface_info_ioctl_rsp *)
10438 &rsp->Buffer[nbytes];
10439 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
10440
10441 nii_rsp->Capability = 0;
10442 if (netdev->real_num_tx_queues > 1)
10443 nii_rsp->Capability |= RSS_CAPABLE;
10444 if (ksmbd_rdma_capable_netdev(netdev))
10445 nii_rsp->Capability |= RDMA_CAPABLE;
10446
10447 nii_rsp->Next = cpu_to_le32(152);
10448 nii_rsp->Reserved = 0;
10449
10450 if (netdev->ethtool_ops->get_link_ksettings) {
10451 struct ethtool_link_ksettings cmd;
10452
10453 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
10454 speed = cmd.base.speed;
10455 } else {
10456 ksmbd_debug(SMB, "%s %s\n", netdev->name,
10457 "speed is unknown, defaulting to 1Gb/sec");
10458 speed = SPEED_1000;
10459 }
10460
10461 speed *= 1000000;
10462 nii_rsp->LinkSpeed = cpu_to_le64(speed);
10463
10464 sockaddr_storage = (struct sockaddr_storage_rsp *)
10465 nii_rsp->SockAddr_Storage;
10466 memset(sockaddr_storage, 0, 128);
10467
10468 if (!ipv4_set) {
10469 struct in_device *idev;
10470
10471 sockaddr_storage->Family = INTERNETWORK;
10472 sockaddr_storage->addr4.Port = 0;
10473
10474 idev = __in_dev_get_rtnl(netdev);
10475 if (!idev)
10476 continue;
10477 sockaddr_storage->addr4.IPv4Address =
10478 idev_ipv4_address(idev);
10479 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
10480 ipv4_set = true;
10481 goto ipv6_retry;
10482 } else {
10483 struct inet6_dev *idev6;
10484 struct inet6_ifaddr *ifa;
10485 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
10486
10487 sockaddr_storage->Family = INTERNETWORKV6;
10488 sockaddr_storage->addr6.Port = 0;
10489 sockaddr_storage->addr6.FlowInfo = 0;
10490
10491 idev6 = __in6_dev_get(netdev);
10492 if (!idev6)
10493 continue;
10494
10495 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
10496 if (ifa->flags & (IFA_F_TENTATIVE |
10497 IFA_F_DEPRECATED))
10498 continue;
10499 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
10500 break;
10501 }
10502 sockaddr_storage->addr6.ScopeId = 0;
10503 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
10504 }
10505 }
10506 rtnl_unlock();
10507
10508 /* zero if this is last one */
10509 if (nii_rsp)
10510 nii_rsp->Next = 0;
10511
10512 rsp->PersistentFileId = SMB2_NO_FID;
10513 rsp->VolatileFileId = SMB2_NO_FID;
10514 return nbytes;
10515 }
10516
fsctl_validate_negotiate_info(struct ksmbd_conn * conn,struct validate_negotiate_info_req * neg_req,struct validate_negotiate_info_rsp * neg_rsp,unsigned int in_buf_len)10517 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
10518 struct validate_negotiate_info_req *neg_req,
10519 struct validate_negotiate_info_rsp *neg_rsp,
10520 unsigned int in_buf_len)
10521 {
10522 int ret = 0;
10523 int dialect;
10524
10525 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
10526 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
10527 return -EINVAL;
10528
10529 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
10530 neg_req->DialectCount);
10531 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
10532 ret = -EINVAL;
10533 goto err_out;
10534 }
10535
10536 if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
10537 ret = -EINVAL;
10538 goto err_out;
10539 }
10540
10541 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
10542 ret = -EINVAL;
10543 goto err_out;
10544 }
10545
10546 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
10547 ret = -EINVAL;
10548 goto err_out;
10549 }
10550
10551 neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
10552 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
10553 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
10554 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
10555 err_out:
10556 return ret;
10557 }
10558
fsctl_query_allocated_ranges(struct ksmbd_work * work,u64 id,struct file_allocated_range_buffer * qar_req,struct file_allocated_range_buffer * qar_rsp,unsigned int in_count,unsigned int * out_count)10559 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
10560 struct file_allocated_range_buffer *qar_req,
10561 struct file_allocated_range_buffer *qar_rsp,
10562 unsigned int in_count, unsigned int *out_count)
10563 {
10564 struct ksmbd_file *fp;
10565 loff_t start, length;
10566 int ret = 0;
10567
10568 *out_count = 0;
10569
10570 start = le64_to_cpu(qar_req->file_offset);
10571 length = le64_to_cpu(qar_req->length);
10572
10573 if (start < 0 || length < 0)
10574 return -EINVAL;
10575
10576 fp = ksmbd_lookup_fd_fast(work, id);
10577 if (!fp)
10578 return -ENOENT;
10579
10580 if (!(fp->daccess & FILE_READ_DATA_LE)) {
10581 ret = -EACCES;
10582 goto out;
10583 }
10584
10585 if (!in_count) {
10586 struct file_allocated_range_buffer range;
10587
10588 ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
10589 &range, 1, out_count);
10590 if ((!ret || ret == -E2BIG) && *out_count)
10591 ret = -ENOSPC;
10592 *out_count = 0;
10593 } else {
10594 ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
10595 qar_rsp, in_count,
10596 out_count);
10597 }
10598 if (ret && ret != -E2BIG)
10599 *out_count = 0;
10600
10601 out:
10602 ksmbd_fd_put(work, fp);
10603 return ret;
10604 }
10605
fsctl_pipe_transceive(struct ksmbd_work * work,u64 id,unsigned int out_buf_len,struct smb2_ioctl_req * req,struct smb2_ioctl_rsp * rsp)10606 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
10607 unsigned int out_buf_len,
10608 struct smb2_ioctl_req *req,
10609 struct smb2_ioctl_rsp *rsp)
10610 {
10611 struct ksmbd_rpc_command *rpc_resp;
10612 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
10613 int nbytes = 0;
10614
10615 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
10616 le32_to_cpu(req->InputCount));
10617 if (rpc_resp) {
10618 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
10619 /*
10620 * set STATUS_SOME_NOT_MAPPED response
10621 * for unknown domain sid.
10622 */
10623 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
10624 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
10625 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
10626 goto out;
10627 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
10628 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10629 goto out;
10630 }
10631
10632 nbytes = rpc_resp->payload_sz;
10633 if (rpc_resp->payload_sz > out_buf_len) {
10634 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
10635 nbytes = out_buf_len;
10636 }
10637
10638 if (!rpc_resp->payload_sz) {
10639 rsp->hdr.Status =
10640 STATUS_UNEXPECTED_IO_ERROR;
10641 goto out;
10642 }
10643
10644 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
10645 }
10646 out:
10647 kvfree(rpc_resp);
10648 return nbytes;
10649 }
10650
fsctl_set_sparse(struct ksmbd_work * work,u64 id,struct file_sparse * sparse)10651 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
10652 struct file_sparse *sparse)
10653 {
10654 struct ksmbd_file *fp;
10655 struct mnt_idmap *idmap;
10656 int ret = 0;
10657 __le32 old_fattr;
10658
10659 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
10660 ksmbd_debug(SMB, "User does not have write permission\n");
10661 return -EACCES;
10662 }
10663
10664 fp = ksmbd_lookup_fd_fast(work, id);
10665 if (!fp)
10666 return -ENOENT;
10667
10668 if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
10669 ret = -EINVAL;
10670 goto out;
10671 }
10672
10673 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE |
10674 FILE_WRITE_ATTRIBUTES_LE))) {
10675 ret = -EACCES;
10676 goto out;
10677 }
10678
10679 idmap = file_mnt_idmap(fp->filp);
10680
10681 old_fattr = fp->f_ci->m_fattr;
10682 if (!sparse->SetSparse &&
10683 (old_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
10684 ret = ksmbd_vfs_zero_holes(fp);
10685 if (ret)
10686 goto out;
10687 }
10688
10689 if (sparse->SetSparse)
10690 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
10691 else
10692 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
10693
10694 if (fp->f_ci->m_fattr != old_fattr) {
10695 const struct cred *saved_cred;
10696 struct xattr_dos_attrib da = {0};
10697
10698 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
10699 fp->filp->f_path.dentry, &da);
10700 if (ret <= 0) {
10701 da.version = 4;
10702 da.itime = fp->itime;
10703 da.create_time = fp->create_time;
10704 da.flags = XATTR_DOSINFO_CREATE_TIME |
10705 XATTR_DOSINFO_ITIME;
10706 }
10707
10708 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
10709 da.flags |= XATTR_DOSINFO_ATTRIB;
10710 saved_cred = override_creds(fp->filp->f_cred);
10711 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
10712 &fp->filp->f_path,
10713 &da, true);
10714 revert_creds(saved_cred);
10715 if (ret)
10716 fp->f_ci->m_fattr = old_fattr;
10717 }
10718
10719 out:
10720 ksmbd_fd_put(work, fp);
10721 return ret;
10722 }
10723
fsctl_request_resume_key(struct ksmbd_work * work,struct smb2_ioctl_req * req,struct resume_key_ioctl_rsp * key_rsp)10724 static int fsctl_request_resume_key(struct ksmbd_work *work,
10725 struct smb2_ioctl_req *req,
10726 struct resume_key_ioctl_rsp *key_rsp)
10727 {
10728 struct ksmbd_file *fp;
10729
10730 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
10731 if (!fp)
10732 return -ENOENT;
10733
10734 memset(key_rsp, 0, sizeof(*key_rsp));
10735 key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
10736 key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
10737 ksmbd_fd_put(work, fp);
10738
10739 return 0;
10740 }
10741
10742 /**
10743 * smb2_ioctl() - handler for smb2 ioctl command
10744 * @work: smb work containing ioctl command buffer
10745 *
10746 * Return: 0 on success, otherwise error
10747 */
smb2_ioctl(struct ksmbd_work * work)10748 int smb2_ioctl(struct ksmbd_work *work)
10749 {
10750 struct smb2_ioctl_req *req;
10751 struct smb2_ioctl_rsp *rsp;
10752 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
10753 u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
10754 struct ksmbd_conn *conn = work->conn;
10755 int ret = 0;
10756 char *buffer;
10757 bool no_fileid_ioctl = false;
10758 bool chseq_err = false;
10759
10760 ksmbd_debug(SMB, "Received smb2 ioctl request\n");
10761
10762 if (work->next_smb2_rcv_hdr_off) {
10763 req = ksmbd_req_buf_next(work);
10764 rsp = ksmbd_resp_buf_next(work);
10765 if (smb2_compound_has_failed(work, &rsp->hdr))
10766 return -EACCES;
10767 if (!has_file_id(req->VolatileFileId)) {
10768 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
10769 work->compound_fid);
10770 id = work->compound_fid;
10771 pid = work->compound_pfid;
10772 }
10773 } else {
10774 req = smb_get_msg(work->request_buf);
10775 rsp = smb_get_msg(work->response_buf);
10776 }
10777
10778 if (!has_file_id(id)) {
10779 id = req->VolatileFileId;
10780 pid = req->PersistentFileId;
10781 }
10782
10783 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
10784 ret = -EOPNOTSUPP;
10785 goto out;
10786 }
10787
10788 buffer = (char *)req + le32_to_cpu(req->InputOffset);
10789
10790 cnt_code = le32_to_cpu(req->CtlCode);
10791 switch (cnt_code) {
10792 case FSCTL_DFS_GET_REFERRALS:
10793 case FSCTL_DFS_GET_REFERRALS_EX:
10794 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
10795 case FSCTL_VALIDATE_NEGOTIATE_INFO:
10796 case FSCTL_PIPE_WAIT:
10797 case FSCTL_PIPE_TRANSCEIVE:
10798 no_fileid_ioctl = true;
10799 break;
10800 default:
10801 break;
10802 }
10803
10804 if (!no_fileid_ioctl && has_file_id(id)) {
10805 struct ksmbd_file *fp;
10806
10807 fp = ksmbd_lookup_fd_slow(work, id, pid);
10808 if (!fp) {
10809 if (cnt_code == FSCTL_DUPLICATE_EXTENTS_TO_FILE) {
10810 rsp->hdr.Status = STATUS_FILE_CLOSED;
10811 goto out2;
10812 }
10813 ret = -ENOENT;
10814 goto out;
10815 }
10816
10817 ret = smb2_set_request_open(work, fp, &req->hdr, true, false);
10818 ksmbd_fd_put(work, fp);
10819 if (ret) {
10820 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
10821 chseq_err = true;
10822 goto out;
10823 }
10824 }
10825
10826 ret = smb2_calc_max_out_buf_len(work,
10827 offsetof(struct smb2_ioctl_rsp, Buffer),
10828 le32_to_cpu(req->MaxOutputResponse));
10829 if (ret < 0) {
10830 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10831 goto out;
10832 }
10833 out_buf_len = (unsigned int)ret;
10834 in_buf_len = le32_to_cpu(req->InputCount);
10835
10836 switch (cnt_code) {
10837 case FSCTL_SRV_ENUM_SNAPS: {
10838 struct srv_snapshot_array *snap_rsp;
10839 struct ksmbd_file *fp;
10840
10841 if (out_buf_len < sizeof(*snap_rsp)) {
10842 ret = -EINVAL;
10843 goto out;
10844 }
10845
10846 fp = ksmbd_lookup_fd_fast(work, id);
10847 if (!fp) {
10848 ret = -ENOENT;
10849 goto out;
10850 }
10851 ksmbd_fd_put(work, fp);
10852
10853 snap_rsp = (struct srv_snapshot_array *)rsp->Buffer;
10854 snap_rsp->NumberOfSnapShots = 0;
10855 snap_rsp->NumberOfSnapShotsReturned = 0;
10856 snap_rsp->SnapShotArraySize = cpu_to_le32(2);
10857 snap_rsp->Reserved = 0;
10858 nbytes = sizeof(*snap_rsp);
10859 break;
10860 }
10861 case FSCTL_DFS_GET_REFERRALS:
10862 case FSCTL_DFS_GET_REFERRALS_EX:
10863 /* Not support DFS yet */
10864 ret = -EOPNOTSUPP;
10865 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
10866 goto out2;
10867 case FSCTL_GET_COMPRESSION: {
10868 struct compress_ioctl *cmpr_rsp;
10869 struct ksmbd_file *fp;
10870 u16 fmt;
10871
10872 if (out_buf_len < sizeof(struct compress_ioctl)) {
10873 ret = -EINVAL;
10874 goto out;
10875 }
10876
10877 fp = ksmbd_lookup_fd_fast(work, id);
10878 if (!fp) {
10879 ret = -ENOENT;
10880 goto out;
10881 }
10882
10883 ret = ksmbd_vfs_get_compression(fp, &fmt);
10884 ksmbd_fd_put(work, fp);
10885 if (ret < 0)
10886 goto out;
10887
10888 cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
10889 cmpr_rsp->CompressionState = cpu_to_le16(fmt);
10890 nbytes = sizeof(struct compress_ioctl);
10891 rsp->PersistentFileId = req->PersistentFileId;
10892 rsp->VolatileFileId = req->VolatileFileId;
10893 break;
10894 }
10895 case FSCTL_SET_COMPRESSION: {
10896 struct compress_ioctl *cmpr_req;
10897 struct ksmbd_file *fp;
10898
10899 if (in_buf_len < sizeof(struct compress_ioctl)) {
10900 ret = -EINVAL;
10901 goto out;
10902 }
10903
10904 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
10905 ksmbd_debug(SMB, "User does not have write permission\n");
10906 ret = -EACCES;
10907 goto out;
10908 }
10909
10910 cmpr_req = (struct compress_ioctl *)buffer;
10911 fp = ksmbd_lookup_fd_fast(work, id);
10912 if (!fp) {
10913 ret = -ENOENT;
10914 goto out;
10915 }
10916
10917 ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
10918 ksmbd_fd_put(work, fp);
10919 if (ret)
10920 goto out;
10921 break;
10922 }
10923 case FSCTL_CREATE_OR_GET_OBJECT_ID:
10924 {
10925 struct file_object_buf_type1_ioctl_rsp *obj_buf;
10926 struct ksmbd_file *fp;
10927
10928 fp = ksmbd_lookup_fd_fast(work, id);
10929 if (!fp) {
10930 ret = -EBADF;
10931 rsp->hdr.Status = STATUS_FILE_CLOSED;
10932 goto out2;
10933 }
10934
10935 if (out_buf_len < sizeof(struct file_object_buf_type1_ioctl_rsp)) {
10936 ksmbd_fd_put(work, fp);
10937 ret = -EINVAL;
10938 goto out;
10939 }
10940 ksmbd_fd_put(work, fp);
10941
10942 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
10943 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
10944 &rsp->Buffer[0];
10945
10946 /*
10947 * TODO: This is dummy implementation to pass smbtorture
10948 * Need to check correct response later
10949 */
10950 memset(obj_buf->ObjectId, 0x0, 16);
10951 memset(obj_buf->BirthVolumeId, 0x0, 16);
10952 memset(obj_buf->BirthObjectId, 0x0, 16);
10953 memset(obj_buf->DomainId, 0x0, 16);
10954
10955 break;
10956 }
10957 case FSCTL_PIPE_TRANSCEIVE:
10958 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
10959 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
10960 break;
10961 case FSCTL_VALIDATE_NEGOTIATE_INFO:
10962 if (conn->dialect < SMB30_PROT_ID) {
10963 ret = -EOPNOTSUPP;
10964 goto out;
10965 }
10966
10967 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
10968 Dialects)) {
10969 ret = -EINVAL;
10970 goto out;
10971 }
10972
10973 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
10974 ret = -EINVAL;
10975 goto out;
10976 }
10977
10978 ret = fsctl_validate_negotiate_info(conn,
10979 (struct validate_negotiate_info_req *)buffer,
10980 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
10981 in_buf_len);
10982 if (ret < 0)
10983 goto out;
10984
10985 nbytes = sizeof(struct validate_negotiate_info_rsp);
10986 rsp->PersistentFileId = SMB2_NO_FID;
10987 rsp->VolatileFileId = SMB2_NO_FID;
10988 break;
10989 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
10990 if (req->PersistentFileId != SMB2_NO_FID ||
10991 req->VolatileFileId != SMB2_NO_FID) {
10992 ret = -EINVAL;
10993 goto out;
10994 }
10995
10996 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
10997 if (ret < 0)
10998 goto out;
10999 nbytes = ret;
11000 break;
11001 case FSCTL_SRV_REQUEST_RESUME_KEY:
11002 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
11003 ret = -EINVAL;
11004 goto out;
11005 }
11006
11007 ret = fsctl_request_resume_key(work, req,
11008 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
11009 if (ret < 0)
11010 goto out;
11011 rsp->PersistentFileId = req->PersistentFileId;
11012 rsp->VolatileFileId = req->VolatileFileId;
11013 nbytes = sizeof(struct resume_key_ioctl_rsp);
11014 break;
11015 case FSCTL_SRV_COPYCHUNK:
11016 case FSCTL_SRV_COPYCHUNK_WRITE:
11017 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11018 ksmbd_debug(SMB,
11019 "User does not have write permission\n");
11020 ret = -EACCES;
11021 goto out;
11022 }
11023
11024 if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) {
11025 ret = -EINVAL;
11026 goto out;
11027 }
11028
11029 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
11030 ret = -EINVAL;
11031 goto out;
11032 }
11033
11034 nbytes = sizeof(struct copychunk_ioctl_rsp);
11035 rsp->VolatileFileId = req->VolatileFileId;
11036 rsp->PersistentFileId = req->PersistentFileId;
11037 fsctl_copychunk(work,
11038 (struct copychunk_ioctl_req *)buffer,
11039 le32_to_cpu(req->CtlCode),
11040 le32_to_cpu(req->InputCount),
11041 req->VolatileFileId,
11042 req->PersistentFileId,
11043 rsp);
11044 break;
11045 case FSCTL_SET_SPARSE:
11046 {
11047 struct file_sparse sparse = {0};
11048
11049 if (in_buf_len && in_buf_len < sizeof(struct file_sparse)) {
11050 ret = -EINVAL;
11051 goto out;
11052 }
11053
11054 *(u8 *)&sparse = 1;
11055 ret = fsctl_set_sparse(work, id, in_buf_len ?
11056 (struct file_sparse *)buffer : &sparse);
11057 if (ret < 0)
11058 goto out;
11059 break;
11060 }
11061 case FSCTL_SET_ZERO_DATA:
11062 {
11063 struct file_zero_data_information *zero_data;
11064 struct ksmbd_file *fp;
11065 loff_t off, len, bfz;
11066
11067 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11068 ksmbd_debug(SMB,
11069 "User does not have write permission\n");
11070 ret = -EACCES;
11071 goto out;
11072 }
11073
11074 if (in_buf_len < sizeof(struct file_zero_data_information)) {
11075 ret = -EINVAL;
11076 goto out;
11077 }
11078
11079 zero_data =
11080 (struct file_zero_data_information *)buffer;
11081
11082 off = le64_to_cpu(zero_data->FileOffset);
11083 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
11084 if (off < 0 || bfz < 0 || off > bfz) {
11085 ret = -EINVAL;
11086 goto out;
11087 }
11088
11089 len = bfz - off;
11090 if (len) {
11091 fp = ksmbd_lookup_fd_fast(work, id);
11092 if (!fp) {
11093 ret = -ENOENT;
11094 goto out;
11095 }
11096
11097 if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
11098 ksmbd_fd_put(work, fp);
11099 ret = -EACCES;
11100 goto out;
11101 }
11102
11103 ret = ksmbd_vfs_zero_data(work, fp, off, len);
11104 ksmbd_fd_put(work, fp);
11105 if (ret == -EAGAIN) {
11106 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
11107 ret = 0;
11108 goto out;
11109 } else if (ret < 0) {
11110 goto out;
11111 }
11112 }
11113 break;
11114 }
11115 case FSCTL_FILE_LEVEL_TRIM:
11116 {
11117 struct file_level_trim *trim_req;
11118 struct file_level_trim_output *trim_rsp;
11119 struct ksmbd_file *fp;
11120 u32 i, num_ranges;
11121
11122 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11123 ksmbd_debug(SMB,
11124 "User does not have write permission\n");
11125 ret = -EACCES;
11126 goto out;
11127 }
11128
11129 if (in_buf_len < offsetof(struct file_level_trim, Ranges)) {
11130 ret = -EINVAL;
11131 goto out;
11132 }
11133
11134 if (out_buf_len < sizeof(struct file_level_trim_output)) {
11135 ret = -EINVAL;
11136 goto out;
11137 }
11138
11139 trim_req = (struct file_level_trim *)buffer;
11140 num_ranges = le32_to_cpu(trim_req->NumRanges);
11141 if (num_ranges >
11142 (in_buf_len - offsetof(struct file_level_trim, Ranges)) /
11143 sizeof(struct file_level_trim_range)) {
11144 ret = -EINVAL;
11145 goto out;
11146 }
11147
11148 fp = ksmbd_lookup_fd_fast(work, id);
11149 if (!fp) {
11150 ret = -ENOENT;
11151 goto out;
11152 }
11153
11154 if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
11155 ksmbd_fd_put(work, fp);
11156 ret = -EACCES;
11157 goto out;
11158 }
11159
11160 trim_rsp = (struct file_level_trim_output *)&rsp->Buffer[0];
11161 trim_rsp->NumRangesProcessed = 0;
11162 for (i = 0; i < num_ranges; i++) {
11163 loff_t off = le64_to_cpu(trim_req->Ranges[i].Offset);
11164 loff_t len = le64_to_cpu(trim_req->Ranges[i].Length);
11165
11166 if (off < 0 || len < 0) {
11167 ret = -EINVAL;
11168 break;
11169 }
11170
11171 if (!len) {
11172 trim_rsp->NumRangesProcessed =
11173 cpu_to_le32(i + 1);
11174 continue;
11175 }
11176
11177 ret = ksmbd_vfs_trim_data(work, fp, off, len);
11178 if (ret)
11179 break;
11180 trim_rsp->NumRangesProcessed = cpu_to_le32(i + 1);
11181 }
11182 ksmbd_fd_put(work, fp);
11183 if (ret == -EAGAIN) {
11184 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
11185 ret = 0;
11186 goto out;
11187 } else if (ret < 0) {
11188 goto out;
11189 }
11190
11191 nbytes = sizeof(struct file_level_trim_output);
11192 break;
11193 }
11194 case FSCTL_QUERY_ALLOCATED_RANGES:
11195 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
11196 ret = -EINVAL;
11197 goto out;
11198 }
11199
11200 ret = fsctl_query_allocated_ranges(work, id,
11201 (struct file_allocated_range_buffer *)buffer,
11202 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
11203 out_buf_len /
11204 sizeof(struct file_allocated_range_buffer), &nbytes);
11205 if (ret == -E2BIG) {
11206 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
11207 } else if (ret < 0) {
11208 nbytes = 0;
11209 goto out;
11210 }
11211
11212 nbytes *= sizeof(struct file_allocated_range_buffer);
11213 break;
11214 case FSCTL_GET_REPARSE_POINT:
11215 {
11216 struct reparse_data_buffer *reparse_ptr;
11217 struct ksmbd_file *fp;
11218
11219 if (out_buf_len < sizeof(struct reparse_data_buffer)) {
11220 ret = -EINVAL;
11221 goto out;
11222 }
11223
11224 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
11225 fp = ksmbd_lookup_fd_fast(work, id);
11226 if (!fp) {
11227 pr_err("not found fp!!\n");
11228 ret = -ENOENT;
11229 goto out;
11230 }
11231
11232 reparse_ptr->ReparseTag =
11233 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
11234 reparse_ptr->ReparseDataLength = 0;
11235 ksmbd_fd_put(work, fp);
11236 nbytes = sizeof(struct reparse_data_buffer);
11237 break;
11238 }
11239 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
11240 {
11241 struct ksmbd_file *fp_in, *fp_out = NULL;
11242 struct duplicate_extents_to_file *dup_ext;
11243 loff_t src_off, dst_off, length, cloned;
11244
11245 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
11246 ret = -EINVAL;
11247 goto out;
11248 }
11249
11250 dup_ext = (struct duplicate_extents_to_file *)buffer;
11251
11252 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
11253 dup_ext->PersistentFileHandle);
11254 if (!fp_in) {
11255 pr_err("not found file handle in duplicate extent to file\n");
11256 ret = -EBADF;
11257 rsp->hdr.Status = STATUS_INVALID_HANDLE;
11258 goto out2;
11259 }
11260
11261 fp_out = ksmbd_lookup_fd_fast(work, id);
11262 if (!fp_out) {
11263 pr_err("not found fp\n");
11264 ret = -EBADF;
11265 rsp->hdr.Status = STATUS_FILE_CLOSED;
11266 ksmbd_fd_put(work, fp_in);
11267 goto out2;
11268 }
11269
11270 if (!test_tree_conn_flag(work->tcon,
11271 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11272 ret = -EACCES;
11273 goto dup_ext_out;
11274 }
11275
11276 if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
11277 ret = -EACCES;
11278 goto dup_ext_out;
11279 }
11280 if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
11281 ret = -EACCES;
11282 goto dup_ext_out;
11283 }
11284
11285 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
11286 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
11287 length = le64_to_cpu(dup_ext->ByteCount);
11288 if (src_off < 0 || dst_off < 0 || length < 0 ||
11289 src_off + length < src_off || dst_off + length < dst_off) {
11290 ret = -EINVAL;
11291 goto dup_ext_out;
11292 }
11293 if (src_off + length > i_size_read(file_inode(fp_in->filp))) {
11294 ret = -EOPNOTSUPP;
11295 goto dup_ext_out;
11296 }
11297 if (dst_off + length > i_size_read(file_inode(fp_out->filp)))
11298 goto dup_ext_out;
11299 if ((fp_in->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE) &&
11300 !(fp_out->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
11301 ret = -EOPNOTSUPP;
11302 goto dup_ext_out;
11303 }
11304 if (file_inode(fp_in->filp) == file_inode(fp_out->filp) &&
11305 dst_off + length > src_off &&
11306 dst_off < src_off + length) {
11307 ret = -EOPNOTSUPP;
11308 goto dup_ext_out;
11309 }
11310
11311 cloned = vfs_clone_file_range(fp_in->filp, src_off,
11312 fp_out->filp, dst_off, length, 0);
11313 if (cloned != length) {
11314 cloned = vfs_copy_file_range(fp_in->filp, src_off,
11315 fp_out->filp, dst_off,
11316 length, 0);
11317 if (cloned != length) {
11318 if (cloned < 0)
11319 ret = cloned;
11320 else
11321 ret = -EINVAL;
11322 }
11323 }
11324
11325 dup_ext_out:
11326 ksmbd_fd_put(work, fp_in);
11327 ksmbd_fd_put(work, fp_out);
11328 if (ret < 0)
11329 goto out;
11330 break;
11331 }
11332 default:
11333 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
11334 cnt_code);
11335 ret = -EOPNOTSUPP;
11336 goto out;
11337 }
11338
11339 rsp->CtlCode = cpu_to_le32(cnt_code);
11340 rsp->InputCount = cpu_to_le32(0);
11341 rsp->InputOffset = cpu_to_le32(112);
11342 rsp->OutputOffset = cpu_to_le32(112);
11343 rsp->OutputCount = cpu_to_le32(nbytes);
11344 rsp->StructureSize = cpu_to_le16(49);
11345 rsp->Reserved = cpu_to_le16(0);
11346 rsp->Flags = cpu_to_le32(0);
11347 rsp->Reserved2 = cpu_to_le32(0);
11348 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
11349 if (!ret)
11350 return ret;
11351
11352 out:
11353 if (ret == -EACCES)
11354 rsp->hdr.Status = STATUS_ACCESS_DENIED;
11355 else if (ret == -ENOENT)
11356 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
11357 else if (ret == -EOPNOTSUPP)
11358 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
11359 else if (ret == -ENOSPC)
11360 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
11361 else if (!chseq_err && (ret < 0 || rsp->hdr.Status == 0))
11362 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11363
11364 out2:
11365 smb2_set_err_rsp(work);
11366 return ret;
11367 }
11368
11369 /**
11370 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
11371 * @work: smb work containing oplock break command buffer
11372 *
11373 * Return: 0
11374 */
smb20_oplock_break_ack(struct ksmbd_work * work)11375 static void smb20_oplock_break_ack(struct ksmbd_work *work)
11376 {
11377 struct smb2_oplock_break *req;
11378 struct smb2_oplock_break *rsp;
11379 struct ksmbd_file *fp;
11380 struct oplock_info *opinfo = NULL;
11381 __le32 status = STATUS_SUCCESS;
11382 int ret;
11383 u64 volatile_id, persistent_id;
11384 char req_oplevel = 0, rsp_oplevel = 0;
11385
11386 WORK_BUFFERS(work, req, rsp);
11387
11388 volatile_id = req->VolatileFid;
11389 persistent_id = req->PersistentFid;
11390 req_oplevel = req->OplockLevel;
11391 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
11392 volatile_id, persistent_id, req_oplevel);
11393
11394 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
11395 if (!fp) {
11396 rsp->hdr.Status = STATUS_FILE_CLOSED;
11397 smb2_set_err_rsp(work);
11398 return;
11399 }
11400
11401 ret = smb2_set_request_open(work, fp, &req->hdr, false, false);
11402 if (ret) {
11403 rsp->hdr.Status = STATUS_FILE_CLOSED;
11404 smb2_set_err_rsp(work);
11405 ksmbd_fd_put(work, fp);
11406 return;
11407 }
11408
11409 opinfo = opinfo_get(fp);
11410 if (!opinfo) {
11411 pr_err("unexpected null oplock_info\n");
11412 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
11413 smb2_set_err_rsp(work);
11414 ksmbd_fd_put(work, fp);
11415 return;
11416 }
11417
11418 if (opinfo->op_state != OPLOCK_ACK_WAIT) {
11419 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
11420 opinfo->op_state);
11421 if (smb3_hdr_replay(&req->hdr) &&
11422 opinfo->op_state == OPLOCK_STATE_NONE) {
11423 rsp->StructureSize = cpu_to_le16(24);
11424 rsp->OplockLevel = opinfo->level;
11425 rsp->Reserved = 0;
11426 rsp->Reserved2 = 0;
11427 rsp->VolatileFid = volatile_id;
11428 rsp->PersistentFid = persistent_id;
11429 ret = ksmbd_iov_pin_rsp(work, rsp,
11430 sizeof(struct smb2_oplock_break));
11431 if (ret)
11432 ksmbd_debug(SMB,
11433 "failed to pin replayed oplock break response: %d\n",
11434 ret);
11435 goto out_no_state_change;
11436 }
11437 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
11438 status = STATUS_INVALID_OPLOCK_PROTOCOL;
11439 else
11440 status = STATUS_INVALID_DEVICE_STATE;
11441 goto err_out;
11442 }
11443
11444 if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
11445 opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11446 status = STATUS_INVALID_PARAMETER;
11447 goto err_out;
11448 }
11449
11450 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
11451 status = STATUS_INVALID_OPLOCK_PROTOCOL;
11452 goto err_out;
11453 }
11454
11455 if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
11456 req_oplevel != SMB2_OPLOCK_LEVEL_II &&
11457 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
11458 opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11459 status = STATUS_INVALID_OPLOCK_PROTOCOL;
11460 goto err_out;
11461 }
11462
11463 if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
11464 req_oplevel != SMB2_OPLOCK_LEVEL_II &&
11465 req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
11466 req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
11467 opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11468 status = STATUS_INVALID_OPLOCK_PROTOCOL;
11469 goto err_out;
11470 }
11471
11472 if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
11473 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
11474 opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11475 status = STATUS_INVALID_OPLOCK_PROTOCOL;
11476 goto err_out;
11477 }
11478
11479 if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
11480 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
11481 else
11482 rsp_oplevel = req_oplevel;
11483
11484 opinfo->level = rsp_oplevel;
11485
11486 rsp->StructureSize = cpu_to_le16(24);
11487 rsp->OplockLevel = rsp_oplevel;
11488 rsp->Reserved = 0;
11489 rsp->Reserved2 = 0;
11490 rsp->VolatileFid = volatile_id;
11491 rsp->PersistentFid = persistent_id;
11492 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
11493 if (ret)
11494 ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
11495 ret);
11496 goto out;
11497
11498 err_out:
11499 rsp->hdr.Status = status;
11500 smb2_set_err_rsp(work);
11501
11502 out:
11503 spin_lock(&opinfo->state_lock);
11504 if (opinfo->op_state != OPLOCK_CLOSING)
11505 opinfo->op_state = OPLOCK_STATE_NONE;
11506 spin_unlock(&opinfo->state_lock);
11507 wake_up_interruptible_all(&opinfo->oplock_q);
11508 out_no_state_change:
11509 opinfo_put(opinfo);
11510 ksmbd_fd_put(work, fp);
11511 }
11512
smb2_lease_state_valid(__le32 state)11513 static bool smb2_lease_state_valid(__le32 state)
11514 {
11515 return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
11516 SMB2_LEASE_HANDLE_CACHING_LE |
11517 SMB2_LEASE_WRITE_CACHING_LE));
11518 }
11519
check_lease_state(struct lease * lease,__le32 req_state)11520 static int check_lease_state(struct lease *lease, __le32 req_state)
11521 {
11522 if (smb2_lease_state_valid(req_state) &&
11523 !(req_state & ~lease->new_state))
11524 return 0;
11525
11526 return 1;
11527 }
11528
11529 /**
11530 * smb21_lease_break_ack() - handler for smb2.1 lease break command
11531 * @work: smb work containing lease break command buffer
11532 *
11533 * Return: 0
11534 */
smb21_lease_break_ack(struct ksmbd_work * work)11535 static void smb21_lease_break_ack(struct ksmbd_work *work)
11536 {
11537 struct ksmbd_conn *conn = work->conn;
11538 struct smb2_lease_ack *req;
11539 struct smb2_lease_ack *rsp;
11540 struct oplock_info *opinfo;
11541 int ret = 0;
11542 __le32 lease_state;
11543 struct lease *lease;
11544
11545 WORK_BUFFERS(work, req, rsp);
11546
11547 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
11548 le32_to_cpu(req->LeaseState));
11549 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
11550 if (!opinfo) {
11551 ksmbd_debug(OPLOCK, "file not opened\n");
11552 smb2_set_err_rsp(work);
11553 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11554 return;
11555 }
11556 lease = opinfo->o_lease;
11557
11558 if (opinfo->op_state == OPLOCK_STATE_NONE) {
11559 pr_err("unexpected lease break state 0x%x\n",
11560 opinfo->op_state);
11561 if (smb3_hdr_replay(&req->hdr))
11562 goto replay_rsp;
11563 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11564 goto err_out;
11565 }
11566
11567 if (!atomic_read(&opinfo->breaking_cnt)) {
11568 if (smb3_hdr_replay(&req->hdr))
11569 goto replay_rsp;
11570 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11571 goto err_out;
11572 }
11573
11574 if (check_lease_state(lease, req->LeaseState)) {
11575 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
11576 ksmbd_debug(OPLOCK,
11577 "req lease state: 0x%x, expected state: 0x%x\n",
11578 req->LeaseState, lease->new_state);
11579 goto err_out;
11580 }
11581
11582 lease_state = req->LeaseState;
11583 lease->state = lease_state;
11584 lease->new_state = SMB2_LEASE_NONE_LE;
11585 lease_update_oplock_levels(lease);
11586
11587 rsp->StructureSize = cpu_to_le16(36);
11588 rsp->Reserved = 0;
11589 rsp->Flags = 0;
11590 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
11591 rsp->LeaseState = lease_state;
11592 rsp->LeaseDuration = 0;
11593 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
11594 if (ret)
11595 goto err_out;
11596
11597 spin_lock(&opinfo->state_lock);
11598 if (opinfo->op_state != OPLOCK_CLOSING)
11599 opinfo->op_state = OPLOCK_STATE_NONE;
11600 spin_unlock(&opinfo->state_lock);
11601 wake_up_interruptible_all(&opinfo->oplock_q);
11602 atomic_dec_if_positive(&opinfo->breaking_cnt);
11603 wake_up_interruptible_all(&opinfo->oplock_brk);
11604 opinfo_put(opinfo);
11605 return;
11606
11607 replay_rsp:
11608 rsp->StructureSize = cpu_to_le16(36);
11609 rsp->Reserved = 0;
11610 rsp->Flags = 0;
11611 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
11612 rsp->LeaseState = lease->state;
11613 rsp->LeaseDuration = 0;
11614 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
11615 if (ret)
11616 goto err_out;
11617 opinfo_put(opinfo);
11618 return;
11619
11620 err_out:
11621 smb2_set_err_rsp(work);
11622 opinfo_put(opinfo);
11623 return;
11624 }
11625
11626 /**
11627 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
11628 * @work: smb work containing oplock/lease break command buffer
11629 *
11630 * Return: 0 on success, otherwise error
11631 */
smb2_oplock_break(struct ksmbd_work * work)11632 int smb2_oplock_break(struct ksmbd_work *work)
11633 {
11634 struct smb2_oplock_break *req;
11635 struct smb2_oplock_break *rsp;
11636
11637 ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
11638
11639 WORK_BUFFERS(work, req, rsp);
11640
11641 switch (le16_to_cpu(req->StructureSize)) {
11642 case OP_BREAK_STRUCT_SIZE_20:
11643 smb20_oplock_break_ack(work);
11644 break;
11645 case OP_BREAK_STRUCT_SIZE_21:
11646 smb21_lease_break_ack(work);
11647 break;
11648 default:
11649 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
11650 le16_to_cpu(req->StructureSize));
11651 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11652 smb2_set_err_rsp(work);
11653 return -EINVAL;
11654 }
11655
11656 return 0;
11657 }
11658
11659 /*
11660 * Cancel handler for a deferred CHANGE_NOTIFY. Races against
11661 * __ksmbd_close_fd()'s notify_pendings drain (vfs_cache.c), which can run
11662 * concurrently on a different connection closing the same handle -- only
11663 * one of the two may claim and free in_work, so both sides check
11664 * list_empty() under fp->f_lock before touching it (list_del_init()
11665 * leaves a node empty, so whichever side removes it first is the owner;
11666 * the loser must not touch in_work again, since the winner may already be
11667 * freeing it).
11668 *
11669 * smb2_cancel() holds conn->request_lock (a spinlock) for the entire
11670 * time it walks conn->async_requests and calls this function -- so this
11671 * runs with preemption disabled and must not sleep or re-acquire that
11672 * same lock. release_async_work() does both (it takes conn->request_lock
11673 * itself, and frees things that can involve sleeping paths), so calling
11674 * it from here would self-deadlock the very thread processing the
11675 * client's CANCEL command. ksmbd_conn_write() can also sleep (it takes
11676 * conn's write mutex). So: do only the non-sleeping, no-relock cleanup
11677 * inline here. smb2_cancel() sends and frees the claimed notify after it
11678 * drops request_lock, preserving response order for a client CANCEL. The
11679 * connection teardown caller has no such post-unlock path, so its wrapper
11680 * defers the send and free to a workqueue.
11681 */
11682 struct notify_cancel_ctx {
11683 struct work_struct work;
11684 struct ksmbd_work *in_work;
11685 };
11686
smb2_send_notify_cancelled(struct ksmbd_work * work)11687 static void smb2_send_notify_cancelled(struct ksmbd_work *work)
11688 {
11689 struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
11690 struct ksmbd_conn *conn = work->conn;
11691 struct ksmbd_session *sess;
11692
11693 sess = ksmbd_session_lookup(conn, le64_to_cpu(hdr->SessionId));
11694 if (sess) {
11695 work->sess = sess;
11696 if (work->encrypted && sess->enc && conn->ops->encrypt_resp) {
11697 conn->ops->encrypt_resp(work);
11698 } else if (conn->ops->is_sign_req && conn->ops->set_sign_rsp &&
11699 conn->ops->is_sign_req(work,
11700 conn->ops->get_cmd_val(work))) {
11701 conn->ops->set_sign_rsp(work);
11702 }
11703 }
11704
11705 ksmbd_conn_write(work);
11706 if (sess) {
11707 ksmbd_user_session_put(sess);
11708 work->sess = NULL;
11709 }
11710 }
11711
smb2_notify_cancel_deferred(struct work_struct * w)11712 static void smb2_notify_cancel_deferred(struct work_struct *w)
11713 {
11714 struct notify_cancel_ctx *ctx =
11715 container_of(w, struct notify_cancel_ctx, work);
11716 struct ksmbd_conn *conn = ctx->in_work->conn;
11717
11718 smb2_complete_notify_cancel(ctx->in_work);
11719 kfree(ctx);
11720 /*
11721 * The connection teardown waits for r_count before destroying
11722 * connection sessions and their proc entries.
11723 */
11724 ksmbd_conn_r_count_dec(conn);
11725 }
11726
smb2_notify_cancel_claim(void ** argv)11727 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv)
11728 {
11729 struct ksmbd_work *in_work = (struct ksmbd_work *)argv[0];
11730 struct ksmbd_file *fp = (struct ksmbd_file *)argv[1];
11731 bool claimed;
11732
11733 spin_lock(&fp->f_lock);
11734 claimed = !list_empty(&in_work->notify_entry);
11735 if (claimed)
11736 list_del_init(&in_work->notify_entry);
11737 spin_unlock(&fp->f_lock);
11738
11739 if (!claimed)
11740 return NULL;
11741
11742 /* conn->request_lock is held by smb2_cancel() or connection teardown. */
11743 in_work->cancel_fn = NULL;
11744 kfree(in_work->cancel_argv);
11745 in_work->cancel_argv = NULL;
11746 return in_work;
11747 }
11748
smb2_complete_notify_cancel(struct ksmbd_work * in_work)11749 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work)
11750 {
11751 struct smb2_hdr *in_hdr = smb_get_msg(in_work->response_buf);
11752
11753 in_hdr->Status = STATUS_CANCELLED;
11754 smb2_send_notify_cancelled(in_work);
11755 release_async_work(in_work);
11756 ksmbd_free_work_struct(in_work);
11757 }
11758
smb2_notify_cancel_fn(void ** argv)11759 static void smb2_notify_cancel_fn(void **argv)
11760 {
11761 struct ksmbd_work *in_work = smb2_notify_cancel_claim(argv);
11762 struct ksmbd_conn *conn;
11763 struct notify_cancel_ctx *ctx;
11764
11765 if (!in_work)
11766 return;
11767 conn = in_work->conn;
11768
11769 ctx = kmalloc(sizeof(*ctx), GFP_ATOMIC);
11770 if (!ctx) {
11771 /* Can't defer the response -- free without sending one. */
11772 list_del_init(&in_work->async_request_entry);
11773 in_work->asynchronous = false;
11774 if (in_work->async_id) {
11775 ksmbd_release_id(&conn->async_ida, in_work->async_id);
11776 in_work->async_id = 0;
11777 }
11778 ksmbd_free_work_struct(in_work);
11779 return;
11780 }
11781 ctx->in_work = in_work;
11782 INIT_WORK(&ctx->work, smb2_notify_cancel_deferred);
11783 /*
11784 * This deferred work can outlive the connection handler's receive loop.
11785 * Keep teardown from destroying the connection's sessions until the
11786 * deferred response has finished using them.
11787 */
11788 ksmbd_conn_r_count_inc(conn);
11789 schedule_work(&ctx->work);
11790 }
11791
11792 /**
11793 * smb2_notify() - handler for smb2 notify request
11794 * @work: smb work containing notify command buffer
11795 *
11796 * Return: 0 on success, otherwise error
11797 */
smb2_notify(struct ksmbd_work * work)11798 int smb2_notify(struct ksmbd_work *work)
11799 {
11800 struct smb2_change_notify_req *req;
11801 struct smb2_change_notify_rsp *rsp;
11802 struct ksmbd_work *in_work;
11803 struct smb2_hdr *in_hdr;
11804 struct ksmbd_file *fp;
11805
11806 ksmbd_debug(SMB, "Received smb2 notify\n");
11807
11808 WORK_BUFFERS(work, req, rsp);
11809
11810 if (smb2_compound_has_failed(work, &rsp->hdr))
11811 return -EACCES;
11812
11813 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
11814 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
11815 smb2_set_err_rsp(work);
11816 return -EIO;
11817 }
11818
11819 /*
11820 * macOS backupd sends CHANGE_NOTIFY with FileId=FFFF...FFFF (share-root
11821 * sentinel) to watch for changes on the share root without holding an
11822 * open handle. Respond STATUS_PENDING + STATUS_NOTIFY_CLEANUP immediately;
11823 * without this, backupd aborts Time Machine setup on STATUS_FILE_CLOSED.
11824 */
11825 if (req->VolatileFileId == SMB2_NO_FID &&
11826 req->PersistentFileId == SMB2_NO_FID) {
11827 in_work = ksmbd_alloc_work_struct();
11828 if (!in_work || allocate_interim_rsp_buf(in_work)) {
11829 if (in_work)
11830 ksmbd_free_work_struct(in_work);
11831 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11832 smb2_set_err_rsp(work);
11833 return 0;
11834 }
11835 if (setup_async_work(work, NULL, NULL)) {
11836 ksmbd_free_work_struct(in_work);
11837 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11838 smb2_set_err_rsp(work);
11839 return 0;
11840 }
11841 smb2_send_interim_resp(work, STATUS_PENDING);
11842 in_work->conn = work->conn;
11843 in_hdr = smb_get_msg(in_work->response_buf);
11844 memcpy(in_hdr, ksmbd_resp_buf_next(work),
11845 __SMB2_HEADER_STRUCTURE_SIZE);
11846 in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
11847 in_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
11848 smb2_set_err_rsp(in_work);
11849 in_hdr->Status = STATUS_NOTIFY_CLEANUP;
11850 in_work->async_id = work->async_id;
11851 work->async_id = 0;
11852 release_async_work(work);
11853 if (smb2_send_interim_work(in_work, work, false))
11854 ksmbd_debug(SMB, "failed to send notify cleanup\n");
11855 ksmbd_free_work_struct(in_work);
11856 work->send_no_response = 1;
11857 return 0;
11858 }
11859
11860 /*
11861 * KSMBD does not implement a real change-notification backend.
11862 * Genuine SMB2 servers (and macOS smbfs) never complete a
11863 * CHANGE_NOTIFY spontaneously: it is satisfied only by a real
11864 * directory change, or with STATUS_NOTIFY_CLEANUP when the watched
11865 * handle is closed. Completing it early (e.g. on a timer) makes
11866 * Finder treat the cleanup as "directory changed" and re-enumerate
11867 * the directory forever, leaving items unopenable. Returning
11868 * STATUS_NOT_IMPLEMENTED here (like stock ksmbd) makes macOS smbfs
11869 * hard-freeze on unmount, so this must stay deferred.
11870 */
11871 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
11872 if (!fp) {
11873 rsp->hdr.Status = STATUS_FILE_CLOSED;
11874 smb2_set_err_rsp(work);
11875 return 0;
11876 }
11877
11878 in_work = ksmbd_alloc_work_struct();
11879 if (!in_work || allocate_interim_rsp_buf(in_work)) {
11880 if (in_work)
11881 ksmbd_free_work_struct(in_work);
11882 ksmbd_fd_put(work, fp);
11883 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11884 smb2_set_err_rsp(work);
11885 return 0;
11886 }
11887 /*
11888 * in_work is synthetic (not from the normal request-receiving
11889 * pipeline), so it has no request_buf of its own. It gets registered
11890 * into conn->async_requests below, and smb2_cancel() unconditionally
11891 * computes smb_get_msg(iter->request_buf) for every entry in that
11892 * list while searching for a match -- give it its own small buffer
11893 * (not an alias of response_buf: ksmbd_free_work_struct() kvfree()s
11894 * both separately, so aliasing them would double-free) so that stays
11895 * a harmless read instead of a near-NULL dereference.
11896 */
11897 in_work->request_buf = kzalloc(MAX_CIFS_SMALL_BUFFER_SIZE, KSMBD_DEFAULT_GFP);
11898 if (!in_work->request_buf) {
11899 ksmbd_free_work_struct(in_work);
11900 ksmbd_fd_put(work, fp);
11901 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11902 smb2_set_err_rsp(work);
11903 return 0;
11904 }
11905 memcpy(smb_get_msg(in_work->request_buf), req,
11906 __SMB2_HEADER_STRUCTURE_SIZE);
11907
11908 if (setup_async_work(work, NULL, NULL)) {
11909 ksmbd_free_work_struct(in_work);
11910 ksmbd_fd_put(work, fp);
11911 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11912 smb2_set_err_rsp(work);
11913 return 0;
11914 }
11915
11916 smb2_send_interim_resp(work, STATUS_PENDING);
11917
11918 /* Keep the async IDA alive until the deferred work is released. */
11919 in_work->conn = ksmbd_conn_get(work->conn);
11920 in_work->owns_conn_ref = true;
11921 in_work->encrypted = work->encrypted;
11922 in_hdr = smb_get_msg(in_work->response_buf);
11923 memcpy(in_hdr, ksmbd_resp_buf_next(work), __SMB2_HEADER_STRUCTURE_SIZE);
11924 in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
11925 in_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
11926 smb2_set_err_rsp(in_work);
11927 in_hdr->Status = STATUS_NOTIFY_CLEANUP;
11928
11929 /*
11930 * Transfer ownership of the async id to in_work; it stays reserved
11931 * until in_work is freed after the deferred response is sent on
11932 * close, so it can't be reused for an unrelated async response.
11933 */
11934 in_work->async_id = work->async_id;
11935 work->async_id = 0;
11936 release_async_work(work);
11937
11938 /*
11939 * work itself is about to be recycled by the normal request-processing
11940 * pipeline, so it can't stay the target of a future CANCEL -- register
11941 * in_work instead, reusing the same async_id, so a client-sent CANCEL
11942 * for this notify actually finds something to cancel instead of
11943 * silently doing nothing until the handle eventually closes.
11944 */
11945 in_work->asynchronous = true;
11946 in_work->cancel_argv = kmalloc_array(2, sizeof(void *), KSMBD_DEFAULT_GFP);
11947 if (in_work->cancel_argv) {
11948 in_work->cancel_argv[0] = in_work;
11949 in_work->cancel_argv[1] = fp;
11950 in_work->cancel_fn = smb2_notify_cancel_fn;
11951 }
11952
11953 if (!ksmbd_conn_link_async_request(work->conn, in_work)) {
11954 kfree(in_work->cancel_argv);
11955 in_work->cancel_argv = NULL;
11956 in_work->cancel_fn = NULL;
11957 in_work->asynchronous = false;
11958 ksmbd_fd_put(work, fp);
11959 if (smb2_send_interim_work(in_work, work, false))
11960 ksmbd_debug(SMB, "failed to send notify cleanup\n");
11961 ksmbd_free_work_struct(in_work);
11962 work->send_no_response = 1;
11963 return 0;
11964 }
11965
11966 spin_lock(&fp->f_lock);
11967 list_add_tail(&in_work->notify_entry, &fp->notify_pendings);
11968 spin_unlock(&fp->f_lock);
11969
11970 ksmbd_fd_put(work, fp);
11971 work->send_no_response = 1;
11972 return 0;
11973 }
11974
11975 /**
11976 * smb2_is_sign_req() - handler for checking packet signing status
11977 * @work: smb work containing notify command buffer
11978 * @command: SMB2 command id
11979 *
11980 * Return: true if packed is signed, false otherwise
11981 */
smb2_is_sign_req(struct ksmbd_work * work,unsigned int command)11982 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
11983 {
11984 struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
11985
11986 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
11987 command != SMB2_NEGOTIATE_HE)
11988 return true;
11989
11990 return false;
11991 }
11992
11993 /**
11994 * smb2_check_sign_req() - handler for req packet sign processing
11995 * @work: smb work containing notify command buffer
11996 *
11997 * Return: 1 on success, 0 otherwise
11998 */
smb2_check_sign_req(struct ksmbd_work * work)11999 int smb2_check_sign_req(struct ksmbd_work *work)
12000 {
12001 struct smb2_hdr *hdr;
12002 char signature_req[SMB2_SIGNATURE_SIZE];
12003 char signature[SMB2_HMACSHA256_SIZE];
12004 struct kvec iov[1];
12005 size_t len;
12006
12007 hdr = smb_get_msg(work->request_buf);
12008 if (work->next_smb2_rcv_hdr_off)
12009 hdr = ksmbd_req_buf_next(work);
12010
12011 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12012 len = get_rfc1002_len(work->request_buf);
12013 else if (hdr->NextCommand)
12014 len = le32_to_cpu(hdr->NextCommand);
12015 else
12016 len = get_rfc1002_len(work->request_buf) -
12017 work->next_smb2_rcv_hdr_off;
12018
12019 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12020 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12021
12022 iov[0].iov_base = (char *)&hdr->ProtocolId;
12023 iov[0].iov_len = len;
12024
12025 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
12026 signature);
12027
12028 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12029 pr_err("bad smb2 signature\n");
12030 return 0;
12031 }
12032
12033 return 1;
12034 }
12035
12036 /**
12037 * smb2_get_sign_rsp_iov() - get the iovecs used to sign a response
12038 * @work: work that has the response iovecs
12039 * @hdr: SMB2 header of the response
12040 * @n_vec: set to the number of iovecs to sign
12041 *
12042 * Response data may be in another buffer. In this case, the response uses
12043 * more than one iovec. Find the iovec that starts with @hdr. Sign this
12044 * iovec and all iovecs after it.
12045 *
12046 * Return: The first iovec to sign.
12047 */
smb2_get_sign_rsp_iov(struct ksmbd_work * work,struct smb2_hdr * hdr,int * n_vec)12048 static struct kvec *smb2_get_sign_rsp_iov(struct ksmbd_work *work,
12049 struct smb2_hdr *hdr, int *n_vec)
12050 {
12051 int i;
12052
12053 /*
12054 * iov[0] has the RFC1002 message length. It is not part of the SMB2
12055 * message, so do not sign it.
12056 */
12057 for (i = 1; i <= work->iov_idx; i++) {
12058 if (work->iov[i].iov_base == hdr) {
12059 *n_vec = work->iov_idx - i + 1;
12060 return &work->iov[i];
12061 }
12062 }
12063
12064 WARN_ON_ONCE(1);
12065 *n_vec = 1;
12066 return &work->iov[work->iov_idx];
12067 }
12068
12069 /**
12070 * smb2_set_sign_rsp() - handler for rsp packet sign processing
12071 * @work: smb work containing notify command buffer
12072 *
12073 */
smb2_set_sign_rsp(struct ksmbd_work * work)12074 void smb2_set_sign_rsp(struct ksmbd_work *work)
12075 {
12076 struct smb2_hdr *hdr;
12077 char signature[SMB2_HMACSHA256_SIZE];
12078 struct kvec *iov;
12079 int n_vec;
12080
12081 hdr = ksmbd_resp_buf_curr(work);
12082 hdr->Flags |= SMB2_FLAGS_SIGNED;
12083 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12084
12085 iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12086
12087 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
12088 signature);
12089 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12090 }
12091
12092 /**
12093 * smb3_check_sign_req() - handler for req packet sign processing
12094 * @work: smb work containing notify command buffer
12095 *
12096 * Return: 1 on success, 0 otherwise
12097 */
smb3_check_sign_req(struct ksmbd_work * work)12098 int smb3_check_sign_req(struct ksmbd_work *work)
12099 {
12100 struct ksmbd_conn *conn = work->conn;
12101 char *signing_key;
12102 struct smb2_hdr *hdr;
12103 struct channel *chann;
12104 char signature_req[SMB2_SIGNATURE_SIZE];
12105 char signature[SMB2_CMACAES_SIZE];
12106 struct kvec iov[1];
12107 size_t len;
12108
12109 hdr = smb_get_msg(work->request_buf);
12110 if (work->next_smb2_rcv_hdr_off)
12111 hdr = ksmbd_req_buf_next(work);
12112
12113 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12114 len = get_rfc1002_len(work->request_buf);
12115 else if (hdr->NextCommand)
12116 len = le32_to_cpu(hdr->NextCommand);
12117 else
12118 len = get_rfc1002_len(work->request_buf) -
12119 work->next_smb2_rcv_hdr_off;
12120
12121 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
12122 signing_key = work->sess->smb3signingkey;
12123 } else {
12124 chann = lookup_chann_list(work->sess, conn);
12125 if (!chann) {
12126 if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
12127 !(hdr->Flags & SMB2_FLAGS_SIGNED))
12128 return 0;
12129 signing_key = work->sess->smb3signingkey;
12130 } else {
12131 signing_key = chann->smb3signingkey;
12132 }
12133 }
12134
12135 if (!signing_key) {
12136 pr_err("SMB3 signing key is not generated\n");
12137 return 0;
12138 }
12139
12140 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12141 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12142 iov[0].iov_base = (char *)&hdr->ProtocolId;
12143 iov[0].iov_len = len;
12144
12145 ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);
12146
12147 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12148 pr_err("bad smb2 signature\n");
12149 return 0;
12150 }
12151
12152 return 1;
12153 }
12154
12155 /**
12156 * smb3_set_sign_rsp() - handler for rsp packet sign processing
12157 * @work: smb work containing notify command buffer
12158 *
12159 */
smb3_set_sign_rsp(struct ksmbd_work * work)12160 void smb3_set_sign_rsp(struct ksmbd_work *work)
12161 {
12162 struct ksmbd_conn *conn = work->conn;
12163 struct smb2_hdr *hdr;
12164 struct channel *chann;
12165 char signature[SMB2_CMACAES_SIZE];
12166 struct kvec *iov;
12167 u16 command = conn->ops->get_cmd_val(work);
12168 int n_vec;
12169 char *signing_key;
12170
12171 hdr = ksmbd_resp_buf_curr(work);
12172
12173 if (command == SMB2_SESSION_SETUP_HE &&
12174 (!conn->binding || hdr->Status != STATUS_SUCCESS)) {
12175 signing_key = work->sess->smb3signingkey;
12176 } else {
12177 chann = lookup_chann_list(work->sess, work->conn);
12178 if (!chann) {
12179 return;
12180 }
12181 signing_key = chann->smb3signingkey;
12182 }
12183
12184 if (!signing_key)
12185 return;
12186
12187 hdr->Flags |= SMB2_FLAGS_SIGNED;
12188 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12189
12190 iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12191
12192 ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
12193 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12194 }
12195
12196 /**
12197 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
12198 * @work: smb work containing response buffer
12199 *
12200 */
smb3_preauth_hash_rsp(struct ksmbd_work * work)12201 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
12202 {
12203 struct ksmbd_conn *conn = work->conn;
12204 struct ksmbd_session *sess = work->sess;
12205 struct smb2_hdr *req, *rsp;
12206
12207 if (conn->dialect != SMB311_PROT_ID)
12208 return;
12209
12210 WORK_BUFFERS(work, req, rsp);
12211
12212 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
12213 ksmbd_conn_lock(conn);
12214 if (conn->preauth_info)
12215 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
12216 conn->preauth_info->Preauth_HashValue);
12217 ksmbd_conn_unlock(conn);
12218 }
12219
12220 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
12221 ksmbd_conn_lock(conn);
12222
12223 if (conn->binding) {
12224 struct preauth_session *preauth_sess;
12225
12226 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
12227 if (preauth_sess)
12228 ksmbd_gen_preauth_integrity_hash(conn,
12229 work->response_buf,
12230 preauth_sess->Preauth_HashValue);
12231 } else if (sess->Preauth_HashValue) {
12232 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
12233 sess->Preauth_HashValue);
12234 }
12235 ksmbd_conn_unlock(conn);
12236 }
12237 }
12238
fill_transform_hdr(void * tr_buf,char * old_buf,__le16 cipher_type)12239 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
12240 {
12241 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
12242 struct smb2_hdr *hdr = smb_get_msg(old_buf);
12243 unsigned int orig_len = get_rfc1002_len(old_buf);
12244
12245 /* tr_buf must be cleared by the caller */
12246 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
12247 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
12248 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
12249 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
12250 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
12251 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
12252 else
12253 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
12254 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
12255 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
12256 inc_rfc1001_len(tr_buf, orig_len);
12257 }
12258
smb3_encrypt_resp(struct ksmbd_work * work)12259 int smb3_encrypt_resp(struct ksmbd_work *work)
12260 {
12261 struct kvec *iov = work->iov;
12262 int rc = -ENOMEM;
12263 void *tr_buf;
12264
12265 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
12266 if (!tr_buf)
12267 return rc;
12268
12269 /* fill transform header */
12270 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
12271
12272 iov[0].iov_base = tr_buf;
12273 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
12274 work->tr_buf = tr_buf;
12275
12276 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
12277 }
12278
smb3_is_transform_hdr(void * buf)12279 bool smb3_is_transform_hdr(void *buf)
12280 {
12281 struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
12282
12283 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
12284 }
12285
smb3_decrypt_req(struct ksmbd_work * work)12286 int smb3_decrypt_req(struct ksmbd_work *work)
12287 {
12288 char *buf = work->request_buf;
12289 unsigned int pdu_length = get_rfc1002_len(buf);
12290 struct kvec iov[2];
12291 unsigned int buf_data_size;
12292 struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
12293 unsigned int original_msg_size;
12294 int rc = 0;
12295
12296 if (pdu_length < sizeof(struct smb2_transform_hdr)) {
12297 pr_err("Transform message is too small (%u)\n",
12298 pdu_length);
12299 return -ECONNABORTED;
12300 }
12301
12302 buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
12303 original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
12304 if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
12305 original_msg_size < sizeof(struct smb2_compression_hdr)) {
12306 pr_err("Transform message is too small (%u)\n",
12307 pdu_length);
12308 return -ECONNABORTED;
12309 }
12310
12311 if (buf_data_size < original_msg_size) {
12312 pr_err("Transform message is broken\n");
12313 return -ECONNABORTED;
12314 }
12315
12316 iov[0].iov_base = buf;
12317 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
12318 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
12319 iov[1].iov_len = buf_data_size;
12320 rc = ksmbd_crypt_message(work, iov, 2, 0);
12321 if (rc)
12322 return rc;
12323
12324 /* Drop the AEAD authentication tag from the inner RFC1002 frame. */
12325 memmove(buf + 4, iov[1].iov_base, original_msg_size);
12326 *(__be32 *)buf = cpu_to_be32(original_msg_size);
12327
12328 return rc;
12329 }
12330
smb3_11_final_sess_setup_resp(struct ksmbd_work * work)12331 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
12332 {
12333 struct ksmbd_conn *conn = work->conn;
12334 struct ksmbd_session *sess = work->sess;
12335 struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
12336
12337 if (conn->dialect < SMB30_PROT_ID)
12338 return false;
12339
12340 if (work->next_smb2_rcv_hdr_off)
12341 rsp = ksmbd_resp_buf_next(work);
12342
12343 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
12344 sess->user && !user_guest(sess->user) &&
12345 rsp->Status == STATUS_SUCCESS)
12346 return true;
12347 return false;
12348 }
12349