Debian Codegraph @

fs/smb/server/smb2pdu.c

raw
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2016 Namjae Jeon <[email protected]>
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/statfs.h>
13 #include <linux/ethtool.h>
14 #include <linux/falloc.h>
15 #include <linux/mount.h>
16 #include <linux/filelock.h>
17
18 #include "glob.h"
19 #include "smbfsctl.h"
20 #include "oplock.h"
21 #include "smbacl.h"
22
23 #include "auth.h"
24 #include "asn1.h"
25 #include "connection.h"
26 #include "transport_ipc.h"
27 #include "../common/smbdirect/smbdirect.h"
28 #include "transport_rdma.h"
29 #include "vfs.h"
30 #include "vfs_cache.h"
31 #include "misc.h"
32
33 #include "server.h"
34 #include "smb_common.h"
35 #include "../common/smb2status.h"
36 #include "ksmbd_work.h"
37 #include "mgmt/user_config.h"
38 #include "mgmt/share_config.h"
39 #include "mgmt/tree_connect.h"
40 #include "mgmt/user_session.h"
41 #include "mgmt/ksmbd_ida.h"
42 #include "ndr.h"
43 #include "stats.h"
44 #include "transport_tcp.h"
45
46 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
47 {
48 if (work->next_smb2_rcv_hdr_off) {
49 *req = ksmbd_req_buf_next(work);
50 *rsp = ksmbd_resp_buf_next(work);
51 } else {
52 *req = smb_get_msg(work->request_buf);
53 *rsp = smb_get_msg(work->response_buf);
54 }
55 }
56
57 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
58
59 /**
60 * check_session_id() - check for valid session id in smb header
61 * @conn: connection instance
62 * @id: session id from smb header
63 *
64 * Return: 1 if valid session id, otherwise 0
65 */
66 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
67 {
68 struct ksmbd_session *sess;
69
70 if (id == 0 || id == -1)
71 return false;
72
73 sess = ksmbd_session_lookup_all(conn, id);
74 if (sess) {
75 ksmbd_user_session_put(sess);
76 return true;
77 }
78 pr_err("Invalid user session id: %llu\n", id);
79 return false;
80 }
81
82 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
83 {
84 struct channel *chann;
85
86 down_read(&sess->chann_lock);
87 chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
88 up_read(&sess->chann_lock);
89
90 return chann;
91 }
92
93 /**
94 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
95 * @work: smb work
96 *
97 * Return: 0 if there is a tree connection matched or these are
98 * skipable commands, otherwise error
99 */
100 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
101 {
102 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
103 unsigned int cmd = le16_to_cpu(req_hdr->Command);
104 unsigned int tree_id;
105
106 if (cmd == SMB2_TREE_CONNECT_HE ||
107 cmd == SMB2_CANCEL_HE ||
108 cmd == SMB2_LOGOFF_HE) {
109 ksmbd_debug(SMB, "skip to check tree connect request\n");
110 return 0;
111 }
112
113 if (xa_empty(&work->sess->tree_conns)) {
114 ksmbd_debug(SMB, "NO tree connected\n");
115 return -ENOENT;
116 }
117
118 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
119
120 /*
121 * If request is not the first in Compound request,
122 * Just validate tree id in header with work->tcon->id.
123 */
124 if (work->next_smb2_rcv_hdr_off) {
125 if (!work->tcon) {
126 pr_err("The first operation in the compound does not have tcon\n");
127 return -EINVAL;
128 }
129 if (work->tcon->t_state != TREE_CONNECTED)
130 return -ENOENT;
131 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
132 pr_err("tree id(%u) is different with id(%u) in first operation\n",
133 tree_id, work->tcon->id);
134 return -EINVAL;
135 }
136 return 1;
137 }
138
139 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
140 if (!work->tcon) {
141 pr_err("Invalid tid %d\n", tree_id);
142 return -ENOENT;
143 }
144
145 return 1;
146 }
147
148 /**
149 * smb2_set_err_rsp() - set error response code on smb response
150 * @work: smb work containing response buffer
151 */
152 void smb2_set_err_rsp(struct ksmbd_work *work)
153 {
154 struct smb2_err_rsp *err_rsp;
155
156 if (work->next_smb2_rcv_hdr_off)
157 err_rsp = ksmbd_resp_buf_next(work);
158 else
159 err_rsp = smb_get_msg(work->response_buf);
160
161 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
162 int err;
163
164 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
165 err_rsp->ErrorContextCount = 0;
166 err_rsp->Reserved = 0;
167 err_rsp->ByteCount = 0;
168 err_rsp->ErrorData[0] = 0;
169 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
170 __SMB2_HEADER_STRUCTURE_SIZE +
171 SMB2_ERROR_STRUCTURE_SIZE2);
172 if (err)
173 work->send_no_response = 1;
174 }
175 }
176
177 /**
178 * is_smb2_neg_cmd() - is it smb2 negotiation command
179 * @work: smb work containing smb header
180 *
181 * Return: true if smb2 negotiation command, otherwise false
182 */
183 bool is_smb2_neg_cmd(struct ksmbd_work *work)
184 {
185 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
186
187 /* is it SMB2 header ? */
188 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
189 return false;
190
191 /* make sure it is request not response message */
192 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
193 return false;
194
195 if (hdr->Command != SMB2_NEGOTIATE)
196 return false;
197
198 return true;
199 }
200
201 /**
202 * is_smb2_rsp() - is it smb2 response
203 * @work: smb work containing smb response buffer
204 *
205 * Return: true if smb2 response, otherwise false
206 */
207 bool is_smb2_rsp(struct ksmbd_work *work)
208 {
209 struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
210
211 /* is it SMB2 header ? */
212 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
213 return false;
214
215 /* make sure it is response not request message */
216 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
217 return false;
218
219 return true;
220 }
221
222 /**
223 * get_smb2_cmd_val() - get smb command code from smb header
224 * @work: smb work containing smb request buffer
225 *
226 * Return: smb2 request command value
227 */
228 u16 get_smb2_cmd_val(struct ksmbd_work *work)
229 {
230 struct smb2_hdr *rcv_hdr;
231
232 if (work->next_smb2_rcv_hdr_off)
233 rcv_hdr = ksmbd_req_buf_next(work);
234 else
235 rcv_hdr = smb_get_msg(work->request_buf);
236 return le16_to_cpu(rcv_hdr->Command);
237 }
238
239 /**
240 * set_smb2_rsp_status() - set error response code on smb2 header
241 * @work: smb work containing response buffer
242 * @err: error response code
243 */
244 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
245 {
246 struct smb2_hdr *rsp_hdr;
247
248 rsp_hdr = smb_get_msg(work->response_buf);
249 rsp_hdr->Status = err;
250
251 work->iov_idx = 0;
252 work->iov_cnt = 0;
253 work->next_smb2_rcv_hdr_off = 0;
254 smb2_set_err_rsp(work);
255 }
256
257 /**
258 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
259 * @work: smb work containing smb request buffer
260 *
261 * smb2 negotiate response is sent in reply of smb1 negotiate command for
262 * dialect auto-negotiation.
263 */
264 int init_smb2_neg_rsp(struct ksmbd_work *work)
265 {
266 struct smb2_hdr *rsp_hdr;
267 struct smb2_negotiate_rsp *rsp;
268 struct ksmbd_conn *conn = work->conn;
269 int err;
270
271 rsp_hdr = smb_get_msg(work->response_buf);
272 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
273 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
274 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
275 rsp_hdr->CreditRequest = cpu_to_le16(2);
276 rsp_hdr->Command = SMB2_NEGOTIATE;
277 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
278 rsp_hdr->NextCommand = 0;
279 rsp_hdr->MessageId = 0;
280 rsp_hdr->Id.SyncId.ProcessId = 0;
281 rsp_hdr->Id.SyncId.TreeId = 0;
282 rsp_hdr->SessionId = 0;
283 memset(rsp_hdr->Signature, 0, 16);
284
285 rsp = smb_get_msg(work->response_buf);
286
287 WARN_ON(ksmbd_conn_good(conn));
288
289 rsp->StructureSize = cpu_to_le16(65);
290 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
291 rsp->DialectRevision = cpu_to_le16(conn->dialect);
292 /* Not setting conn guid rsp->ServerGUID, as it
293 * not used by client for identifying connection
294 */
295 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
296 /* Default Max Message Size till SMB2.0, 64K*/
297 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
298 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
299 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
300
301 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
302 rsp->ServerStartTime = 0;
303
304 rsp->SecurityBufferOffset = cpu_to_le16(128);
305 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
306 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
307 le16_to_cpu(rsp->SecurityBufferOffset));
308 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
309 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
310 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
311 err = ksmbd_iov_pin_rsp(work, rsp,
312 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
313 if (err)
314 return err;
315 conn->use_spnego = true;
316
317 ksmbd_conn_set_need_negotiate(conn);
318 return 0;
319 }
320
321 /**
322 * smb2_set_rsp_credits() - set number of credits in response buffer
323 * @work: smb work containing smb response buffer
324 */
325 int smb2_set_rsp_credits(struct ksmbd_work *work)
326 {
327 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
328 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
329 struct ksmbd_conn *conn = work->conn;
330 unsigned short credits_requested, aux_max;
331 unsigned short credit_charge, credits_granted = 0;
332
333 if (work->send_no_response)
334 return 0;
335
336 hdr->CreditCharge = req_hdr->CreditCharge;
337
338 if (conn->total_credits > conn->vals->max_credits) {
339 hdr->CreditRequest = 0;
340 pr_err("Total credits overflow: %d\n", conn->total_credits);
341 return -EINVAL;
342 }
343
344 credit_charge = max_t(unsigned short,
345 le16_to_cpu(req_hdr->CreditCharge), 1);
346 if (credit_charge > conn->total_credits) {
347 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
348 credit_charge, conn->total_credits);
349 return -EINVAL;
350 }
351
352 conn->total_credits -= credit_charge;
353 conn->outstanding_credits -= credit_charge;
354 credits_requested = max_t(unsigned short,
355 le16_to_cpu(req_hdr->CreditRequest), 1);
356
357 /* according to smb2.credits smbtorture, Windows server
358 * 2016 or later grant up to 8192 credits at once.
359 *
360 * TODO: Need to adjuct CreditRequest value according to
361 * current cpu load
362 */
363 if (hdr->Command == SMB2_NEGOTIATE)
364 aux_max = 1;
365 else
366 aux_max = conn->vals->max_credits - conn->total_credits;
367 credits_granted = min_t(unsigned short, credits_requested, aux_max);
368
369 conn->total_credits += credits_granted;
370 work->credits_granted += credits_granted;
371
372 if (!req_hdr->NextCommand) {
373 /* Update CreditRequest in last request */
374 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
375 }
376 ksmbd_debug(SMB,
377 "credits: requested[%d] granted[%d] total_granted[%d]\n",
378 credits_requested, credits_granted,
379 conn->total_credits);
380 return 0;
381 }
382
383 /**
384 * init_chained_smb2_rsp() - initialize smb2 chained response
385 * @work: smb work containing smb response buffer
386 */
387 static void init_chained_smb2_rsp(struct ksmbd_work *work)
388 {
389 struct smb2_hdr *req = ksmbd_req_buf_next(work);
390 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
391 struct smb2_hdr *rsp_hdr;
392 struct smb2_hdr *rcv_hdr;
393 int next_hdr_offset = 0;
394 int len, new_len;
395
396 /* Len of this response = updated RFC len - offset of previous cmd
397 * in the compound rsp
398 */
399
400 /* Storing the current local FID which may be needed by subsequent
401 * command in the compound request
402 */
403 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
404 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
405 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
406 work->compound_sid = le64_to_cpu(rsp->SessionId);
407 }
408
409 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
410 next_hdr_offset = le32_to_cpu(req->NextCommand);
411
412 new_len = ALIGN(len, 8);
413 work->iov[work->iov_idx].iov_len += (new_len - len);
414 inc_rfc1001_len(work->response_buf, new_len - len);
415 rsp->NextCommand = cpu_to_le32(new_len);
416
417 work->next_smb2_rcv_hdr_off += next_hdr_offset;
418 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
419 work->next_smb2_rsp_hdr_off += new_len;
420 ksmbd_debug(SMB,
421 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
422 new_len, work->next_smb2_rcv_hdr_off,
423 work->next_smb2_rsp_hdr_off);
424
425 rsp_hdr = ksmbd_resp_buf_next(work);
426 rcv_hdr = ksmbd_req_buf_next(work);
427
428 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
429 ksmbd_debug(SMB, "related flag should be set\n");
430 work->compound_fid = KSMBD_NO_FID;
431 work->compound_pfid = KSMBD_NO_FID;
432 }
433 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
434 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
435 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
436 rsp_hdr->Command = rcv_hdr->Command;
437
438 /*
439 * Message is response. We don't grant oplock yet.
440 */
441 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
442 SMB2_FLAGS_RELATED_OPERATIONS);
443 rsp_hdr->NextCommand = 0;
444 rsp_hdr->MessageId = rcv_hdr->MessageId;
445 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
446 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
447 rsp_hdr->SessionId = rcv_hdr->SessionId;
448 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
449 }
450
451 /**
452 * is_chained_smb2_message() - check for chained command
453 * @work: smb work containing smb request buffer
454 *
455 * Return: true if chained request, otherwise false
456 */
457 bool is_chained_smb2_message(struct ksmbd_work *work)
458 {
459 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
460 unsigned int len, next_cmd;
461
462 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
463 return false;
464
465 hdr = ksmbd_req_buf_next(work);
466 next_cmd = le32_to_cpu(hdr->NextCommand);
467 if (next_cmd > 0) {
468 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
469 __SMB2_HEADER_STRUCTURE_SIZE >
470 get_rfc1002_len(work->request_buf)) {
471 pr_err("next command(%u) offset exceeds smb msg size\n",
472 next_cmd);
473 return false;
474 }
475
476 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
477 work->response_sz) {
478 pr_err("next response offset exceeds response buffer size\n");
479 return false;
480 }
481
482 ksmbd_debug(SMB, "got SMB2 chained command\n");
483 init_chained_smb2_rsp(work);
484 return true;
485 } else if (work->next_smb2_rcv_hdr_off) {
486 /*
487 * This is last request in chained command,
488 * align response to 8 byte
489 */
490 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
491 len = len - get_rfc1002_len(work->response_buf);
492 if (len) {
493 ksmbd_debug(SMB, "padding len %u\n", len);
494 work->iov[work->iov_idx].iov_len += len;
495 inc_rfc1001_len(work->response_buf, len);
496 }
497 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
498 }
499 return false;
500 }
501
502 /**
503 * init_smb2_rsp_hdr() - initialize smb2 response
504 * @work: smb work containing smb request buffer
505 *
506 * Return: 0
507 */
508 int init_smb2_rsp_hdr(struct ksmbd_work *work)
509 {
510 struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
511 struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
512
513 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
514 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
515 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
516 rsp_hdr->Command = rcv_hdr->Command;
517
518 /*
519 * Message is response. We don't grant oplock yet.
520 */
521 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
522 rsp_hdr->NextCommand = 0;
523 rsp_hdr->MessageId = rcv_hdr->MessageId;
524 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
525 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
526 rsp_hdr->SessionId = rcv_hdr->SessionId;
527 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
528
529 return 0;
530 }
531
532 /**
533 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
534 * @work: smb work containing smb request buffer
535 *
536 * Return: 0 on success, otherwise error
537 */
538 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
539 {
540 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
541 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
542 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
543 size_t sz = small_sz;
544 int cmd = le16_to_cpu(hdr->Command);
545
546 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
547 sz = large_sz;
548
549 if (cmd == SMB2_QUERY_INFO_HE) {
550 struct smb2_query_info_req *req;
551
552 if (get_rfc1002_len(work->request_buf) <
553 offsetof(struct smb2_query_info_req, OutputBufferLength))
554 return -EINVAL;
555
556 req = smb_get_msg(work->request_buf);
557 if ((req->InfoType == SMB2_O_INFO_FILE &&
558 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
559 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
560 req->InfoType == SMB2_O_INFO_SECURITY)
561 sz = large_sz;
562 }
563
564 /* allocate large response buf for chained commands */
565 if (le32_to_cpu(hdr->NextCommand) > 0)
566 sz = large_sz;
567
568 work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
569 if (!work->response_buf)
570 return -ENOMEM;
571
572 work->response_sz = sz;
573 return 0;
574 }
575
576 /**
577 * smb2_check_user_session() - check for valid session for a user
578 * @work: smb work containing smb request buffer
579 *
580 * Return: 0 on success, otherwise error
581 */
582 int smb2_check_user_session(struct ksmbd_work *work)
583 {
584 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
585 struct ksmbd_conn *conn = work->conn;
586 unsigned int cmd = le16_to_cpu(req_hdr->Command);
587 unsigned long long sess_id;
588
589 /*
590 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
591 * require a session id, so no need to validate user session's for
592 * these commands.
593 */
594 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
595 cmd == SMB2_SESSION_SETUP_HE)
596 return 0;
597
598 if (!ksmbd_conn_good(conn))
599 return -EIO;
600
601 sess_id = le64_to_cpu(req_hdr->SessionId);
602
603 /*
604 * If request is not the first in Compound request,
605 * Just validate session id in header with work->sess->id.
606 */
607 if (work->next_smb2_rcv_hdr_off) {
608 if (!work->sess) {
609 pr_err("The first operation in the compound does not have sess\n");
610 return -EINVAL;
611 }
612 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
613 pr_err("session id(%llu) is different with the first operation(%lld)\n",
614 sess_id, work->sess->id);
615 return -EINVAL;
616 }
617 return 1;
618 }
619
620 /* Check for validity of user session */
621 work->sess = ksmbd_session_lookup_all(conn, sess_id);
622 if (work->sess)
623 return 1;
624 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
625 return -ENOENT;
626 }
627
628 /**
629 * smb2_get_name() - get filename string from on the wire smb format
630 * @src: source buffer
631 * @maxlen: maxlen of source string
632 * @local_nls: nls_table pointer
633 *
634 * Return: matching converted filename on success, otherwise error ptr
635 */
636 static char *
637 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
638 {
639 char *name;
640
641 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
642 if (IS_ERR(name)) {
643 pr_err("failed to get name %ld\n", PTR_ERR(name));
644 return name;
645 }
646
647 if (*name == '\0') {
648 kfree(name);
649 return ERR_PTR(-EINVAL);
650 }
651
652 if (*name == '\\') {
653 pr_err("not allow directory name included leading slash\n");
654 kfree(name);
655 return ERR_PTR(-EINVAL);
656 }
657
658 ksmbd_conv_path_to_unix(name);
659 ksmbd_strip_last_slash(name);
660 return name;
661 }
662
663 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
664 {
665 struct ksmbd_conn *conn = work->conn;
666 int id;
667
668 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
669 if (id < 0) {
670 pr_err("Failed to alloc async message id\n");
671 return id;
672 }
673 work->asynchronous = true;
674 work->async_id = id;
675
676 ksmbd_debug(SMB,
677 "Send interim Response to inform async request id : %d\n",
678 work->async_id);
679
680 work->cancel_fn = fn;
681 work->cancel_argv = arg;
682
683 if (list_empty(&work->async_request_entry)) {
684 spin_lock(&conn->request_lock);
685 list_add_tail(&work->async_request_entry, &conn->async_requests);
686 spin_unlock(&conn->request_lock);
687 }
688
689 return 0;
690 }
691
692 void release_async_work(struct ksmbd_work *work)
693 {
694 struct ksmbd_conn *conn = work->conn;
695
696 spin_lock(&conn->request_lock);
697 list_del_init(&work->async_request_entry);
698 spin_unlock(&conn->request_lock);
699
700 work->asynchronous = 0;
701 work->cancel_fn = NULL;
702 kfree(work->cancel_argv);
703 work->cancel_argv = NULL;
704 if (work->async_id) {
705 ksmbd_release_id(&conn->async_ida, work->async_id);
706 work->async_id = 0;
707 }
708 }
709
710 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
711 {
712 struct smb2_hdr *rsp_hdr;
713 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
714
715 if (!in_work)
716 return;
717
718 if (allocate_interim_rsp_buf(in_work)) {
719 pr_err("smb_allocate_rsp_buf failed!\n");
720 ksmbd_free_work_struct(in_work);
721 return;
722 }
723
724 in_work->conn = work->conn;
725 memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
726 __SMB2_HEADER_STRUCTURE_SIZE);
727
728 rsp_hdr = smb_get_msg(in_work->response_buf);
729 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
730 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
731 smb2_set_err_rsp(in_work);
732 rsp_hdr->Status = status;
733
734 ksmbd_conn_write(in_work);
735 ksmbd_free_work_struct(in_work);
736 }
737
738 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
739 {
740 if (S_ISDIR(mode) || S_ISREG(mode))
741 return 0;
742
743 if (S_ISLNK(mode))
744 return IO_REPARSE_TAG_LX_SYMLINK_LE;
745 else if (S_ISFIFO(mode))
746 return IO_REPARSE_TAG_LX_FIFO_LE;
747 else if (S_ISSOCK(mode))
748 return IO_REPARSE_TAG_AF_UNIX_LE;
749 else if (S_ISCHR(mode))
750 return IO_REPARSE_TAG_LX_CHR_LE;
751 else if (S_ISBLK(mode))
752 return IO_REPARSE_TAG_LX_BLK_LE;
753
754 return 0;
755 }
756
757 /**
758 * smb2_get_dos_mode() - get file mode in dos format from unix mode
759 * @stat: kstat containing file mode
760 * @attribute: attribute flags
761 *
762 * Return: converted dos mode
763 */
764 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
765 {
766 int attr = 0;
767
768 if (S_ISDIR(stat->mode)) {
769 attr = FILE_ATTRIBUTE_DIRECTORY |
770 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
771 } else {
772 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
773 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
774 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
775 FILE_SUPPORTS_SPARSE_FILES))
776 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
777
778 if (smb2_get_reparse_tag_special_file(stat->mode))
779 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
780 }
781
782 return attr;
783 }
784
785 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
786 __le16 hash_id)
787 {
788 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
789 pneg_ctxt->DataLength = cpu_to_le16(38);
790 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
791 pneg_ctxt->Reserved = cpu_to_le32(0);
792 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
793 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
794 pneg_ctxt->HashAlgorithms = hash_id;
795 }
796
797 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
798 __le16 cipher_type)
799 {
800 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
801 pneg_ctxt->DataLength = cpu_to_le16(4);
802 pneg_ctxt->Reserved = cpu_to_le32(0);
803 pneg_ctxt->CipherCount = cpu_to_le16(1);
804 pneg_ctxt->Ciphers[0] = cipher_type;
805 }
806
807 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
808 __le16 sign_algo)
809 {
810 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
811 pneg_ctxt->DataLength =
812 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
813 - sizeof(struct smb2_neg_context));
814 pneg_ctxt->Reserved = cpu_to_le32(0);
815 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
816 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
817 }
818
819 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
820 {
821 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
822 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
823 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
824 pneg_ctxt->Name[0] = 0x93;
825 pneg_ctxt->Name[1] = 0xAD;
826 pneg_ctxt->Name[2] = 0x25;
827 pneg_ctxt->Name[3] = 0x50;
828 pneg_ctxt->Name[4] = 0x9C;
829 pneg_ctxt->Name[5] = 0xB4;
830 pneg_ctxt->Name[6] = 0x11;
831 pneg_ctxt->Name[7] = 0xE7;
832 pneg_ctxt->Name[8] = 0xB4;
833 pneg_ctxt->Name[9] = 0x23;
834 pneg_ctxt->Name[10] = 0x83;
835 pneg_ctxt->Name[11] = 0xDE;
836 pneg_ctxt->Name[12] = 0x96;
837 pneg_ctxt->Name[13] = 0x8B;
838 pneg_ctxt->Name[14] = 0xCD;
839 pneg_ctxt->Name[15] = 0x7C;
840 }
841
842 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
843 struct smb2_negotiate_rsp *rsp)
844 {
845 char * const pneg_ctxt = (char *)rsp +
846 le32_to_cpu(rsp->NegotiateContextOffset);
847 int neg_ctxt_cnt = 1;
848 int ctxt_size;
849
850 ksmbd_debug(SMB,
851 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
852 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
853 conn->preauth_info->Preauth_HashId);
854 ctxt_size = sizeof(struct smb2_preauth_neg_context);
855
856 if (conn->cipher_type) {
857 /* Round to 8 byte boundary */
858 ctxt_size = round_up(ctxt_size, 8);
859 ksmbd_debug(SMB,
860 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
861 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
862 (pneg_ctxt + ctxt_size),
863 conn->cipher_type);
864 neg_ctxt_cnt++;
865 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
866 }
867
868 /* compression context not yet supported */
869 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
870
871 if (conn->posix_ext_supported) {
872 ctxt_size = round_up(ctxt_size, 8);
873 ksmbd_debug(SMB,
874 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
875 build_posix_ctxt((struct smb2_posix_neg_context *)
876 (pneg_ctxt + ctxt_size));
877 neg_ctxt_cnt++;
878 ctxt_size += sizeof(struct smb2_posix_neg_context);
879 }
880
881 if (conn->signing_negotiated) {
882 ctxt_size = round_up(ctxt_size, 8);
883 ksmbd_debug(SMB,
884 "assemble SMB2_SIGNING_CAPABILITIES context\n");
885 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
886 (pneg_ctxt + ctxt_size),
887 conn->signing_algorithm);
888 neg_ctxt_cnt++;
889 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
890 }
891
892 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
893 return ctxt_size + AUTH_GSS_PADDING;
894 }
895
896 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
897 struct smb2_preauth_neg_context *pneg_ctxt,
898 int ctxt_len)
899 {
900 /*
901 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
902 * which may not be present. Only check for used HashAlgorithms[1].
903 */
904 if (ctxt_len <
905 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
906 return STATUS_INVALID_PARAMETER;
907
908 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
909 return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
910
911 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
912 return STATUS_SUCCESS;
913 }
914
915 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
916 struct smb2_encryption_neg_context *pneg_ctxt,
917 int ctxt_len)
918 {
919 int cph_cnt;
920 int i, cphs_size;
921
922 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
923 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
924 return;
925 }
926
927 conn->cipher_type = 0;
928
929 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
930 cphs_size = cph_cnt * sizeof(__le16);
931
932 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
933 ctxt_len) {
934 pr_err("Invalid cipher count(%d)\n", cph_cnt);
935 return;
936 }
937
938 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
939 return;
940
941 for (i = 0; i < cph_cnt; i++) {
942 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
943 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
944 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
945 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
946 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
947 pneg_ctxt->Ciphers[i]);
948 conn->cipher_type = pneg_ctxt->Ciphers[i];
949 break;
950 }
951 }
952 }
953
954 /**
955 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
956 * @conn: smb connection
957 *
958 * Return: true if connection should be encrypted, else false
959 */
960 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
961 {
962 if (!conn->ops->generate_encryptionkey)
963 return false;
964
965 /*
966 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
967 * SMB 3.1.1 uses the cipher_type field.
968 */
969 return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
970 conn->cipher_type;
971 }
972
973 static void decode_compress_ctxt(struct ksmbd_conn *conn,
974 struct smb2_compression_capabilities_context *pneg_ctxt)
975 {
976 conn->compress_algorithm = SMB3_COMPRESS_NONE;
977 }
978
979 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
980 struct smb2_signing_capabilities *pneg_ctxt,
981 int ctxt_len)
982 {
983 int sign_algo_cnt;
984 int i, sign_alos_size;
985
986 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
987 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
988 return;
989 }
990
991 conn->signing_negotiated = false;
992 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
993 sign_alos_size = sign_algo_cnt * sizeof(__le16);
994
995 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
996 ctxt_len) {
997 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
998 return;
999 }
1000
1001 for (i = 0; i < sign_algo_cnt; i++) {
1002 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1003 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1004 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1005 pneg_ctxt->SigningAlgorithms[i]);
1006 conn->signing_negotiated = true;
1007 conn->signing_algorithm =
1008 pneg_ctxt->SigningAlgorithms[i];
1009 break;
1010 }
1011 }
1012 }
1013
1014 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1015 struct smb2_negotiate_req *req,
1016 unsigned int len_of_smb)
1017 {
1018 /* +4 is to account for the RFC1001 len field */
1019 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1020 int i = 0, len_of_ctxts;
1021 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1022 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1023 __le32 status = STATUS_INVALID_PARAMETER;
1024
1025 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1026 if (len_of_smb <= offset) {
1027 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1028 return status;
1029 }
1030
1031 len_of_ctxts = len_of_smb - offset;
1032
1033 while (i++ < neg_ctxt_cnt) {
1034 int clen, ctxt_len;
1035
1036 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1037 break;
1038
1039 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1040 clen = le16_to_cpu(pctx->DataLength);
1041 ctxt_len = clen + sizeof(struct smb2_neg_context);
1042
1043 if (ctxt_len > len_of_ctxts)
1044 break;
1045
1046 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1047 ksmbd_debug(SMB,
1048 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1049 if (conn->preauth_info->Preauth_HashId)
1050 break;
1051
1052 status = decode_preauth_ctxt(conn,
1053 (struct smb2_preauth_neg_context *)pctx,
1054 ctxt_len);
1055 if (status != STATUS_SUCCESS)
1056 break;
1057 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1058 ksmbd_debug(SMB,
1059 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1060 if (conn->cipher_type)
1061 break;
1062
1063 decode_encrypt_ctxt(conn,
1064 (struct smb2_encryption_neg_context *)pctx,
1065 ctxt_len);
1066 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1067 ksmbd_debug(SMB,
1068 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1069 if (conn->compress_algorithm)
1070 break;
1071
1072 decode_compress_ctxt(conn,
1073 (struct smb2_compression_capabilities_context *)pctx);
1074 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1075 ksmbd_debug(SMB,
1076 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1077 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1078 ksmbd_debug(SMB,
1079 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1080 conn->posix_ext_supported = true;
1081 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1082 ksmbd_debug(SMB,
1083 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1084
1085 decode_sign_cap_ctxt(conn,
1086 (struct smb2_signing_capabilities *)pctx,
1087 ctxt_len);
1088 }
1089
1090 /* offsets must be 8 byte aligned */
1091 offset = (ctxt_len + 7) & ~0x7;
1092 len_of_ctxts -= offset;
1093 }
1094 return status;
1095 }
1096
1097 /**
1098 * smb2_handle_negotiate() - handler for smb2 negotiate command
1099 * @work: smb work containing smb request buffer
1100 *
1101 * Return: 0
1102 */
1103 int smb2_handle_negotiate(struct ksmbd_work *work)
1104 {
1105 struct ksmbd_conn *conn = work->conn;
1106 struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1107 struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1108 int rc = 0;
1109 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1110 __le32 status;
1111
1112 ksmbd_debug(SMB, "Received negotiate request\n");
1113 conn->need_neg = false;
1114 if (ksmbd_conn_good(conn)) {
1115 pr_err("conn->tcp_status is already in CifsGood State\n");
1116 work->send_no_response = 1;
1117 return rc;
1118 }
1119
1120 ksmbd_conn_lock(conn);
1121 smb2_buf_len = get_rfc1002_len(work->request_buf);
1122 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1123 if (smb2_neg_size > smb2_buf_len) {
1124 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1125 rc = -EINVAL;
1126 goto err_out;
1127 }
1128
1129 if (req->DialectCount == 0) {
1130 pr_err("malformed packet\n");
1131 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1132 rc = -EINVAL;
1133 goto err_out;
1134 }
1135
1136 if (conn->dialect == SMB311_PROT_ID) {
1137 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1138
1139 if (smb2_buf_len < nego_ctxt_off) {
1140 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1141 rc = -EINVAL;
1142 goto err_out;
1143 }
1144
1145 if (smb2_neg_size > nego_ctxt_off) {
1146 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1147 rc = -EINVAL;
1148 goto err_out;
1149 }
1150
1151 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1152 nego_ctxt_off) {
1153 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1154 rc = -EINVAL;
1155 goto err_out;
1156 }
1157 } else {
1158 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1159 smb2_buf_len) {
1160 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1161 rc = -EINVAL;
1162 goto err_out;
1163 }
1164 }
1165
1166 conn->cli_cap = le32_to_cpu(req->Capabilities);
1167 switch (conn->dialect) {
1168 case SMB311_PROT_ID:
1169 conn->preauth_info =
1170 kzalloc_obj(struct preauth_integrity_info,
1171 KSMBD_DEFAULT_GFP);
1172 if (!conn->preauth_info) {
1173 rc = -ENOMEM;
1174 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1175 goto err_out;
1176 }
1177
1178 status = deassemble_neg_contexts(conn, req,
1179 get_rfc1002_len(work->request_buf));
1180 if (status != STATUS_SUCCESS) {
1181 pr_err("deassemble_neg_contexts error(0x%x)\n",
1182 status);
1183 rsp->hdr.Status = status;
1184 rc = -EINVAL;
1185 kfree(conn->preauth_info);
1186 conn->preauth_info = NULL;
1187 goto err_out;
1188 }
1189
1190 rc = init_smb3_11_server(conn);
1191 if (rc < 0) {
1192 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1193 kfree(conn->preauth_info);
1194 conn->preauth_info = NULL;
1195 goto err_out;
1196 }
1197
1198 ksmbd_gen_preauth_integrity_hash(conn,
1199 work->request_buf,
1200 conn->preauth_info->Preauth_HashValue);
1201 rsp->NegotiateContextOffset =
1202 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1203 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1204 break;
1205 case SMB302_PROT_ID:
1206 init_smb3_02_server(conn);
1207 break;
1208 case SMB30_PROT_ID:
1209 init_smb3_0_server(conn);
1210 break;
1211 case SMB21_PROT_ID:
1212 init_smb2_1_server(conn);
1213 break;
1214 case SMB2X_PROT_ID:
1215 case BAD_PROT_ID:
1216 default:
1217 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1218 conn->dialect);
1219 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1220 rc = -EINVAL;
1221 goto err_out;
1222 }
1223 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1224
1225 /* For stats */
1226 conn->connection_type = conn->dialect;
1227
1228 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1229 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1230 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1231
1232 memcpy(conn->ClientGUID, req->ClientGUID,
1233 SMB2_CLIENT_GUID_SIZE);
1234 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1235
1236 rsp->StructureSize = cpu_to_le16(65);
1237 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1238 /* Not setting conn guid rsp->ServerGUID, as it
1239 * not used by client for identifying server
1240 */
1241 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1242
1243 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1244 rsp->ServerStartTime = 0;
1245 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1246 le32_to_cpu(rsp->NegotiateContextOffset),
1247 le16_to_cpu(rsp->NegotiateContextCount));
1248
1249 rsp->SecurityBufferOffset = cpu_to_le16(128);
1250 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1251 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1252 le16_to_cpu(rsp->SecurityBufferOffset));
1253
1254 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1255 conn->use_spnego = true;
1256
1257 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1258 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1259 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1260 conn->sign = true;
1261 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1262 server_conf.enforced_signing = true;
1263 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1264 conn->sign = true;
1265 }
1266
1267 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1268 ksmbd_conn_set_need_setup(conn);
1269
1270 err_out:
1271 ksmbd_conn_unlock(conn);
1272 if (rc)
1273 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1274
1275 if (!rc)
1276 rc = ksmbd_iov_pin_rsp(work, rsp,
1277 sizeof(struct smb2_negotiate_rsp) +
1278 AUTH_GSS_LENGTH + neg_ctxt_len);
1279 if (rc < 0)
1280 smb2_set_err_rsp(work);
1281 return rc;
1282 }
1283
1284 static int alloc_preauth_hash(struct ksmbd_session *sess,
1285 struct ksmbd_conn *conn)
1286 {
1287 if (sess->Preauth_HashValue)
1288 return 0;
1289
1290 if (!conn->preauth_info)
1291 return -ENOMEM;
1292
1293 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1294 PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
1295 if (!sess->Preauth_HashValue)
1296 return -ENOMEM;
1297
1298 return 0;
1299 }
1300
1301 static int generate_preauth_hash(struct ksmbd_work *work)
1302 {
1303 struct ksmbd_conn *conn = work->conn;
1304 struct ksmbd_session *sess = work->sess;
1305 u8 *preauth_hash;
1306
1307 if (conn->dialect != SMB311_PROT_ID)
1308 return 0;
1309
1310 if (conn->binding) {
1311 struct preauth_session *preauth_sess;
1312
1313 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1314 if (!preauth_sess) {
1315 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1316 if (!preauth_sess)
1317 return -ENOMEM;
1318 }
1319
1320 preauth_hash = preauth_sess->Preauth_HashValue;
1321 } else {
1322 if (!sess->Preauth_HashValue)
1323 if (alloc_preauth_hash(sess, conn))
1324 return -ENOMEM;
1325 preauth_hash = sess->Preauth_HashValue;
1326 }
1327
1328 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1329 return 0;
1330 }
1331
1332 static int decode_negotiation_token(struct ksmbd_conn *conn,
1333 struct negotiate_message *negblob,
1334 size_t sz)
1335 {
1336 if (!conn->use_spnego)
1337 return -EINVAL;
1338
1339 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1340 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1341 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1342 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1343 conn->use_spnego = false;
1344 }
1345 }
1346 return 0;
1347 }
1348
1349 static int ntlm_negotiate(struct ksmbd_work *work,
1350 struct negotiate_message *negblob,
1351 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1352 {
1353 struct challenge_message *chgblob;
1354 unsigned char *spnego_blob = NULL;
1355 u16 spnego_blob_len;
1356 char *neg_blob;
1357 int sz, rc;
1358
1359 ksmbd_debug(SMB, "negotiate phase\n");
1360 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1361 if (rc)
1362 return rc;
1363
1364 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1365 chgblob = (struct challenge_message *)rsp->Buffer;
1366 memset(chgblob, 0, sizeof(struct challenge_message));
1367
1368 if (!work->conn->use_spnego) {
1369 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1370 if (sz < 0)
1371 return -ENOMEM;
1372
1373 rsp->SecurityBufferLength = cpu_to_le16(sz);
1374 return 0;
1375 }
1376
1377 sz = sizeof(struct challenge_message);
1378 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1379
1380 neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
1381 if (!neg_blob)
1382 return -ENOMEM;
1383
1384 chgblob = (struct challenge_message *)neg_blob;
1385 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1386 if (sz < 0) {
1387 rc = -ENOMEM;
1388 goto out;
1389 }
1390
1391 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1392 neg_blob, sz);
1393 if (rc) {
1394 rc = -ENOMEM;
1395 goto out;
1396 }
1397
1398 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1399 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1400
1401 out:
1402 kfree(spnego_blob);
1403 kfree(neg_blob);
1404 return rc;
1405 }
1406
1407 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1408 struct smb2_sess_setup_req *req)
1409 {
1410 int sz;
1411
1412 if (conn->use_spnego && conn->mechToken)
1413 return (struct authenticate_message *)conn->mechToken;
1414
1415 sz = le16_to_cpu(req->SecurityBufferOffset);
1416 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1417 + sz);
1418 }
1419
1420 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1421 struct smb2_sess_setup_req *req)
1422 {
1423 struct authenticate_message *authblob;
1424 struct ksmbd_user *user;
1425 char *name;
1426 unsigned int name_off, name_len, secbuf_len;
1427
1428 if (conn->use_spnego && conn->mechToken)
1429 secbuf_len = conn->mechTokenLen;
1430 else
1431 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1432 if (secbuf_len < sizeof(struct authenticate_message)) {
1433 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1434 return NULL;
1435 }
1436 authblob = user_authblob(conn, req);
1437 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1438 name_len = le16_to_cpu(authblob->UserName.Length);
1439
1440 if (secbuf_len < (u64)name_off + name_len)
1441 return NULL;
1442
1443 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1444 name_len,
1445 true,
1446 conn->local_nls);
1447 if (IS_ERR(name)) {
1448 pr_err("cannot allocate memory\n");
1449 return NULL;
1450 }
1451
1452 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1453 user = ksmbd_login_user(name);
1454 kfree(name);
1455 return user;
1456 }
1457
1458 static int ntlm_authenticate(struct ksmbd_work *work,
1459 struct smb2_sess_setup_req *req,
1460 struct smb2_sess_setup_rsp *rsp)
1461 {
1462 struct ksmbd_conn *conn = work->conn;
1463 struct ksmbd_session *sess = work->sess;
1464 struct channel *chann = NULL, *old;
1465 struct ksmbd_user *user;
1466 u64 prev_id;
1467 int sz, rc;
1468
1469 ksmbd_debug(SMB, "authenticate phase\n");
1470 if (conn->use_spnego) {
1471 unsigned char *spnego_blob;
1472 u16 spnego_blob_len;
1473
1474 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1475 &spnego_blob_len,
1476 0);
1477 if (rc)
1478 return -ENOMEM;
1479
1480 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1481 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1482 kfree(spnego_blob);
1483 }
1484
1485 user = session_user(conn, req);
1486 if (!user) {
1487 ksmbd_debug(SMB, "Unknown user name or an error\n");
1488 return -EPERM;
1489 }
1490
1491 /* Check for previous session */
1492 prev_id = le64_to_cpu(req->PreviousSessionId);
1493 if (prev_id && prev_id != sess->id)
1494 destroy_previous_session(conn, user, prev_id);
1495
1496 if (sess->state == SMB2_SESSION_VALID) {
1497 /*
1498 * Reuse session if anonymous try to connect
1499 * on reauthetication.
1500 */
1501 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1502 ksmbd_free_user(user);
1503 return 0;
1504 }
1505
1506 if (!ksmbd_compare_user(sess->user, user)) {
1507 ksmbd_free_user(user);
1508 return -EPERM;
1509 }
1510 ksmbd_free_user(user);
1511 } else {
1512 sess->user = user;
1513 }
1514
1515 if (conn->binding == false && user_guest(sess->user)) {
1516 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1517 } else {
1518 struct authenticate_message *authblob;
1519
1520 authblob = user_authblob(conn, req);
1521 if (conn->use_spnego && conn->mechToken)
1522 sz = conn->mechTokenLen;
1523 else
1524 sz = le16_to_cpu(req->SecurityBufferLength);
1525 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1526 if (rc) {
1527 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1528 ksmbd_debug(SMB, "authentication failed\n");
1529 return -EPERM;
1530 }
1531 }
1532
1533 /*
1534 * If session state is SMB2_SESSION_VALID, We can assume
1535 * that it is reauthentication. And the user/password
1536 * has been verified, so return it here.
1537 */
1538 if (sess->state == SMB2_SESSION_VALID) {
1539 if (conn->binding)
1540 goto binding_session;
1541 return 0;
1542 }
1543
1544 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1545 (conn->sign || server_conf.enforced_signing)) ||
1546 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1547 sess->sign = true;
1548
1549 if (smb3_encryption_negotiated(conn) &&
1550 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1551 conn->ops->generate_encryptionkey(conn, sess);
1552 sess->enc = true;
1553 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1554 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1555 /*
1556 * signing is disable if encryption is enable
1557 * on this session
1558 */
1559 sess->sign = false;
1560 }
1561
1562 binding_session:
1563 if (conn->dialect >= SMB30_PROT_ID) {
1564 chann = lookup_chann_list(sess, conn);
1565 if (!chann) {
1566 chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
1567 if (!chann)
1568 return -ENOMEM;
1569
1570 chann->conn = conn;
1571 down_write(&sess->chann_lock);
1572 old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
1573 KSMBD_DEFAULT_GFP);
1574 up_write(&sess->chann_lock);
1575 if (xa_is_err(old)) {
1576 kfree(chann);
1577 return xa_err(old);
1578 }
1579 }
1580 }
1581
1582 if (conn->ops->generate_signingkey) {
1583 rc = conn->ops->generate_signingkey(sess, conn);
1584 if (rc) {
1585 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1586 return -EINVAL;
1587 }
1588 }
1589
1590 if (!ksmbd_conn_lookup_dialect(conn)) {
1591 pr_err("fail to verify the dialect\n");
1592 return -ENOENT;
1593 }
1594 return 0;
1595 }
1596
1597 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1598 static int krb5_authenticate(struct ksmbd_work *work,
1599 struct smb2_sess_setup_req *req,
1600 struct smb2_sess_setup_rsp *rsp)
1601 {
1602 struct ksmbd_conn *conn = work->conn;
1603 struct ksmbd_session *sess = work->sess;
1604 char *in_blob, *out_blob;
1605 struct channel *chann = NULL, *old;
1606 u64 prev_sess_id;
1607 int in_len, out_len;
1608 int retval;
1609
1610 in_blob = (char *)&req->hdr.ProtocolId +
1611 le16_to_cpu(req->SecurityBufferOffset);
1612 in_len = le16_to_cpu(req->SecurityBufferLength);
1613 out_blob = (char *)&rsp->hdr.ProtocolId +
1614 le16_to_cpu(rsp->SecurityBufferOffset);
1615 out_len = work->response_sz -
1616 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1617
1618 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1619 out_blob, &out_len);
1620 if (retval) {
1621 ksmbd_debug(SMB, "krb5 authentication failed\n");
1622 return -EINVAL;
1623 }
1624
1625 /* Check previous session */
1626 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1627 if (prev_sess_id && prev_sess_id != sess->id)
1628 destroy_previous_session(conn, sess->user, prev_sess_id);
1629
1630 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1631
1632 /*
1633 * If session state is SMB2_SESSION_VALID, We can assume
1634 * that it is reauthentication. And the user/password
1635 * has been verified, so return it here.
1636 */
1637 if (sess->state == SMB2_SESSION_VALID) {
1638 if (conn->binding)
1639 goto binding_session;
1640 return 0;
1641 }
1642
1643 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1644 (conn->sign || server_conf.enforced_signing)) ||
1645 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1646 sess->sign = true;
1647
1648 if (smb3_encryption_negotiated(conn) &&
1649 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1650 conn->ops->generate_encryptionkey(conn, sess);
1651 sess->enc = true;
1652 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1653 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1654 sess->sign = false;
1655 }
1656
1657 binding_session:
1658 if (conn->dialect >= SMB30_PROT_ID) {
1659 chann = lookup_chann_list(sess, conn);
1660 if (!chann) {
1661 chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
1662 if (!chann)
1663 return -ENOMEM;
1664
1665 chann->conn = conn;
1666 down_write(&sess->chann_lock);
1667 old = xa_store(&sess->ksmbd_chann_list, (long)conn,
1668 chann, KSMBD_DEFAULT_GFP);
1669 up_write(&sess->chann_lock);
1670 if (xa_is_err(old)) {
1671 kfree(chann);
1672 return xa_err(old);
1673 }
1674 }
1675 }
1676
1677 if (conn->ops->generate_signingkey) {
1678 retval = conn->ops->generate_signingkey(sess, conn);
1679 if (retval) {
1680 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1681 return -EINVAL;
1682 }
1683 }
1684
1685 if (!ksmbd_conn_lookup_dialect(conn)) {
1686 pr_err("fail to verify the dialect\n");
1687 return -ENOENT;
1688 }
1689 return 0;
1690 }
1691 #else
1692 static int krb5_authenticate(struct ksmbd_work *work,
1693 struct smb2_sess_setup_req *req,
1694 struct smb2_sess_setup_rsp *rsp)
1695 {
1696 return -EOPNOTSUPP;
1697 }
1698 #endif
1699
1700 int smb2_sess_setup(struct ksmbd_work *work)
1701 {
1702 struct ksmbd_conn *conn = work->conn;
1703 struct smb2_sess_setup_req *req;
1704 struct smb2_sess_setup_rsp *rsp;
1705 struct ksmbd_session *sess;
1706 struct negotiate_message *negblob;
1707 unsigned int negblob_len, negblob_off;
1708 int rc = 0;
1709
1710 ksmbd_debug(SMB, "Received smb2 session setup request\n");
1711
1712 if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
1713 work->send_no_response = 1;
1714 return rc;
1715 }
1716
1717 WORK_BUFFERS(work, req, rsp);
1718
1719 rsp->StructureSize = cpu_to_le16(9);
1720 rsp->SessionFlags = 0;
1721 rsp->SecurityBufferOffset = cpu_to_le16(72);
1722 rsp->SecurityBufferLength = 0;
1723
1724 ksmbd_conn_lock(conn);
1725 if (!req->hdr.SessionId) {
1726 sess = ksmbd_smb2_session_create();
1727 if (!sess) {
1728 rc = -ENOMEM;
1729 goto out_err;
1730 }
1731 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1732 rc = ksmbd_session_register(conn, sess);
1733 if (rc)
1734 goto out_err;
1735
1736 conn->binding = false;
1737 } else if (conn->dialect >= SMB30_PROT_ID &&
1738 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1739 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1740 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1741
1742 sess = ksmbd_session_lookup_slowpath(sess_id);
1743 if (!sess) {
1744 rc = -ENOENT;
1745 goto out_err;
1746 }
1747
1748 if (conn->dialect != sess->dialect) {
1749 rc = -EINVAL;
1750 goto out_err;
1751 }
1752
1753 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1754 rc = -EINVAL;
1755 goto out_err;
1756 }
1757
1758 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1759 SMB2_CLIENT_GUID_SIZE)) {
1760 rc = -ENOENT;
1761 goto out_err;
1762 }
1763
1764 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1765 rc = -EACCES;
1766 goto out_err;
1767 }
1768
1769 if (sess->state == SMB2_SESSION_EXPIRED) {
1770 rc = -EFAULT;
1771 goto out_err;
1772 }
1773
1774 if (ksmbd_conn_need_reconnect(conn)) {
1775 rc = -EFAULT;
1776 ksmbd_user_session_put(sess);
1777 sess = NULL;
1778 goto out_err;
1779 }
1780
1781 if (is_ksmbd_session_in_connection(conn, sess_id)) {
1782 rc = -EACCES;
1783 goto out_err;
1784 }
1785
1786 if (user_guest(sess->user)) {
1787 rc = -EOPNOTSUPP;
1788 goto out_err;
1789 }
1790
1791 conn->binding = true;
1792 } else if ((conn->dialect < SMB30_PROT_ID ||
1793 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1794 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1795 sess = NULL;
1796 rc = -EACCES;
1797 goto out_err;
1798 } else {
1799 sess = ksmbd_session_lookup(conn,
1800 le64_to_cpu(req->hdr.SessionId));
1801 if (!sess) {
1802 rc = -ENOENT;
1803 goto out_err;
1804 }
1805
1806 if (sess->state == SMB2_SESSION_EXPIRED) {
1807 rc = -EFAULT;
1808 goto out_err;
1809 }
1810
1811 if (ksmbd_conn_need_reconnect(conn)) {
1812 rc = -EFAULT;
1813 ksmbd_user_session_put(sess);
1814 sess = NULL;
1815 goto out_err;
1816 }
1817
1818 conn->binding = false;
1819 }
1820 work->sess = sess;
1821
1822 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1823 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1824 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1825 rc = -EINVAL;
1826 goto out_err;
1827 }
1828
1829 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1830 negblob_off);
1831
1832 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1833 if (conn->mechToken) {
1834 negblob = (struct negotiate_message *)conn->mechToken;
1835 negblob_len = conn->mechTokenLen;
1836 }
1837 }
1838
1839 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1840 rc = -EINVAL;
1841 goto out_err;
1842 }
1843
1844 if (server_conf.auth_mechs & conn->auth_mechs) {
1845 rc = generate_preauth_hash(work);
1846 if (rc)
1847 goto out_err;
1848
1849 if (conn->preferred_auth_mech &
1850 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1851 rc = krb5_authenticate(work, req, rsp);
1852 if (rc) {
1853 rc = -EINVAL;
1854 goto out_err;
1855 }
1856
1857 if (!ksmbd_conn_need_reconnect(conn)) {
1858 ksmbd_conn_set_good(conn);
1859 sess->state = SMB2_SESSION_VALID;
1860 }
1861 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1862 if (negblob->MessageType == NtLmNegotiate) {
1863 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1864 if (rc)
1865 goto out_err;
1866 rsp->hdr.Status =
1867 STATUS_MORE_PROCESSING_REQUIRED;
1868 } else if (negblob->MessageType == NtLmAuthenticate) {
1869 rc = ntlm_authenticate(work, req, rsp);
1870 if (rc)
1871 goto out_err;
1872
1873 if (!ksmbd_conn_need_reconnect(conn)) {
1874 ksmbd_conn_set_good(conn);
1875 sess->state = SMB2_SESSION_VALID;
1876 }
1877 if (conn->binding) {
1878 struct preauth_session *preauth_sess;
1879
1880 preauth_sess =
1881 ksmbd_preauth_session_lookup(conn, sess->id);
1882 if (preauth_sess) {
1883 list_del(&preauth_sess->preauth_entry);
1884 kfree(preauth_sess);
1885 }
1886 }
1887 } else {
1888 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1889 le32_to_cpu(negblob->MessageType));
1890 rc = -EINVAL;
1891 }
1892 } else {
1893 /* TODO: need one more negotiation */
1894 pr_err("Not support the preferred authentication\n");
1895 rc = -EINVAL;
1896 }
1897 } else {
1898 pr_err("Not support authentication\n");
1899 rc = -EINVAL;
1900 }
1901
1902 out_err:
1903 if (rc == -EINVAL)
1904 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1905 else if (rc == -ENOENT)
1906 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1907 else if (rc == -EACCES)
1908 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1909 else if (rc == -EFAULT)
1910 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1911 else if (rc == -ENOMEM)
1912 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1913 else if (rc == -EOPNOTSUPP)
1914 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1915 else if (rc)
1916 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1917
1918 if (conn->mechToken) {
1919 kfree(conn->mechToken);
1920 conn->mechToken = NULL;
1921 }
1922
1923 if (rc < 0) {
1924 /*
1925 * SecurityBufferOffset should be set to zero
1926 * in session setup error response.
1927 */
1928 rsp->SecurityBufferOffset = 0;
1929
1930 if (sess) {
1931 bool try_delay = false;
1932
1933 /*
1934 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1935 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1936 * failure to make it harder to send enough random connection requests
1937 * to break into a server.
1938 */
1939 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1940 try_delay = true;
1941
1942 /*
1943 * For binding requests, session belongs to another
1944 * connection. Do not expire it.
1945 */
1946 if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1947 sess->last_active = jiffies;
1948 sess->state = SMB2_SESSION_EXPIRED;
1949 }
1950 ksmbd_user_session_put(sess);
1951 work->sess = NULL;
1952 if (try_delay) {
1953 ksmbd_conn_set_need_reconnect(conn);
1954 ssleep(5);
1955 ksmbd_conn_set_need_setup(conn);
1956 }
1957 }
1958 smb2_set_err_rsp(work);
1959 conn->binding = false;
1960 } else {
1961 unsigned int iov_len;
1962
1963 if (rsp->SecurityBufferLength)
1964 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1965 le16_to_cpu(rsp->SecurityBufferLength);
1966 else
1967 iov_len = sizeof(struct smb2_sess_setup_rsp);
1968 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1969 if (rc)
1970 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1971 }
1972
1973 ksmbd_conn_unlock(conn);
1974 return rc;
1975 }
1976
1977 /**
1978 * smb2_tree_connect() - handler for smb2 tree connect command
1979 * @work: smb work containing smb request buffer
1980 *
1981 * Return: 0 on success, otherwise error
1982 */
1983 int smb2_tree_connect(struct ksmbd_work *work)
1984 {
1985 struct ksmbd_conn *conn = work->conn;
1986 struct smb2_tree_connect_req *req;
1987 struct smb2_tree_connect_rsp *rsp;
1988 struct ksmbd_session *sess = work->sess;
1989 char *treename = NULL, *name = NULL;
1990 struct ksmbd_tree_conn_status status;
1991 struct ksmbd_share_config *share = NULL;
1992 int rc = -EINVAL;
1993
1994 ksmbd_debug(SMB, "Received smb2 tree connect request\n");
1995
1996 WORK_BUFFERS(work, req, rsp);
1997
1998 treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
1999 le16_to_cpu(req->PathLength), true,
2000 conn->local_nls);
2001 if (IS_ERR(treename)) {
2002 pr_err("treename is NULL\n");
2003 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2004 goto out_err1;
2005 }
2006
2007 name = ksmbd_extract_sharename(conn->um, treename);
2008 if (IS_ERR(name)) {
2009 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2010 goto out_err1;
2011 }
2012
2013 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
2014 name, treename);
2015
2016 status = ksmbd_tree_conn_connect(work, name);
2017 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
2018 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
2019 else
2020 goto out_err1;
2021
2022 share = status.tree_conn->share_conf;
2023 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2024 ksmbd_debug(SMB, "IPC share path request\n");
2025 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2026 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2027 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2028 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2029 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2030 FILE_SYNCHRONIZE_LE;
2031 } else {
2032 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2033 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2034 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2035 if (test_tree_conn_flag(status.tree_conn,
2036 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2037 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2038 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2039 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2040 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2041 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2042 FILE_SYNCHRONIZE_LE;
2043 }
2044 }
2045
2046 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2047 if (conn->posix_ext_supported)
2048 status.tree_conn->posix_extensions = true;
2049
2050 down_write(&sess->tree_conns_lock);
2051 status.tree_conn->t_state = TREE_CONNECTED;
2052 up_write(&sess->tree_conns_lock);
2053 rsp->StructureSize = cpu_to_le16(16);
2054 out_err1:
2055 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && share &&
2056 test_share_config_flag(share,
2057 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
2058 rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
2059 else
2060 rsp->Capabilities = 0;
2061 rsp->Reserved = 0;
2062 /* default manual caching */
2063 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2064
2065 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2066 if (rc)
2067 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2068
2069 if (!IS_ERR(treename))
2070 kfree(treename);
2071 if (!IS_ERR(name))
2072 kfree(name);
2073
2074 switch (status.ret) {
2075 case KSMBD_TREE_CONN_STATUS_OK:
2076 rsp->hdr.Status = STATUS_SUCCESS;
2077 rc = 0;
2078 break;
2079 case -ESTALE:
2080 case -ENOENT:
2081 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2082 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2083 break;
2084 case -ENOMEM:
2085 case KSMBD_TREE_CONN_STATUS_NOMEM:
2086 rsp->hdr.Status = STATUS_NO_MEMORY;
2087 break;
2088 case KSMBD_TREE_CONN_STATUS_ERROR:
2089 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2090 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2091 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2092 break;
2093 case -EINVAL:
2094 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2095 break;
2096 default:
2097 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2098 }
2099
2100 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2101 smb2_set_err_rsp(work);
2102
2103 return rc;
2104 }
2105
2106 /**
2107 * smb2_create_open_flags() - convert smb open flags to unix open flags
2108 * @file_present: is file already present
2109 * @access: file access flags
2110 * @disposition: file disposition flags
2111 * @may_flags: set with MAY_ flags
2112 * @coptions: file creation options
2113 * @mode: file mode
2114 *
2115 * Return: file open flags
2116 */
2117 static int smb2_create_open_flags(bool file_present, __le32 access,
2118 __le32 disposition,
2119 int *may_flags,
2120 __le32 coptions,
2121 umode_t mode)
2122 {
2123 int oflags = O_NONBLOCK | O_LARGEFILE;
2124
2125 if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2126 access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2127 ksmbd_debug(SMB, "Discard write access to a directory\n");
2128 }
2129
2130 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2131 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2132 oflags |= O_RDWR;
2133 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2134 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2135 oflags |= O_WRONLY;
2136 *may_flags = MAY_OPEN | MAY_WRITE;
2137 } else {
2138 oflags |= O_RDONLY;
2139 *may_flags = MAY_OPEN | MAY_READ;
2140 }
2141
2142 if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2143 oflags |= O_PATH;
2144
2145 if (file_present) {
2146 switch (disposition & FILE_CREATE_MASK_LE) {
2147 case FILE_OPEN_LE:
2148 case FILE_CREATE_LE:
2149 break;
2150 case FILE_SUPERSEDE_LE:
2151 case FILE_OVERWRITE_LE:
2152 case FILE_OVERWRITE_IF_LE:
2153 oflags |= O_TRUNC;
2154 break;
2155 default:
2156 break;
2157 }
2158 } else {
2159 switch (disposition & FILE_CREATE_MASK_LE) {
2160 case FILE_SUPERSEDE_LE:
2161 case FILE_CREATE_LE:
2162 case FILE_OPEN_IF_LE:
2163 case FILE_OVERWRITE_IF_LE:
2164 oflags |= O_CREAT;
2165 break;
2166 case FILE_OPEN_LE:
2167 case FILE_OVERWRITE_LE:
2168 oflags &= ~O_CREAT;
2169 break;
2170 default:
2171 break;
2172 }
2173 }
2174
2175 return oflags;
2176 }
2177
2178 /**
2179 * smb2_tree_disconnect() - handler for smb tree connect request
2180 * @work: smb work containing request buffer
2181 *
2182 * Return: 0 on success, otherwise error
2183 */
2184 int smb2_tree_disconnect(struct ksmbd_work *work)
2185 {
2186 struct smb2_tree_disconnect_rsp *rsp;
2187 struct smb2_tree_disconnect_req *req;
2188 struct ksmbd_session *sess = work->sess;
2189 struct ksmbd_tree_connect *tcon = work->tcon;
2190 int err;
2191
2192 ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
2193
2194 WORK_BUFFERS(work, req, rsp);
2195
2196 if (!tcon) {
2197 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2198
2199 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2200 err = -ENOENT;
2201 goto err_out;
2202 }
2203
2204 ksmbd_close_tree_conn_fds(work);
2205
2206 down_write(&sess->tree_conns_lock);
2207 if (tcon->t_state == TREE_DISCONNECTED) {
2208 up_write(&sess->tree_conns_lock);
2209 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2210 err = -ENOENT;
2211 goto err_out;
2212 }
2213
2214 tcon->t_state = TREE_DISCONNECTED;
2215 up_write(&sess->tree_conns_lock);
2216
2217 err = ksmbd_tree_conn_disconnect(sess, tcon);
2218 if (err) {
2219 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2220 goto err_out;
2221 }
2222
2223 rsp->StructureSize = cpu_to_le16(4);
2224 err = ksmbd_iov_pin_rsp(work, rsp,
2225 sizeof(struct smb2_tree_disconnect_rsp));
2226 if (err) {
2227 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2228 goto err_out;
2229 }
2230
2231 return 0;
2232
2233 err_out:
2234 smb2_set_err_rsp(work);
2235 return err;
2236
2237 }
2238
2239 /**
2240 * smb2_session_logoff() - handler for session log off request
2241 * @work: smb work containing request buffer
2242 *
2243 * Return: 0 on success, otherwise error
2244 */
2245 int smb2_session_logoff(struct ksmbd_work *work)
2246 {
2247 struct ksmbd_conn *conn = work->conn;
2248 struct ksmbd_session *sess = work->sess;
2249 struct smb2_logoff_req *req;
2250 struct smb2_logoff_rsp *rsp;
2251 u64 sess_id;
2252 int err;
2253
2254 WORK_BUFFERS(work, req, rsp);
2255
2256 ksmbd_debug(SMB, "Received smb2 session logoff request\n");
2257
2258 ksmbd_conn_lock(conn);
2259 if (!ksmbd_conn_good(conn)) {
2260 ksmbd_conn_unlock(conn);
2261 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2262 smb2_set_err_rsp(work);
2263 return -ENOENT;
2264 }
2265 sess_id = le64_to_cpu(req->hdr.SessionId);
2266 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2267 ksmbd_conn_unlock(conn);
2268
2269 ksmbd_close_session_fds(work);
2270 ksmbd_conn_wait_idle(conn);
2271
2272 if (ksmbd_tree_conn_session_logoff(sess)) {
2273 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2274 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2275 smb2_set_err_rsp(work);
2276 return -ENOENT;
2277 }
2278
2279 down_write(&conn->session_lock);
2280 sess->state = SMB2_SESSION_EXPIRED;
2281 up_write(&conn->session_lock);
2282
2283 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_SETUP);
2284
2285 rsp->StructureSize = cpu_to_le16(4);
2286 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2287 if (err) {
2288 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2289 smb2_set_err_rsp(work);
2290 return err;
2291 }
2292 return 0;
2293 }
2294
2295 /**
2296 * create_smb2_pipe() - create IPC pipe
2297 * @work: smb work containing request buffer
2298 *
2299 * Return: 0 on success, otherwise error
2300 */
2301 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2302 {
2303 struct smb2_create_rsp *rsp;
2304 struct smb2_create_req *req;
2305 int id = -1;
2306 int err;
2307 char *name;
2308
2309 WORK_BUFFERS(work, req, rsp);
2310
2311 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2312 1, work->conn->local_nls);
2313 if (IS_ERR(name)) {
2314 rsp->hdr.Status = STATUS_NO_MEMORY;
2315 err = PTR_ERR(name);
2316 goto out;
2317 }
2318
2319 id = ksmbd_session_rpc_open(work->sess, name);
2320 if (id < 0) {
2321 pr_err("Unable to open RPC pipe: %d\n", id);
2322 err = id;
2323 goto out;
2324 }
2325
2326 rsp->hdr.Status = STATUS_SUCCESS;
2327 rsp->StructureSize = cpu_to_le16(89);
2328 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2329 rsp->Flags = 0;
2330 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2331
2332 rsp->CreationTime = cpu_to_le64(0);
2333 rsp->LastAccessTime = cpu_to_le64(0);
2334 rsp->ChangeTime = cpu_to_le64(0);
2335 rsp->AllocationSize = cpu_to_le64(0);
2336 rsp->EndofFile = cpu_to_le64(0);
2337 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2338 rsp->Reserved2 = 0;
2339 rsp->VolatileFileId = id;
2340 rsp->PersistentFileId = 0;
2341 rsp->CreateContextsOffset = 0;
2342 rsp->CreateContextsLength = 0;
2343
2344 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2345 if (err)
2346 goto out;
2347
2348 kfree(name);
2349 return 0;
2350
2351 out:
2352 switch (err) {
2353 case -EINVAL:
2354 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2355 break;
2356 case -ENOSPC:
2357 case -ENOMEM:
2358 rsp->hdr.Status = STATUS_NO_MEMORY;
2359 break;
2360 }
2361
2362 if (id >= 0)
2363 ksmbd_session_rpc_close(work->sess, id);
2364
2365 if (!IS_ERR(name))
2366 kfree(name);
2367
2368 smb2_set_err_rsp(work);
2369 return err;
2370 }
2371
2372 /**
2373 * smb2_set_ea() - handler for setting extended attributes using set
2374 * info command
2375 * @eabuf: set info command buffer
2376 * @buf_len: set info command buffer length
2377 * @path: dentry path for get ea
2378 * @get_write: get write access to a mount
2379 *
2380 * Return: 0 on success, otherwise error
2381 */
2382 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2383 const struct path *path, bool get_write)
2384 {
2385 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2386 char *attr_name = NULL, *value;
2387 int rc = 0;
2388 unsigned int next = 0;
2389
2390 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2391 le16_to_cpu(eabuf->EaValueLength))
2392 return -EINVAL;
2393
2394 attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
2395 if (!attr_name)
2396 return -ENOMEM;
2397
2398 do {
2399 if (!eabuf->EaNameLength)
2400 goto next;
2401
2402 ksmbd_debug(SMB,
2403 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2404 eabuf->name, eabuf->EaNameLength,
2405 le16_to_cpu(eabuf->EaValueLength),
2406 le32_to_cpu(eabuf->NextEntryOffset));
2407
2408 if (eabuf->EaNameLength >
2409 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2410 rc = -EINVAL;
2411 break;
2412 }
2413
2414 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2415 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2416 eabuf->EaNameLength);
2417 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2418 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2419
2420 if (!eabuf->EaValueLength) {
2421 rc = ksmbd_vfs_casexattr_len(idmap,
2422 path->dentry,
2423 attr_name,
2424 XATTR_USER_PREFIX_LEN +
2425 eabuf->EaNameLength);
2426
2427 /* delete the EA only when it exits */
2428 if (rc > 0) {
2429 rc = ksmbd_vfs_remove_xattr(idmap,
2430 path,
2431 attr_name,
2432 get_write);
2433
2434 if (rc < 0) {
2435 ksmbd_debug(SMB,
2436 "remove xattr failed(%d)\n",
2437 rc);
2438 break;
2439 }
2440 }
2441
2442 /* if the EA doesn't exist, just do nothing. */
2443 rc = 0;
2444 } else {
2445 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2446 le16_to_cpu(eabuf->EaValueLength),
2447 0, get_write);
2448 if (rc < 0) {
2449 ksmbd_debug(SMB,
2450 "ksmbd_vfs_setxattr is failed(%d)\n",
2451 rc);
2452 break;
2453 }
2454 }
2455
2456 next:
2457 next = le32_to_cpu(eabuf->NextEntryOffset);
2458 if (next == 0 || buf_len < next)
2459 break;
2460 buf_len -= next;
2461 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2462 if (buf_len < sizeof(struct smb2_ea_info)) {
2463 rc = -EINVAL;
2464 break;
2465 }
2466
2467 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2468 le16_to_cpu(eabuf->EaValueLength)) {
2469 rc = -EINVAL;
2470 break;
2471 }
2472 } while (next != 0);
2473
2474 kfree(attr_name);
2475 return rc;
2476 }
2477
2478 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2479 struct ksmbd_file *fp,
2480 char *stream_name, int s_type)
2481 {
2482 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2483 size_t xattr_stream_size;
2484 char *xattr_stream_name;
2485 int rc;
2486
2487 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2488 &xattr_stream_name,
2489 &xattr_stream_size,
2490 s_type);
2491 if (rc)
2492 return rc;
2493
2494 fp->stream.name = xattr_stream_name;
2495 fp->stream.size = xattr_stream_size;
2496
2497 /* Check if there is stream prefix in xattr space */
2498 rc = ksmbd_vfs_casexattr_len(idmap,
2499 path->dentry,
2500 xattr_stream_name,
2501 xattr_stream_size);
2502 if (rc >= 0)
2503 return 0;
2504
2505 if (fp->cdoption == FILE_OPEN_LE) {
2506 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2507 return -EBADF;
2508 }
2509
2510 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2511 if (rc < 0)
2512 pr_err("Failed to store XATTR stream name :%d\n", rc);
2513 return 0;
2514 }
2515
2516 static int smb2_remove_smb_xattrs(const struct path *path)
2517 {
2518 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2519 char *name, *xattr_list = NULL;
2520 ssize_t xattr_list_len;
2521 int err = 0;
2522
2523 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2524 if (xattr_list_len < 0) {
2525 goto out;
2526 } else if (!xattr_list_len) {
2527 ksmbd_debug(SMB, "empty xattr in the file\n");
2528 goto out;
2529 }
2530
2531 for (name = xattr_list; name - xattr_list < xattr_list_len;
2532 name += strlen(name) + 1) {
2533 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2534
2535 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2536 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2537 STREAM_PREFIX_LEN)) {
2538 err = ksmbd_vfs_remove_xattr(idmap, path,
2539 name, true);
2540 if (err)
2541 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2542 name);
2543 }
2544 }
2545 out:
2546 kvfree(xattr_list);
2547 return err;
2548 }
2549
2550 static int smb2_create_truncate(const struct path *path)
2551 {
2552 int rc = vfs_truncate(path, 0);
2553
2554 if (rc) {
2555 pr_err("vfs_truncate failed, rc %d\n", rc);
2556 return rc;
2557 }
2558
2559 rc = smb2_remove_smb_xattrs(path);
2560 if (rc == -EOPNOTSUPP)
2561 rc = 0;
2562 if (rc)
2563 ksmbd_debug(SMB,
2564 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2565 rc);
2566 return rc;
2567 }
2568
2569 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2570 struct ksmbd_file *fp)
2571 {
2572 struct xattr_dos_attrib da = {0};
2573 int rc;
2574
2575 if (!test_share_config_flag(tcon->share_conf,
2576 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2577 return;
2578
2579 da.version = 4;
2580 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2581 da.itime = da.create_time = fp->create_time;
2582 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2583 XATTR_DOSINFO_ITIME;
2584
2585 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2586 if (rc)
2587 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2588 }
2589
2590 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2591 const struct path *path, struct ksmbd_file *fp)
2592 {
2593 struct xattr_dos_attrib da;
2594 int rc;
2595
2596 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2597
2598 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2599 if (!test_share_config_flag(tcon->share_conf,
2600 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2601 return;
2602
2603 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2604 path->dentry, &da);
2605 if (rc > 0) {
2606 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2607 fp->create_time = da.create_time;
2608 fp->itime = da.itime;
2609 }
2610 }
2611
2612 static int smb2_creat(struct ksmbd_work *work,
2613 struct path *path, char *name, int open_flags,
2614 umode_t posix_mode, bool is_dir)
2615 {
2616 struct ksmbd_tree_connect *tcon = work->tcon;
2617 struct ksmbd_share_config *share = tcon->share_conf;
2618 umode_t mode;
2619 int rc;
2620
2621 if (!(open_flags & O_CREAT))
2622 return -EBADF;
2623
2624 ksmbd_debug(SMB, "file does not exist, so creating\n");
2625 if (is_dir == true) {
2626 ksmbd_debug(SMB, "creating directory\n");
2627
2628 mode = share_config_directory_mode(share, posix_mode);
2629 rc = ksmbd_vfs_mkdir(work, name, mode);
2630 if (rc)
2631 return rc;
2632 } else {
2633 ksmbd_debug(SMB, "creating regular file\n");
2634
2635 mode = share_config_create_mode(share, posix_mode);
2636 rc = ksmbd_vfs_create(work, name, mode);
2637 if (rc)
2638 return rc;
2639 }
2640
2641 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2642 if (rc) {
2643 pr_err("cannot get linux path (%s), err = %d\n",
2644 name, rc);
2645 return rc;
2646 }
2647 return 0;
2648 }
2649
2650 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2651 struct smb2_create_req *req,
2652 const struct path *path)
2653 {
2654 struct create_context *context;
2655 struct create_sd_buf_req *sd_buf;
2656
2657 if (!req->CreateContextsOffset)
2658 return -ENOENT;
2659
2660 /* Parse SD BUFFER create contexts */
2661 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2662 if (!context)
2663 return -ENOENT;
2664 else if (IS_ERR(context))
2665 return PTR_ERR(context);
2666
2667 ksmbd_debug(SMB,
2668 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2669 sd_buf = (struct create_sd_buf_req *)context;
2670 if (le16_to_cpu(context->DataOffset) +
2671 le32_to_cpu(context->DataLength) <
2672 sizeof(struct create_sd_buf_req))
2673 return -EINVAL;
2674 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2675 le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2676 }
2677
2678 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2679 struct mnt_idmap *idmap,
2680 struct inode *inode)
2681 {
2682 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2683 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2684
2685 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2686 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2687 fattr->cf_mode = inode->i_mode;
2688 fattr->cf_acls = NULL;
2689 fattr->cf_dacls = NULL;
2690
2691 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2692 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2693 if (S_ISDIR(inode->i_mode))
2694 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2695 }
2696 }
2697
2698 enum {
2699 DURABLE_RECONN_V2 = 1,
2700 DURABLE_RECONN,
2701 DURABLE_REQ_V2,
2702 DURABLE_REQ,
2703 };
2704
2705 struct durable_info {
2706 struct ksmbd_file *fp;
2707 unsigned short int type;
2708 bool persistent;
2709 bool reconnected;
2710 unsigned int timeout;
2711 char *CreateGuid;
2712 };
2713
2714 static int parse_durable_handle_context(struct ksmbd_work *work,
2715 struct smb2_create_req *req,
2716 struct lease_ctx_info *lc,
2717 struct durable_info *dh_info)
2718 {
2719 struct ksmbd_conn *conn = work->conn;
2720 struct create_context *context;
2721 int dh_idx, err = 0;
2722 u64 persistent_id = 0;
2723 int req_op_level;
2724 static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
2725
2726 req_op_level = req->RequestedOplockLevel;
2727 for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
2728 dh_idx++) {
2729 context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
2730 if (IS_ERR(context)) {
2731 err = PTR_ERR(context);
2732 goto out;
2733 }
2734 if (!context)
2735 continue;
2736
2737 switch (dh_idx) {
2738 case DURABLE_RECONN_V2:
2739 {
2740 struct create_durable_handle_reconnect_v2 *recon_v2;
2741
2742 if (dh_info->type == DURABLE_RECONN ||
2743 dh_info->type == DURABLE_REQ_V2) {
2744 err = -EINVAL;
2745 goto out;
2746 }
2747
2748 if (le16_to_cpu(context->DataOffset) +
2749 le32_to_cpu(context->DataLength) <
2750 sizeof(struct create_durable_handle_reconnect_v2)) {
2751 err = -EINVAL;
2752 goto out;
2753 }
2754
2755 recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
2756 persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
2757 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2758 if (!dh_info->fp) {
2759 ksmbd_debug(SMB, "Failed to get durable handle state\n");
2760 err = -EBADF;
2761 goto out;
2762 }
2763
2764 if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
2765 SMB2_CREATE_GUID_SIZE)) {
2766 err = -EBADF;
2767 ksmbd_put_durable_fd(dh_info->fp);
2768 goto out;
2769 }
2770
2771 dh_info->type = dh_idx;
2772 dh_info->reconnected = true;
2773 ksmbd_debug(SMB,
2774 "reconnect v2 Persistent-id from reconnect = %llu\n",
2775 persistent_id);
2776 break;
2777 }
2778 case DURABLE_RECONN:
2779 {
2780 create_durable_reconn_t *recon;
2781
2782 if (dh_info->type == DURABLE_RECONN_V2 ||
2783 dh_info->type == DURABLE_REQ_V2) {
2784 err = -EINVAL;
2785 goto out;
2786 }
2787
2788 if (le16_to_cpu(context->DataOffset) +
2789 le32_to_cpu(context->DataLength) <
2790 sizeof(create_durable_reconn_t)) {
2791 err = -EINVAL;
2792 goto out;
2793 }
2794
2795 recon = (create_durable_reconn_t *)context;
2796 persistent_id = recon->Data.Fid.PersistentFileId;
2797 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2798 if (!dh_info->fp) {
2799 ksmbd_debug(SMB, "Failed to get durable handle state\n");
2800 err = -EBADF;
2801 goto out;
2802 }
2803
2804 dh_info->type = dh_idx;
2805 dh_info->reconnected = true;
2806 ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
2807 persistent_id);
2808 break;
2809 }
2810 case DURABLE_REQ_V2:
2811 {
2812 struct create_durable_req_v2 *durable_v2_blob;
2813
2814 if (dh_info->type == DURABLE_RECONN ||
2815 dh_info->type == DURABLE_RECONN_V2) {
2816 err = -EINVAL;
2817 goto out;
2818 }
2819
2820 if (le16_to_cpu(context->DataOffset) +
2821 le32_to_cpu(context->DataLength) <
2822 sizeof(struct create_durable_req_v2)) {
2823 err = -EINVAL;
2824 goto out;
2825 }
2826
2827 durable_v2_blob =
2828 (struct create_durable_req_v2 *)context;
2829 ksmbd_debug(SMB, "Request for durable v2 open\n");
2830 dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
2831 if (dh_info->fp) {
2832 if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
2833 SMB2_CLIENT_GUID_SIZE)) {
2834 if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
2835 err = -ENOEXEC;
2836 ksmbd_put_durable_fd(dh_info->fp);
2837 goto out;
2838 }
2839
2840 if (dh_info->fp->conn) {
2841 ksmbd_put_durable_fd(dh_info->fp);
2842 err = -EBADF;
2843 goto out;
2844 }
2845 dh_info->reconnected = true;
2846 goto out;
2847 }
2848 ksmbd_put_durable_fd(dh_info->fp);
2849 dh_info->fp = NULL;
2850 }
2851
2852 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2853 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2854 dh_info->CreateGuid =
2855 durable_v2_blob->dcontext.CreateGuid;
2856 dh_info->persistent =
2857 le32_to_cpu(durable_v2_blob->dcontext.Flags);
2858 dh_info->timeout =
2859 le32_to_cpu(durable_v2_blob->dcontext.Timeout);
2860 dh_info->type = dh_idx;
2861 }
2862 break;
2863 }
2864 case DURABLE_REQ:
2865 if (dh_info->type == DURABLE_RECONN)
2866 goto out;
2867 if (dh_info->type == DURABLE_RECONN_V2 ||
2868 dh_info->type == DURABLE_REQ_V2) {
2869 err = -EINVAL;
2870 goto out;
2871 }
2872
2873 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2874 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2875 ksmbd_debug(SMB, "Request for durable open\n");
2876 dh_info->type = dh_idx;
2877 }
2878 }
2879 }
2880
2881 out:
2882 return err;
2883 }
2884
2885 /**
2886 * smb2_open() - handler for smb file open request
2887 * @work: smb work containing request buffer
2888 *
2889 * Return: 0 on success, otherwise error
2890 */
2891 int smb2_open(struct ksmbd_work *work)
2892 {
2893 struct ksmbd_conn *conn = work->conn;
2894 struct ksmbd_session *sess = work->sess;
2895 struct ksmbd_tree_connect *tcon = work->tcon;
2896 struct smb2_create_req *req;
2897 struct smb2_create_rsp *rsp;
2898 struct path path;
2899 struct ksmbd_share_config *share = tcon->share_conf;
2900 struct ksmbd_file *fp = NULL;
2901 struct file *filp = NULL;
2902 struct mnt_idmap *idmap = NULL;
2903 struct kstat stat;
2904 struct create_context *context;
2905 struct lease_ctx_info *lc = NULL;
2906 struct create_ea_buf_req *ea_buf = NULL;
2907 struct oplock_info *opinfo;
2908 struct durable_info dh_info = {0};
2909 __le32 *next_ptr = NULL;
2910 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2911 int rc = 0;
2912 int contxt_cnt = 0, query_disk_id = 0;
2913 bool maximal_access_ctxt = false, posix_ctxt = false;
2914 int s_type = 0;
2915 int next_off = 0;
2916 char *name = NULL;
2917 char *stream_name = NULL;
2918 bool file_present = false, created = false, already_permitted = false;
2919 int share_ret, need_truncate = 0;
2920 u64 time;
2921 umode_t posix_mode = 0;
2922 __le32 daccess, maximal_access = 0;
2923 int iov_len = 0;
2924
2925 ksmbd_debug(SMB, "Received smb2 create request\n");
2926
2927 WORK_BUFFERS(work, req, rsp);
2928
2929 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2930 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2931 ksmbd_debug(SMB, "invalid flag in chained command\n");
2932 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2933 smb2_set_err_rsp(work);
2934 return -EINVAL;
2935 }
2936
2937 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2938 ksmbd_debug(SMB, "IPC pipe create request\n");
2939 return create_smb2_pipe(work);
2940 }
2941
2942 if (req->CreateContextsOffset && tcon->posix_extensions) {
2943 context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
2944 if (IS_ERR(context)) {
2945 rc = PTR_ERR(context);
2946 goto err_out2;
2947 } else if (context) {
2948 struct create_posix *posix = (struct create_posix *)context;
2949
2950 if (le16_to_cpu(context->DataOffset) +
2951 le32_to_cpu(context->DataLength) <
2952 sizeof(struct create_posix) - 4) {
2953 rc = -EINVAL;
2954 goto err_out2;
2955 }
2956 ksmbd_debug(SMB, "get posix context\n");
2957
2958 posix_mode = le32_to_cpu(posix->Mode);
2959 posix_ctxt = true;
2960 }
2961 }
2962
2963 if (req->NameLength) {
2964 name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
2965 le16_to_cpu(req->NameLength),
2966 work->conn->local_nls);
2967 if (IS_ERR(name)) {
2968 rc = PTR_ERR(name);
2969 name = NULL;
2970 goto err_out2;
2971 }
2972
2973 ksmbd_debug(SMB, "converted name = %s\n", name);
2974
2975 if (posix_ctxt == false) {
2976 if (strchr(name, ':')) {
2977 if (!test_share_config_flag(work->tcon->share_conf,
2978 KSMBD_SHARE_FLAG_STREAMS)) {
2979 rc = -EBADF;
2980 goto err_out2;
2981 }
2982 rc = parse_stream_name(name, &stream_name, &s_type);
2983 if (rc < 0)
2984 goto err_out2;
2985 }
2986
2987 rc = ksmbd_validate_filename(name);
2988 if (rc < 0)
2989 goto err_out2;
2990 }
2991
2992 if (ksmbd_share_veto_filename(share, name)) {
2993 rc = -ENOENT;
2994 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2995 name);
2996 goto err_out2;
2997 }
2998 } else {
2999 name = kstrdup("", KSMBD_DEFAULT_GFP);
3000 if (!name) {
3001 rc = -ENOMEM;
3002 goto err_out2;
3003 }
3004 }
3005
3006 req_op_level = req->RequestedOplockLevel;
3007
3008 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
3009 req->CreateContextsOffset) {
3010 lc = parse_lease_state(req);
3011 rc = parse_durable_handle_context(work, req, lc, &dh_info);
3012 if (rc) {
3013 ksmbd_debug(SMB, "error parsing durable handle context\n");
3014 goto err_out2;
3015 }
3016
3017 if (dh_info.reconnected == true) {
3018 rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
3019 lc, sess->user, name);
3020 if (rc)
3021 goto err_out2;
3022
3023 rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
3024 if (rc)
3025 goto err_out2;
3026
3027 fp = dh_info.fp;
3028
3029 if (ksmbd_override_fsids(work)) {
3030 rc = -ENOMEM;
3031 goto err_out2;
3032 }
3033
3034 file_info = FILE_OPENED;
3035
3036 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3037 if (rc)
3038 goto err_out2;
3039
3040 goto reconnected_fp;
3041 }
3042 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3043 lc = parse_lease_state(req);
3044
3045 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3046 pr_err("Invalid impersonationlevel : 0x%x\n",
3047 le32_to_cpu(req->ImpersonationLevel));
3048 rc = -EIO;
3049 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3050 goto err_out2;
3051 }
3052
3053 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3054 pr_err("Invalid create options : 0x%x\n",
3055 le32_to_cpu(req->CreateOptions));
3056 rc = -EINVAL;
3057 goto err_out2;
3058 } else {
3059 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3060 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3061 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
3062
3063 if (req->CreateOptions &
3064 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3065 FILE_RESERVE_OPFILTER_LE)) {
3066 rc = -EOPNOTSUPP;
3067 goto err_out2;
3068 }
3069
3070 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3071 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3072 rc = -EINVAL;
3073 goto err_out2;
3074 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3075 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
3076 }
3077 }
3078 }
3079
3080 if (le32_to_cpu(req->CreateDisposition) >
3081 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3082 pr_err("Invalid create disposition : 0x%x\n",
3083 le32_to_cpu(req->CreateDisposition));
3084 rc = -EINVAL;
3085 goto err_out2;
3086 }
3087
3088 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3089 pr_err("Invalid desired access : 0x%x\n",
3090 le32_to_cpu(req->DesiredAccess));
3091 rc = -EACCES;
3092 goto err_out2;
3093 }
3094
3095 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
3096 pr_err("Invalid file attribute : 0x%x\n",
3097 le32_to_cpu(req->FileAttributes));
3098 rc = -EINVAL;
3099 goto err_out2;
3100 }
3101
3102 if (req->CreateContextsOffset) {
3103 /* Parse non-durable handle create contexts */
3104 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3105 if (IS_ERR(context)) {
3106 rc = PTR_ERR(context);
3107 goto err_out2;
3108 } else if (context) {
3109 ea_buf = (struct create_ea_buf_req *)context;
3110 if (le16_to_cpu(context->DataOffset) +
3111 le32_to_cpu(context->DataLength) <
3112 sizeof(struct create_ea_buf_req)) {
3113 rc = -EINVAL;
3114 goto err_out2;
3115 }
3116 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3117 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3118 rc = -EACCES;
3119 goto err_out2;
3120 }
3121 }
3122
3123 context = smb2_find_context_vals(req,
3124 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3125 if (IS_ERR(context)) {
3126 rc = PTR_ERR(context);
3127 goto err_out2;
3128 } else if (context) {
3129 ksmbd_debug(SMB,
3130 "get query maximal access context\n");
3131 maximal_access_ctxt = 1;
3132 }
3133
3134 context = smb2_find_context_vals(req,
3135 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3136 if (IS_ERR(context)) {
3137 rc = PTR_ERR(context);
3138 goto err_out2;
3139 } else if (context) {
3140 ksmbd_debug(SMB, "get timewarp context\n");
3141 rc = -EBADF;
3142 goto err_out2;
3143 }
3144 }
3145
3146 if (ksmbd_override_fsids(work)) {
3147 rc = -ENOMEM;
3148 goto err_out2;
3149 }
3150
3151 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3152 &path, 1);
3153 if (!rc) {
3154 file_present = true;
3155
3156 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3157 /*
3158 * If file exists with under flags, return access
3159 * denied error.
3160 */
3161 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3162 req->CreateDisposition == FILE_OPEN_IF_LE) {
3163 rc = -EACCES;
3164 goto err_out;
3165 }
3166
3167 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3168 ksmbd_debug(SMB,
3169 "User does not have write permission\n");
3170 rc = -EACCES;
3171 goto err_out;
3172 }
3173 } else if (d_is_symlink(path.dentry)) {
3174 rc = -EACCES;
3175 goto err_out;
3176 }
3177
3178 idmap = mnt_idmap(path.mnt);
3179 } else {
3180 if (rc != -ENOENT)
3181 goto err_out;
3182 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3183 name, rc);
3184 rc = 0;
3185 }
3186
3187 if (stream_name) {
3188 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3189 if (s_type == DATA_STREAM) {
3190 rc = -EIO;
3191 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3192 }
3193 } else {
3194 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3195 s_type == DATA_STREAM) {
3196 rc = -EIO;
3197 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3198 }
3199 }
3200
3201 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3202 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3203 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3204 rc = -EIO;
3205 }
3206
3207 if (rc < 0)
3208 goto err_out;
3209 }
3210
3211 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3212 S_ISDIR(d_inode(path.dentry)->i_mode) &&
3213 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3214 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3215 name, req->CreateOptions);
3216 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3217 rc = -EIO;
3218 goto err_out;
3219 }
3220
3221 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3222 !(req->CreateDisposition == FILE_CREATE_LE) &&
3223 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3224 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3225 rc = -EIO;
3226 goto err_out;
3227 }
3228
3229 if (!stream_name && file_present &&
3230 req->CreateDisposition == FILE_CREATE_LE) {
3231 rc = -EEXIST;
3232 goto err_out;
3233 }
3234
3235 daccess = smb_map_generic_desired_access(req->DesiredAccess);
3236
3237 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3238 rc = smb_check_perm_dacl(conn, &path, &daccess,
3239 sess->user->uid);
3240 if (rc)
3241 goto err_out;
3242 }
3243
3244 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3245 if (!file_present) {
3246 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3247 } else {
3248 ksmbd_vfs_query_maximal_access(idmap,
3249 path.dentry,
3250 &daccess);
3251 already_permitted = true;
3252 }
3253 maximal_access = daccess;
3254 }
3255
3256 open_flags = smb2_create_open_flags(file_present, daccess,
3257 req->CreateDisposition,
3258 &may_flags,
3259 req->CreateOptions,
3260 file_present ? d_inode(path.dentry)->i_mode : 0);
3261
3262 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3263 if (open_flags & (O_CREAT | O_TRUNC)) {
3264 ksmbd_debug(SMB,
3265 "User does not have write permission\n");
3266 rc = -EACCES;
3267 goto err_out;
3268 }
3269 }
3270
3271 /*create file if not present */
3272 if (!file_present) {
3273 rc = smb2_creat(work, &path, name, open_flags,
3274 posix_mode,
3275 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3276 if (rc) {
3277 if (rc == -ENOENT) {
3278 rc = -EIO;
3279 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3280 }
3281 goto err_out;
3282 }
3283
3284 created = true;
3285 idmap = mnt_idmap(path.mnt);
3286 if (ea_buf) {
3287 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3288 sizeof(struct smb2_ea_info)) {
3289 rc = -EINVAL;
3290 goto err_out;
3291 }
3292
3293 rc = smb2_set_ea(&ea_buf->ea,
3294 le32_to_cpu(ea_buf->ccontext.DataLength),
3295 &path, false);
3296 if (rc == -EOPNOTSUPP)
3297 rc = 0;
3298 else if (rc)
3299 goto err_out;
3300 }
3301 } else if (!already_permitted) {
3302 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3303 * because execute(search) permission on a parent directory,
3304 * is already granted.
3305 */
3306 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3307 rc = inode_permission(idmap,
3308 d_inode(path.dentry),
3309 may_flags);
3310 if (rc)
3311 goto err_out;
3312
3313 if ((daccess & FILE_DELETE_LE) ||
3314 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3315 rc = inode_permission(idmap,
3316 d_inode(path.dentry->d_parent),
3317 MAY_EXEC | MAY_WRITE);
3318 if (rc)
3319 goto err_out;
3320 }
3321 }
3322 }
3323
3324 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3325 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3326 rc = -EBUSY;
3327 goto err_out;
3328 }
3329
3330 rc = 0;
3331 filp = dentry_open(&path, open_flags, current_cred());
3332 if (IS_ERR(filp)) {
3333 rc = PTR_ERR(filp);
3334 pr_err("dentry open for dir failed, rc %d\n", rc);
3335 goto err_out;
3336 }
3337
3338 if (file_present) {
3339 if (!(open_flags & O_TRUNC))
3340 file_info = FILE_OPENED;
3341 else
3342 file_info = FILE_OVERWRITTEN;
3343
3344 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3345 FILE_SUPERSEDE_LE)
3346 file_info = FILE_SUPERSEDED;
3347 } else if (open_flags & O_CREAT) {
3348 file_info = FILE_CREATED;
3349 }
3350
3351 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3352
3353 /* Obtain Volatile-ID */
3354 fp = ksmbd_open_fd(work, filp);
3355 if (IS_ERR(fp)) {
3356 fput(filp);
3357 rc = PTR_ERR(fp);
3358 fp = NULL;
3359 goto err_out;
3360 }
3361
3362 /* Get Persistent-ID */
3363 ksmbd_open_durable_fd(fp);
3364 if (!has_file_id(fp->persistent_id)) {
3365 rc = -ENOMEM;
3366 goto err_out;
3367 }
3368
3369 fp->cdoption = req->CreateDisposition;
3370 fp->daccess = daccess;
3371 fp->saccess = req->ShareAccess;
3372 fp->coption = req->CreateOptions;
3373
3374 /* Set default windows and posix acls if creating new file */
3375 if (created) {
3376 int posix_acl_rc;
3377 struct inode *inode = d_inode(path.dentry);
3378
3379 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3380 &path,
3381 d_inode(path.dentry->d_parent));
3382 if (posix_acl_rc)
3383 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3384
3385 if (test_share_config_flag(work->tcon->share_conf,
3386 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3387 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3388 sess->user->gid);
3389 }
3390
3391 if (rc) {
3392 rc = smb2_create_sd_buffer(work, req, &path);
3393 if (rc) {
3394 if (posix_acl_rc)
3395 ksmbd_vfs_set_init_posix_acl(idmap,
3396 &path);
3397
3398 if (test_share_config_flag(work->tcon->share_conf,
3399 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3400 struct smb_fattr fattr;
3401 struct smb_ntsd *pntsd;
3402 int pntsd_size;
3403 size_t scratch_len;
3404
3405 ksmbd_acls_fattr(&fattr, idmap, inode);
3406 scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
3407 NULL, 0,
3408 OWNER_SECINFO | GROUP_SECINFO |
3409 DACL_SECINFO);
3410 if (!scratch_len || scratch_len == SIZE_MAX) {
3411 rc = -EFBIG;
3412 posix_acl_release(fattr.cf_acls);
3413 posix_acl_release(fattr.cf_dacls);
3414 goto err_out;
3415 }
3416
3417 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
3418 if (!pntsd) {
3419 rc = -ENOMEM;
3420 posix_acl_release(fattr.cf_acls);
3421 posix_acl_release(fattr.cf_dacls);
3422 goto err_out;
3423 }
3424
3425 rc = build_sec_desc(idmap,
3426 pntsd, NULL, 0,
3427 OWNER_SECINFO |
3428 GROUP_SECINFO |
3429 DACL_SECINFO,
3430 &pntsd_size, &fattr);
3431 posix_acl_release(fattr.cf_acls);
3432 posix_acl_release(fattr.cf_dacls);
3433 if (rc) {
3434 kvfree(pntsd);
3435 goto err_out;
3436 }
3437
3438 rc = ksmbd_vfs_set_sd_xattr(conn,
3439 idmap,
3440 &path,
3441 pntsd,
3442 pntsd_size,
3443 false);
3444 kvfree(pntsd);
3445 if (rc)
3446 pr_err("failed to store ntacl in xattr : %d\n",
3447 rc);
3448 }
3449 }
3450 }
3451 rc = 0;
3452 }
3453
3454 if (stream_name) {
3455 rc = smb2_set_stream_name_xattr(&path,
3456 fp,
3457 stream_name,
3458 s_type);
3459 if (rc)
3460 goto err_out;
3461 file_info = FILE_CREATED;
3462 }
3463
3464 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3465 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3466
3467 fp->is_posix_ctxt = posix_ctxt;
3468
3469 /* fp should be searchable through ksmbd_inode.m_fp_list
3470 * after daccess, saccess, attrib_only, and stream are
3471 * initialized.
3472 */
3473 down_write(&fp->f_ci->m_lock);
3474 list_add(&fp->node, &fp->f_ci->m_fp_list);
3475 up_write(&fp->f_ci->m_lock);
3476
3477 /* Check delete pending among previous fp before oplock break */
3478 if (ksmbd_inode_pending_delete(fp)) {
3479 rc = -EBUSY;
3480 goto err_out;
3481 }
3482
3483 if (file_present || created)
3484 path_put(&path);
3485
3486 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3487 !fp->attrib_only && !stream_name) {
3488 smb_break_all_oplock(work, fp);
3489 need_truncate = 1;
3490 }
3491
3492 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3493 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3494 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3495 !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3496 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3497 rc = share_ret;
3498 goto err_out1;
3499 }
3500 } else {
3501 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3502 if (S_ISDIR(file_inode(filp)->i_mode)) {
3503 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3504 lc->is_dir = true;
3505 }
3506
3507 /*
3508 * Compare parent lease using parent key. If there is no
3509 * a lease that has same parent key, Send lease break
3510 * notification.
3511 */
3512 smb_send_parent_lease_break_noti(fp, lc);
3513
3514 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3515 ksmbd_debug(SMB,
3516 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3517 name, req_op_level, lc->req_state);
3518 rc = find_same_lease_key(sess, fp->f_ci, lc);
3519 if (rc)
3520 goto err_out1;
3521 } else if (open_flags == O_RDONLY &&
3522 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3523 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3524 req_op_level = SMB2_OPLOCK_LEVEL_II;
3525
3526 rc = smb_grant_oplock(work, req_op_level,
3527 fp->persistent_id, fp,
3528 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3529 lc, share_ret);
3530 if (rc < 0)
3531 goto err_out1;
3532 }
3533
3534 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3535 ksmbd_fd_set_delete_on_close(fp, file_info);
3536
3537 if (need_truncate) {
3538 rc = smb2_create_truncate(&fp->filp->f_path);
3539 if (rc)
3540 goto err_out1;
3541 }
3542
3543 if (req->CreateContextsOffset) {
3544 struct create_alloc_size_req *az_req;
3545
3546 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3547 SMB2_CREATE_ALLOCATION_SIZE, 4);
3548 if (IS_ERR(az_req)) {
3549 rc = PTR_ERR(az_req);
3550 goto err_out1;
3551 } else if (az_req) {
3552 loff_t alloc_size;
3553 int err;
3554
3555 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3556 le32_to_cpu(az_req->ccontext.DataLength) <
3557 sizeof(struct create_alloc_size_req)) {
3558 rc = -EINVAL;
3559 goto err_out1;
3560 }
3561 alloc_size = le64_to_cpu(az_req->AllocationSize);
3562 ksmbd_debug(SMB,
3563 "request smb2 create allocate size : %llu\n",
3564 alloc_size);
3565 smb_break_all_levII_oplock(work, fp, 1);
3566 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3567 alloc_size);
3568 if (err < 0)
3569 ksmbd_debug(SMB,
3570 "vfs_fallocate is failed : %d\n",
3571 err);
3572 }
3573
3574 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3575 if (IS_ERR(context)) {
3576 rc = PTR_ERR(context);
3577 goto err_out1;
3578 } else if (context) {
3579 ksmbd_debug(SMB, "get query on disk id context\n");
3580 query_disk_id = 1;
3581 }
3582
3583 if (conn->is_aapl == false) {
3584 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3585 if (IS_ERR(context)) {
3586 rc = PTR_ERR(context);
3587 goto err_out1;
3588 } else if (context)
3589 conn->is_aapl = true;
3590 }
3591 }
3592
3593 rc = ksmbd_vfs_getattr(&path, &stat);
3594 if (rc)
3595 goto err_out1;
3596
3597 if (stat.result_mask & STATX_BTIME)
3598 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3599 else
3600 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3601 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3602 fp->f_ci->m_fattr =
3603 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3604
3605 if (!created)
3606 smb2_update_xattrs(tcon, &path, fp);
3607 else
3608 smb2_new_xattrs(tcon, &path, fp);
3609
3610 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3611
3612 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3613 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3614 test_share_config_flag(work->tcon->share_conf,
3615 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3616 fp->is_persistent = true;
3617 else
3618 fp->is_durable = true;
3619
3620 if (dh_info.type == DURABLE_REQ_V2) {
3621 memcpy(fp->create_guid, dh_info.CreateGuid,
3622 SMB2_CREATE_GUID_SIZE);
3623 if (dh_info.timeout)
3624 fp->durable_timeout =
3625 min_t(unsigned int, dh_info.timeout,
3626 DURABLE_HANDLE_MAX_TIMEOUT);
3627 else
3628 fp->durable_timeout = 60;
3629 }
3630 }
3631
3632 reconnected_fp:
3633 rsp->StructureSize = cpu_to_le16(89);
3634 opinfo = opinfo_get(fp);
3635 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3636 rsp->Flags = 0;
3637 rsp->CreateAction = cpu_to_le32(file_info);
3638 rsp->CreationTime = cpu_to_le64(fp->create_time);
3639 time = ksmbd_UnixTimeToNT(stat.atime);
3640 rsp->LastAccessTime = cpu_to_le64(time);
3641 time = ksmbd_UnixTimeToNT(stat.mtime);
3642 rsp->LastWriteTime = cpu_to_le64(time);
3643 time = ksmbd_UnixTimeToNT(stat.ctime);
3644 rsp->ChangeTime = cpu_to_le64(time);
3645 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3646 cpu_to_le64(stat.blocks << 9);
3647 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3648 rsp->FileAttributes = fp->f_ci->m_fattr;
3649
3650 rsp->Reserved2 = 0;
3651
3652 rsp->PersistentFileId = fp->persistent_id;
3653 rsp->VolatileFileId = fp->volatile_id;
3654
3655 rsp->CreateContextsOffset = 0;
3656 rsp->CreateContextsLength = 0;
3657 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3658
3659 /* If lease is request send lease context response */
3660 if (opinfo && opinfo->is_lease) {
3661 struct create_context *lease_ccontext;
3662
3663 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3664 name, opinfo->o_lease->state);
3665 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3666
3667 lease_ccontext = (struct create_context *)rsp->Buffer;
3668 contxt_cnt++;
3669 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3670 le32_add_cpu(&rsp->CreateContextsLength,
3671 conn->vals->create_lease_size);
3672 iov_len += conn->vals->create_lease_size;
3673 next_ptr = &lease_ccontext->Next;
3674 next_off = conn->vals->create_lease_size;
3675 }
3676 opinfo_put(opinfo);
3677
3678 if (maximal_access_ctxt) {
3679 struct create_context *mxac_ccontext;
3680
3681 if (maximal_access == 0)
3682 ksmbd_vfs_query_maximal_access(idmap,
3683 path.dentry,
3684 &maximal_access);
3685 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3686 le32_to_cpu(rsp->CreateContextsLength));
3687 contxt_cnt++;
3688 create_mxac_rsp_buf(rsp->Buffer +
3689 le32_to_cpu(rsp->CreateContextsLength),
3690 le32_to_cpu(maximal_access));
3691 le32_add_cpu(&rsp->CreateContextsLength,
3692 conn->vals->create_mxac_size);
3693 iov_len += conn->vals->create_mxac_size;
3694 if (next_ptr)
3695 *next_ptr = cpu_to_le32(next_off);
3696 next_ptr = &mxac_ccontext->Next;
3697 next_off = conn->vals->create_mxac_size;
3698 }
3699
3700 if (query_disk_id) {
3701 struct create_context *disk_id_ccontext;
3702
3703 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3704 le32_to_cpu(rsp->CreateContextsLength));
3705 contxt_cnt++;
3706 create_disk_id_rsp_buf(rsp->Buffer +
3707 le32_to_cpu(rsp->CreateContextsLength),
3708 stat.ino, tcon->id);
3709 le32_add_cpu(&rsp->CreateContextsLength,
3710 conn->vals->create_disk_id_size);
3711 iov_len += conn->vals->create_disk_id_size;
3712 if (next_ptr)
3713 *next_ptr = cpu_to_le32(next_off);
3714 next_ptr = &disk_id_ccontext->Next;
3715 next_off = conn->vals->create_disk_id_size;
3716 }
3717
3718 if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3719 struct create_context *durable_ccontext;
3720
3721 durable_ccontext = (struct create_context *)(rsp->Buffer +
3722 le32_to_cpu(rsp->CreateContextsLength));
3723 contxt_cnt++;
3724 if (dh_info.type == DURABLE_REQ) {
3725 create_durable_rsp_buf(rsp->Buffer +
3726 le32_to_cpu(rsp->CreateContextsLength));
3727 le32_add_cpu(&rsp->CreateContextsLength,
3728 conn->vals->create_durable_size);
3729 iov_len += conn->vals->create_durable_size;
3730 } else {
3731 create_durable_v2_rsp_buf(rsp->Buffer +
3732 le32_to_cpu(rsp->CreateContextsLength),
3733 fp);
3734 le32_add_cpu(&rsp->CreateContextsLength,
3735 conn->vals->create_durable_v2_size);
3736 iov_len += conn->vals->create_durable_v2_size;
3737 }
3738
3739 if (next_ptr)
3740 *next_ptr = cpu_to_le32(next_off);
3741 next_ptr = &durable_ccontext->Next;
3742 next_off = conn->vals->create_durable_size;
3743 }
3744
3745 if (posix_ctxt) {
3746 contxt_cnt++;
3747 create_posix_rsp_buf(rsp->Buffer +
3748 le32_to_cpu(rsp->CreateContextsLength),
3749 fp);
3750 le32_add_cpu(&rsp->CreateContextsLength,
3751 conn->vals->create_posix_size);
3752 iov_len += conn->vals->create_posix_size;
3753 if (next_ptr)
3754 *next_ptr = cpu_to_le32(next_off);
3755 }
3756
3757 if (contxt_cnt > 0) {
3758 rsp->CreateContextsOffset =
3759 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3760 }
3761
3762 err_out:
3763 if (rc && (file_present || created))
3764 path_put(&path);
3765
3766 err_out1:
3767 ksmbd_revert_fsids(work);
3768
3769 err_out2:
3770 if (!rc) {
3771 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3772 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3773 }
3774 if (rc) {
3775 if (rc == -EINVAL)
3776 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3777 else if (rc == -EOPNOTSUPP)
3778 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3779 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3780 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3781 else if (rc == -ENOENT)
3782 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3783 else if (rc == -EPERM)
3784 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3785 else if (rc == -EBUSY)
3786 rsp->hdr.Status = STATUS_DELETE_PENDING;
3787 else if (rc == -EBADF)
3788 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3789 else if (rc == -ENOEXEC)
3790 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3791 else if (rc == -ENXIO)
3792 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3793 else if (rc == -EEXIST)
3794 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3795 else if (rc == -EMFILE)
3796 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3797 if (!rsp->hdr.Status)
3798 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3799
3800 if (fp)
3801 ksmbd_fd_put(work, fp);
3802 smb2_set_err_rsp(work);
3803 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3804 }
3805
3806 if (dh_info.reconnected) {
3807 /*
3808 * If reconnect succeeded, fp was republished in the
3809 * session file table. On a later error, ksmbd_fd_put()
3810 * above drops the session reference; drop the durable
3811 * lookup reference through the same session-aware path so
3812 * final close removes the volatile id before freeing fp.
3813 */
3814 if (rc && fp == dh_info.fp)
3815 ksmbd_fd_put(work, dh_info.fp);
3816 else
3817 ksmbd_put_durable_fd(dh_info.fp);
3818 }
3819
3820 kfree(name);
3821 kfree(lc);
3822
3823 return rc;
3824 }
3825
3826 static int readdir_info_level_struct_sz(int info_level)
3827 {
3828 switch (info_level) {
3829 case FILE_FULL_DIRECTORY_INFORMATION:
3830 return sizeof(FILE_FULL_DIRECTORY_INFO);
3831 case FILE_BOTH_DIRECTORY_INFORMATION:
3832 return sizeof(FILE_BOTH_DIRECTORY_INFO);
3833 case FILE_DIRECTORY_INFORMATION:
3834 return sizeof(FILE_DIRECTORY_INFO);
3835 case FILE_NAMES_INFORMATION:
3836 return sizeof(struct file_names_info);
3837 case FILEID_FULL_DIRECTORY_INFORMATION:
3838 return sizeof(FILE_ID_FULL_DIR_INFO);
3839 case FILEID_BOTH_DIRECTORY_INFORMATION:
3840 return sizeof(struct file_id_both_directory_info);
3841 case SMB_FIND_FILE_POSIX_INFO:
3842 return sizeof(struct smb2_posix_info);
3843 default:
3844 return -EOPNOTSUPP;
3845 }
3846 }
3847
3848 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3849 {
3850 switch (info_level) {
3851 case FILE_FULL_DIRECTORY_INFORMATION:
3852 {
3853 FILE_FULL_DIRECTORY_INFO *ffdinfo;
3854
3855 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
3856 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3857 d_info->name = ffdinfo->FileName;
3858 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3859 return 0;
3860 }
3861 case FILE_BOTH_DIRECTORY_INFORMATION:
3862 {
3863 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3864
3865 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
3866 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3867 d_info->name = fbdinfo->FileName;
3868 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3869 return 0;
3870 }
3871 case FILE_DIRECTORY_INFORMATION:
3872 {
3873 FILE_DIRECTORY_INFO *fdinfo;
3874
3875 fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
3876 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3877 d_info->name = fdinfo->FileName;
3878 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3879 return 0;
3880 }
3881 case FILE_NAMES_INFORMATION:
3882 {
3883 struct file_names_info *fninfo;
3884
3885 fninfo = (struct file_names_info *)d_info->rptr;
3886 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3887 d_info->name = fninfo->FileName;
3888 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3889 return 0;
3890 }
3891 case FILEID_FULL_DIRECTORY_INFORMATION:
3892 {
3893 FILE_ID_FULL_DIR_INFO *dinfo;
3894
3895 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
3896 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3897 d_info->name = dinfo->FileName;
3898 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3899 return 0;
3900 }
3901 case FILEID_BOTH_DIRECTORY_INFORMATION:
3902 {
3903 struct file_id_both_directory_info *fibdinfo;
3904
3905 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3906 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3907 d_info->name = fibdinfo->FileName;
3908 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3909 return 0;
3910 }
3911 case SMB_FIND_FILE_POSIX_INFO:
3912 {
3913 struct smb2_posix_info *posix_info;
3914
3915 posix_info = (struct smb2_posix_info *)d_info->rptr;
3916 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3917 d_info->name = posix_info->name;
3918 d_info->name_len = le32_to_cpu(posix_info->name_len);
3919 return 0;
3920 }
3921 default:
3922 return -EINVAL;
3923 }
3924 }
3925
3926 /**
3927 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3928 * buffer
3929 * @conn: connection instance
3930 * @info_level: smb information level
3931 * @d_info: structure included variables for query dir
3932 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3933 *
3934 * if directory has many entries, find first can't read it fully.
3935 * find next might be called multiple times to read remaining dir entries
3936 *
3937 * Return: 0 on success, otherwise error
3938 */
3939 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3940 struct ksmbd_dir_info *d_info,
3941 struct ksmbd_kstat *ksmbd_kstat)
3942 {
3943 int next_entry_offset = 0;
3944 char *conv_name;
3945 int conv_len;
3946 void *kstat;
3947 int struct_sz, rc = 0;
3948
3949 conv_name = ksmbd_convert_dir_info_name(d_info,
3950 conn->local_nls,
3951 &conv_len);
3952 if (!conv_name)
3953 return -ENOMEM;
3954
3955 /* Somehow the name has only terminating NULL bytes */
3956 if (conv_len < 0) {
3957 rc = -EINVAL;
3958 goto free_conv_name;
3959 }
3960
3961 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3962 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3963 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3964
3965 if (next_entry_offset > d_info->out_buf_len) {
3966 d_info->out_buf_len = 0;
3967 rc = -ENOSPC;
3968 goto free_conv_name;
3969 }
3970
3971 kstat = d_info->wptr;
3972 if (info_level != FILE_NAMES_INFORMATION)
3973 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3974
3975 switch (info_level) {
3976 case FILE_FULL_DIRECTORY_INFORMATION:
3977 {
3978 FILE_FULL_DIRECTORY_INFO *ffdinfo;
3979
3980 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
3981 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3982 ffdinfo->EaSize =
3983 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3984 if (ffdinfo->EaSize)
3985 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3986 if (d_info->hide_dot_file && d_info->name[0] == '.')
3987 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3988 memcpy(ffdinfo->FileName, conv_name, conv_len);
3989 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3990 break;
3991 }
3992 case FILE_BOTH_DIRECTORY_INFORMATION:
3993 {
3994 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3995
3996 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
3997 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3998 fbdinfo->EaSize =
3999 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4000 if (fbdinfo->EaSize)
4001 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4002 fbdinfo->ShortNameLength = 0;
4003 fbdinfo->Reserved = 0;
4004 if (d_info->hide_dot_file && d_info->name[0] == '.')
4005 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4006 memcpy(fbdinfo->FileName, conv_name, conv_len);
4007 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4008 break;
4009 }
4010 case FILE_DIRECTORY_INFORMATION:
4011 {
4012 FILE_DIRECTORY_INFO *fdinfo;
4013
4014 fdinfo = (FILE_DIRECTORY_INFO *)kstat;
4015 fdinfo->FileNameLength = cpu_to_le32(conv_len);
4016 if (d_info->hide_dot_file && d_info->name[0] == '.')
4017 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4018 memcpy(fdinfo->FileName, conv_name, conv_len);
4019 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4020 break;
4021 }
4022 case FILE_NAMES_INFORMATION:
4023 {
4024 struct file_names_info *fninfo;
4025
4026 fninfo = (struct file_names_info *)kstat;
4027 fninfo->FileNameLength = cpu_to_le32(conv_len);
4028 memcpy(fninfo->FileName, conv_name, conv_len);
4029 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4030 break;
4031 }
4032 case FILEID_FULL_DIRECTORY_INFORMATION:
4033 {
4034 FILE_ID_FULL_DIR_INFO *dinfo;
4035
4036 dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
4037 dinfo->FileNameLength = cpu_to_le32(conv_len);
4038 dinfo->EaSize =
4039 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4040 if (dinfo->EaSize)
4041 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4042 dinfo->Reserved = 0;
4043 if (conn->is_aapl)
4044 dinfo->UniqueId = 0;
4045 else
4046 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4047 if (d_info->hide_dot_file && d_info->name[0] == '.')
4048 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4049 memcpy(dinfo->FileName, conv_name, conv_len);
4050 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4051 break;
4052 }
4053 case FILEID_BOTH_DIRECTORY_INFORMATION:
4054 {
4055 struct file_id_both_directory_info *fibdinfo;
4056
4057 fibdinfo = (struct file_id_both_directory_info *)kstat;
4058 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4059 fibdinfo->EaSize =
4060 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4061 if (fibdinfo->EaSize)
4062 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4063 if (conn->is_aapl)
4064 fibdinfo->UniqueId = 0;
4065 else
4066 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4067 fibdinfo->ShortNameLength = 0;
4068 fibdinfo->Reserved = 0;
4069 fibdinfo->Reserved2 = cpu_to_le16(0);
4070 if (d_info->hide_dot_file && d_info->name[0] == '.')
4071 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4072 memcpy(fibdinfo->FileName, conv_name, conv_len);
4073 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4074 break;
4075 }
4076 case SMB_FIND_FILE_POSIX_INFO:
4077 {
4078 struct smb2_posix_info *posix_info;
4079 u64 time;
4080
4081 posix_info = (struct smb2_posix_info *)kstat;
4082 posix_info->Ignored = 0;
4083 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4084 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4085 posix_info->ChangeTime = cpu_to_le64(time);
4086 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4087 posix_info->LastAccessTime = cpu_to_le64(time);
4088 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4089 posix_info->LastWriteTime = cpu_to_le64(time);
4090 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4091 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4092 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4093 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4094 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4095 switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4096 case S_IFDIR:
4097 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4098 break;
4099 case S_IFLNK:
4100 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4101 break;
4102 case S_IFCHR:
4103 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4104 break;
4105 case S_IFBLK:
4106 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4107 break;
4108 case S_IFIFO:
4109 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4110 break;
4111 case S_IFSOCK:
4112 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4113 }
4114
4115 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4116 posix_info->DosAttributes =
4117 S_ISDIR(ksmbd_kstat->kstat->mode) ?
4118 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4119 if (d_info->hide_dot_file && d_info->name[0] == '.')
4120 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4121 /*
4122 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4123 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4124 * sub_auth(4 * 1(num_subauth)) + RID(4).
4125 */
4126 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4127 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4128 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4129 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4130 memcpy(posix_info->name, conv_name, conv_len);
4131 posix_info->name_len = cpu_to_le32(conv_len);
4132 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4133 break;
4134 }
4135
4136 } /* switch (info_level) */
4137
4138 d_info->last_entry_offset = d_info->data_count;
4139 d_info->data_count += next_entry_offset;
4140 d_info->out_buf_len -= next_entry_offset;
4141 d_info->wptr += next_entry_offset;
4142
4143 ksmbd_debug(SMB,
4144 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4145 info_level, d_info->out_buf_len,
4146 next_entry_offset, d_info->data_count);
4147
4148 free_conv_name:
4149 kfree(conv_name);
4150 return rc;
4151 }
4152
4153 struct smb2_query_dir_private {
4154 struct ksmbd_work *work;
4155 char *search_pattern;
4156 struct ksmbd_file *dir_fp;
4157
4158 struct ksmbd_dir_info *d_info;
4159 int info_level;
4160 };
4161
4162 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4163 {
4164 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
4165 struct kstat kstat;
4166 struct ksmbd_kstat ksmbd_kstat;
4167 int rc;
4168 int i;
4169
4170 for (i = 0; i < priv->d_info->num_entry; i++) {
4171 struct dentry *dent;
4172
4173 if (dentry_name(priv->d_info, priv->info_level))
4174 return -EINVAL;
4175
4176 dent = lookup_one_unlocked(idmap,
4177 &QSTR_LEN(priv->d_info->name,
4178 priv->d_info->name_len),
4179 priv->dir_fp->filp->f_path.dentry);
4180
4181 if (IS_ERR(dent)) {
4182 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4183 priv->d_info->name,
4184 PTR_ERR(dent));
4185 continue;
4186 }
4187 if (unlikely(d_is_negative(dent))) {
4188 dput(dent);
4189 ksmbd_debug(SMB, "Negative dentry `%s'\n",
4190 priv->d_info->name);
4191 continue;
4192 }
4193
4194 ksmbd_kstat.kstat = &kstat;
4195 if (priv->info_level != FILE_NAMES_INFORMATION) {
4196 rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4197 idmap,
4198 dent,
4199 &ksmbd_kstat);
4200 if (rc) {
4201 dput(dent);
4202 continue;
4203 }
4204 }
4205
4206 rc = smb2_populate_readdir_entry(priv->work->conn,
4207 priv->info_level,
4208 priv->d_info,
4209 &ksmbd_kstat);
4210 dput(dent);
4211 if (rc)
4212 return rc;
4213 }
4214 return 0;
4215 }
4216
4217 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4218 int info_level)
4219 {
4220 int struct_sz;
4221 int conv_len;
4222 int next_entry_offset;
4223
4224 struct_sz = readdir_info_level_struct_sz(info_level);
4225 if (struct_sz == -EOPNOTSUPP)
4226 return -EOPNOTSUPP;
4227
4228 conv_len = (d_info->name_len + 1) * 2;
4229 next_entry_offset = ALIGN(struct_sz + conv_len,
4230 KSMBD_DIR_INFO_ALIGNMENT);
4231
4232 if (next_entry_offset > d_info->out_buf_len) {
4233 d_info->out_buf_len = 0;
4234 return -ENOSPC;
4235 }
4236
4237 switch (info_level) {
4238 case FILE_FULL_DIRECTORY_INFORMATION:
4239 {
4240 FILE_FULL_DIRECTORY_INFO *ffdinfo;
4241
4242 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
4243 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4244 ffdinfo->FileName[d_info->name_len] = 0x00;
4245 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4246 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4247 break;
4248 }
4249 case FILE_BOTH_DIRECTORY_INFORMATION:
4250 {
4251 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4252
4253 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
4254 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4255 fbdinfo->FileName[d_info->name_len] = 0x00;
4256 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4257 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4258 break;
4259 }
4260 case FILE_DIRECTORY_INFORMATION:
4261 {
4262 FILE_DIRECTORY_INFO *fdinfo;
4263
4264 fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
4265 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4266 fdinfo->FileName[d_info->name_len] = 0x00;
4267 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4268 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4269 break;
4270 }
4271 case FILE_NAMES_INFORMATION:
4272 {
4273 struct file_names_info *fninfo;
4274
4275 fninfo = (struct file_names_info *)d_info->wptr;
4276 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4277 fninfo->FileName[d_info->name_len] = 0x00;
4278 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4279 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4280 break;
4281 }
4282 case FILEID_FULL_DIRECTORY_INFORMATION:
4283 {
4284 FILE_ID_FULL_DIR_INFO *dinfo;
4285
4286 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
4287 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4288 dinfo->FileName[d_info->name_len] = 0x00;
4289 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4290 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4291 break;
4292 }
4293 case FILEID_BOTH_DIRECTORY_INFORMATION:
4294 {
4295 struct file_id_both_directory_info *fibdinfo;
4296
4297 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4298 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4299 fibdinfo->FileName[d_info->name_len] = 0x00;
4300 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4301 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4302 break;
4303 }
4304 case SMB_FIND_FILE_POSIX_INFO:
4305 {
4306 struct smb2_posix_info *posix_info;
4307
4308 posix_info = (struct smb2_posix_info *)d_info->wptr;
4309 memcpy(posix_info->name, d_info->name, d_info->name_len);
4310 posix_info->name[d_info->name_len] = 0x00;
4311 posix_info->name_len = cpu_to_le32(d_info->name_len);
4312 posix_info->NextEntryOffset =
4313 cpu_to_le32(next_entry_offset);
4314 break;
4315 }
4316 } /* switch (info_level) */
4317
4318 d_info->num_entry++;
4319 d_info->out_buf_len -= next_entry_offset;
4320 d_info->wptr += next_entry_offset;
4321 return 0;
4322 }
4323
4324 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4325 loff_t offset, u64 ino, unsigned int d_type)
4326 {
4327 struct ksmbd_readdir_data *buf;
4328 struct smb2_query_dir_private *priv;
4329 struct ksmbd_dir_info *d_info;
4330 int rc;
4331
4332 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
4333 priv = buf->private;
4334 d_info = priv->d_info;
4335
4336 /* dot and dotdot entries are already reserved */
4337 if (!strcmp(".", name) || !strcmp("..", name))
4338 return true;
4339 d_info->num_scan++;
4340 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4341 return true;
4342 if (!match_pattern(name, namlen, priv->search_pattern))
4343 return true;
4344
4345 d_info->name = name;
4346 d_info->name_len = namlen;
4347 rc = reserve_populate_dentry(d_info, priv->info_level);
4348 if (rc)
4349 return false;
4350 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4351 d_info->out_buf_len = 0;
4352 return true;
4353 }
4354
4355 static int verify_info_level(int info_level)
4356 {
4357 switch (info_level) {
4358 case FILE_FULL_DIRECTORY_INFORMATION:
4359 case FILE_BOTH_DIRECTORY_INFORMATION:
4360 case FILE_DIRECTORY_INFORMATION:
4361 case FILE_NAMES_INFORMATION:
4362 case FILEID_FULL_DIRECTORY_INFORMATION:
4363 case FILEID_BOTH_DIRECTORY_INFORMATION:
4364 case SMB_FIND_FILE_POSIX_INFO:
4365 break;
4366 default:
4367 return -EOPNOTSUPP;
4368 }
4369
4370 return 0;
4371 }
4372
4373 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4374 {
4375 int free_len;
4376
4377 free_len = (int)(work->response_sz -
4378 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4379 return free_len;
4380 }
4381
4382 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4383 unsigned short hdr2_len,
4384 unsigned int out_buf_len)
4385 {
4386 int free_len;
4387
4388 if (out_buf_len > work->conn->vals->max_trans_size)
4389 return -EINVAL;
4390
4391 free_len = smb2_resp_buf_len(work, hdr2_len);
4392 if (free_len < 0)
4393 return -EINVAL;
4394
4395 return min_t(int, out_buf_len, free_len);
4396 }
4397
4398 int smb2_query_dir(struct ksmbd_work *work)
4399 {
4400 struct ksmbd_conn *conn = work->conn;
4401 struct smb2_query_directory_req *req;
4402 struct smb2_query_directory_rsp *rsp;
4403 struct ksmbd_share_config *share = work->tcon->share_conf;
4404 struct ksmbd_file *dir_fp = NULL;
4405 struct ksmbd_dir_info d_info;
4406 int rc = 0;
4407 char *srch_ptr = NULL;
4408 unsigned char srch_flag;
4409 int buffer_sz;
4410 struct smb2_query_dir_private query_dir_private = {NULL, };
4411
4412 ksmbd_debug(SMB, "Received smb2 query directory request\n");
4413
4414 WORK_BUFFERS(work, req, rsp);
4415
4416 if (ksmbd_override_fsids(work)) {
4417 rsp->hdr.Status = STATUS_NO_MEMORY;
4418 smb2_set_err_rsp(work);
4419 return -ENOMEM;
4420 }
4421
4422 rc = verify_info_level(req->FileInformationClass);
4423 if (rc) {
4424 rc = -EFAULT;
4425 goto err_out2;
4426 }
4427
4428 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4429 if (!dir_fp) {
4430 rc = -EBADF;
4431 goto err_out2;
4432 }
4433
4434 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4435 inode_permission(file_mnt_idmap(dir_fp->filp),
4436 file_inode(dir_fp->filp),
4437 MAY_READ | MAY_EXEC)) {
4438 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4439 rc = -EACCES;
4440 goto err_out2;
4441 }
4442
4443 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4444 pr_err("can't do query dir for a file\n");
4445 rc = -EINVAL;
4446 goto err_out2;
4447 }
4448
4449 srch_flag = req->Flags;
4450 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4451 le16_to_cpu(req->FileNameLength), 1,
4452 conn->local_nls);
4453 if (IS_ERR(srch_ptr)) {
4454 ksmbd_debug(SMB, "Search Pattern not found\n");
4455 rc = -EINVAL;
4456 goto err_out2;
4457 } else {
4458 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4459 }
4460
4461 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4462 ksmbd_debug(SMB, "Restart directory scan\n");
4463 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4464 }
4465
4466 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4467 d_info.wptr = (char *)rsp->Buffer;
4468 d_info.rptr = (char *)rsp->Buffer;
4469 d_info.out_buf_len =
4470 smb2_calc_max_out_buf_len(work,
4471 offsetof(struct smb2_query_directory_rsp, Buffer),
4472 le32_to_cpu(req->OutputBufferLength));
4473 if (d_info.out_buf_len < 0) {
4474 rc = -EINVAL;
4475 goto err_out;
4476 }
4477 d_info.flags = srch_flag;
4478
4479 /*
4480 * reserve dot and dotdot entries in head of buffer
4481 * in first response
4482 */
4483 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4484 dir_fp, &d_info, srch_ptr,
4485 smb2_populate_readdir_entry);
4486 if (rc == -ENOSPC)
4487 rc = 0;
4488 else if (rc)
4489 goto err_out;
4490
4491 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4492 d_info.hide_dot_file = true;
4493
4494 buffer_sz = d_info.out_buf_len;
4495 d_info.rptr = d_info.wptr;
4496 query_dir_private.work = work;
4497 query_dir_private.search_pattern = srch_ptr;
4498 query_dir_private.dir_fp = dir_fp;
4499 query_dir_private.d_info = &d_info;
4500 query_dir_private.info_level = req->FileInformationClass;
4501 dir_fp->readdir_data.private = &query_dir_private;
4502 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4503 again:
4504 d_info.num_scan = 0;
4505 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4506 /*
4507 * num_entry can be 0 if the directory iteration stops before reaching
4508 * the end of the directory and no file is matched with the search
4509 * pattern.
4510 */
4511 if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4512 d_info.out_buf_len > 0)
4513 goto again;
4514 /*
4515 * req->OutputBufferLength is too small to contain even one entry.
4516 * In this case, it immediately returns OutputBufferLength 0 to client.
4517 */
4518 if (!d_info.out_buf_len && !d_info.num_entry)
4519 goto no_buf_len;
4520 if (rc > 0 || rc == -ENOSPC)
4521 rc = 0;
4522 else if (rc)
4523 goto err_out;
4524
4525 d_info.wptr = d_info.rptr;
4526 d_info.out_buf_len = buffer_sz;
4527 rc = process_query_dir_entries(&query_dir_private);
4528 if (rc)
4529 goto err_out;
4530
4531 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4532 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4533 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4534 } else {
4535 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4536 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4537 }
4538 rsp->StructureSize = cpu_to_le16(9);
4539 rsp->OutputBufferOffset = cpu_to_le16(0);
4540 rsp->OutputBufferLength = cpu_to_le32(0);
4541 rsp->Buffer[0] = 0;
4542 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4543 offsetof(struct smb2_query_directory_rsp, Buffer)
4544 + 1);
4545 if (rc)
4546 goto err_out;
4547 } else {
4548 no_buf_len:
4549 ((FILE_DIRECTORY_INFO *)
4550 ((char *)rsp->Buffer + d_info.last_entry_offset))
4551 ->NextEntryOffset = 0;
4552 if (d_info.data_count >= d_info.last_entry_off_align)
4553 d_info.data_count -= d_info.last_entry_off_align;
4554
4555 rsp->StructureSize = cpu_to_le16(9);
4556 rsp->OutputBufferOffset = cpu_to_le16(72);
4557 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4558 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4559 offsetof(struct smb2_query_directory_rsp, Buffer) +
4560 d_info.data_count);
4561 if (rc)
4562 goto err_out;
4563 }
4564
4565 kfree(srch_ptr);
4566 ksmbd_fd_put(work, dir_fp);
4567 ksmbd_revert_fsids(work);
4568 return 0;
4569
4570 err_out:
4571 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4572 kfree(srch_ptr);
4573
4574 err_out2:
4575 if (rc == -EINVAL)
4576 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4577 else if (rc == -EACCES)
4578 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4579 else if (rc == -ENOENT)
4580 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4581 else if (rc == -EBADF)
4582 rsp->hdr.Status = STATUS_FILE_CLOSED;
4583 else if (rc == -ENOMEM)
4584 rsp->hdr.Status = STATUS_NO_MEMORY;
4585 else if (rc == -EFAULT)
4586 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4587 else if (rc == -EIO)
4588 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4589 if (!rsp->hdr.Status)
4590 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4591
4592 smb2_set_err_rsp(work);
4593 ksmbd_fd_put(work, dir_fp);
4594 ksmbd_revert_fsids(work);
4595 return rc;
4596 }
4597
4598 /**
4599 * buffer_check_err() - helper function to check buffer errors
4600 * @reqOutputBufferLength: max buffer length expected in command response
4601 * @rsp: query info response buffer contains output buffer length
4602 * @rsp_org: base response buffer pointer in case of chained response
4603 *
4604 * Return: 0 on success, otherwise error
4605 */
4606 static int buffer_check_err(int reqOutputBufferLength,
4607 struct smb2_query_info_rsp *rsp,
4608 void *rsp_org)
4609 {
4610 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4611 pr_err("Invalid Buffer Size Requested\n");
4612 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4613 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4614 return -EINVAL;
4615 }
4616 return 0;
4617 }
4618
4619 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4620 void *rsp_org)
4621 {
4622 struct smb2_file_standard_info *sinfo;
4623
4624 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4625
4626 sinfo->AllocationSize = cpu_to_le64(4096);
4627 sinfo->EndOfFile = cpu_to_le64(0);
4628 sinfo->NumberOfLinks = cpu_to_le32(1);
4629 sinfo->DeletePending = 1;
4630 sinfo->Directory = 0;
4631 rsp->OutputBufferLength =
4632 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4633 }
4634
4635 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4636 void *rsp_org)
4637 {
4638 struct smb2_file_internal_info *file_info;
4639
4640 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4641
4642 /* any unique number */
4643 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4644 rsp->OutputBufferLength =
4645 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4646 }
4647
4648 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4649 struct smb2_query_info_req *req,
4650 struct smb2_query_info_rsp *rsp,
4651 void *rsp_org)
4652 {
4653 u64 id;
4654 int rc;
4655
4656 /*
4657 * Windows can sometime send query file info request on
4658 * pipe without opening it, checking error condition here
4659 */
4660 id = req->VolatileFileId;
4661
4662 lockdep_assert_not_held(&sess->rpc_lock);
4663
4664 down_read(&sess->rpc_lock);
4665 if (!ksmbd_session_rpc_method(sess, id)) {
4666 up_read(&sess->rpc_lock);
4667 return -ENOENT;
4668 }
4669 up_read(&sess->rpc_lock);
4670
4671 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4672 req->FileInfoClass, req->VolatileFileId);
4673
4674 switch (req->FileInfoClass) {
4675 case FILE_STANDARD_INFORMATION:
4676 get_standard_info_pipe(rsp, rsp_org);
4677 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4678 rsp, rsp_org);
4679 break;
4680 case FILE_INTERNAL_INFORMATION:
4681 get_internal_info_pipe(rsp, id, rsp_org);
4682 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4683 rsp, rsp_org);
4684 break;
4685 default:
4686 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4687 req->FileInfoClass);
4688 rc = -EOPNOTSUPP;
4689 }
4690 return rc;
4691 }
4692
4693 /**
4694 * smb2_get_ea() - handler for smb2 get extended attribute command
4695 * @work: smb work containing query info command buffer
4696 * @fp: ksmbd_file pointer
4697 * @req: get extended attribute request
4698 * @rsp: response buffer pointer
4699 * @rsp_org: base response buffer pointer in case of chained response
4700 *
4701 * Return: 0 on success, otherwise error
4702 */
4703 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4704 struct smb2_query_info_req *req,
4705 struct smb2_query_info_rsp *rsp, void *rsp_org)
4706 {
4707 struct smb2_ea_info *eainfo, *prev_eainfo;
4708 char *name, *ptr, *xattr_list = NULL, *buf;
4709 int rc, name_len, value_len, xattr_list_len, idx;
4710 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4711 struct smb2_ea_info_req *ea_req = NULL;
4712 const struct path *path;
4713 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4714
4715 if (!(fp->daccess & FILE_READ_EA_LE)) {
4716 pr_err("Not permitted to read ext attr : 0x%x\n",
4717 fp->daccess);
4718 return -EACCES;
4719 }
4720
4721 path = &fp->filp->f_path;
4722 /* single EA entry is requested with given user.* name */
4723 if (req->InputBufferLength) {
4724 if (le32_to_cpu(req->InputBufferLength) <=
4725 sizeof(struct smb2_ea_info_req))
4726 return -EINVAL;
4727
4728 ea_req = (struct smb2_ea_info_req *)((char *)req +
4729 le16_to_cpu(req->InputBufferOffset));
4730
4731 if (le32_to_cpu(req->InputBufferLength) <
4732 offsetof(struct smb2_ea_info_req, name) +
4733 ea_req->EaNameLength)
4734 return -EINVAL;
4735 } else {
4736 /* need to send all EAs, if no specific EA is requested*/
4737 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4738 ksmbd_debug(SMB,
4739 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4740 le32_to_cpu(req->Flags));
4741 }
4742
4743 buf_free_len =
4744 smb2_calc_max_out_buf_len(work,
4745 offsetof(struct smb2_query_info_rsp, Buffer),
4746 le32_to_cpu(req->OutputBufferLength));
4747 if (buf_free_len < 0)
4748 return -EINVAL;
4749
4750 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4751 if (rc < 0) {
4752 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4753 goto out;
4754 } else if (!rc) { /* there is no EA in the file */
4755 ksmbd_debug(SMB, "no ea data in the file\n");
4756 goto done;
4757 }
4758 xattr_list_len = rc;
4759
4760 ptr = (char *)rsp->Buffer;
4761 eainfo = (struct smb2_ea_info *)ptr;
4762 prev_eainfo = eainfo;
4763 idx = 0;
4764
4765 while (idx < xattr_list_len) {
4766 name = xattr_list + idx;
4767 name_len = strlen(name);
4768
4769 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4770 idx += name_len + 1;
4771
4772 /*
4773 * CIFS does not support EA other than user.* namespace,
4774 * still keep the framework generic, to list other attrs
4775 * in future.
4776 */
4777 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4778 continue;
4779
4780 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4781 STREAM_PREFIX_LEN))
4782 continue;
4783
4784 if (req->InputBufferLength &&
4785 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4786 ea_req->EaNameLength))
4787 continue;
4788
4789 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4790 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4791 continue;
4792
4793 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4794 name_len -= XATTR_USER_PREFIX_LEN;
4795
4796 ptr = eainfo->name + name_len + 1;
4797 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4798 name_len + 1);
4799 /* bailout if xattr can't fit in buf_free_len */
4800 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4801 name, &buf);
4802 if (value_len <= 0) {
4803 rc = -ENOENT;
4804 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4805 goto out;
4806 }
4807
4808 buf_free_len -= value_len;
4809 if (buf_free_len < 0) {
4810 kfree(buf);
4811 break;
4812 }
4813
4814 memcpy(ptr, buf, value_len);
4815 kfree(buf);
4816
4817 ptr += value_len;
4818 eainfo->Flags = 0;
4819 eainfo->EaNameLength = name_len;
4820
4821 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4822 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4823 name_len);
4824 else
4825 memcpy(eainfo->name, name, name_len);
4826
4827 eainfo->name[name_len] = '\0';
4828 eainfo->EaValueLength = cpu_to_le16(value_len);
4829 next_offset = offsetof(struct smb2_ea_info, name) +
4830 name_len + 1 + value_len;
4831
4832 /* align next xattr entry at 4 byte bundary */
4833 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4834 if (alignment_bytes) {
4835 if (buf_free_len < alignment_bytes)
4836 break;
4837 memset(ptr, '\0', alignment_bytes);
4838 ptr += alignment_bytes;
4839 next_offset += alignment_bytes;
4840 buf_free_len -= alignment_bytes;
4841 }
4842 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4843 prev_eainfo = eainfo;
4844 eainfo = (struct smb2_ea_info *)ptr;
4845 rsp_data_cnt += next_offset;
4846
4847 if (req->InputBufferLength) {
4848 ksmbd_debug(SMB, "single entry requested\n");
4849 break;
4850 }
4851 }
4852
4853 /* no more ea entries */
4854 prev_eainfo->NextEntryOffset = 0;
4855 done:
4856 rc = 0;
4857 if (rsp_data_cnt == 0)
4858 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4859 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4860 out:
4861 kvfree(xattr_list);
4862 return rc;
4863 }
4864
4865 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4866 struct ksmbd_file *fp, void *rsp_org)
4867 {
4868 struct smb2_file_access_info *file_info;
4869
4870 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4871 file_info->AccessFlags = fp->daccess;
4872 rsp->OutputBufferLength =
4873 cpu_to_le32(sizeof(struct smb2_file_access_info));
4874 }
4875
4876 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4877 struct ksmbd_file *fp, void *rsp_org)
4878 {
4879 struct smb2_file_basic_info *basic_info;
4880 struct kstat stat;
4881 u64 time;
4882 int ret;
4883
4884 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4885 pr_err("no right to read the attributes : 0x%x\n",
4886 fp->daccess);
4887 return -EACCES;
4888 }
4889
4890 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4891 AT_STATX_SYNC_AS_STAT);
4892 if (ret)
4893 return ret;
4894
4895 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4896 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4897 time = ksmbd_UnixTimeToNT(stat.atime);
4898 basic_info->LastAccessTime = cpu_to_le64(time);
4899 time = ksmbd_UnixTimeToNT(stat.mtime);
4900 basic_info->LastWriteTime = cpu_to_le64(time);
4901 time = ksmbd_UnixTimeToNT(stat.ctime);
4902 basic_info->ChangeTime = cpu_to_le64(time);
4903 basic_info->Attributes = fp->f_ci->m_fattr;
4904 basic_info->Pad1 = 0;
4905 rsp->OutputBufferLength =
4906 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4907 return 0;
4908 }
4909
4910 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4911 struct ksmbd_file *fp, void *rsp_org)
4912 {
4913 struct smb2_file_standard_info *sinfo;
4914 unsigned int delete_pending;
4915 struct kstat stat;
4916 int ret;
4917
4918 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4919 AT_STATX_SYNC_AS_STAT);
4920 if (ret)
4921 return ret;
4922
4923 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4924 delete_pending = ksmbd_inode_pending_delete(fp);
4925
4926 if (ksmbd_stream_fd(fp) == false) {
4927 sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4928 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4929 } else {
4930 sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
4931 sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
4932 }
4933 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4934 sinfo->DeletePending = delete_pending;
4935 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4936 rsp->OutputBufferLength =
4937 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4938
4939 return 0;
4940 }
4941
4942 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4943 void *rsp_org)
4944 {
4945 struct smb2_file_alignment_info *file_info;
4946
4947 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4948 file_info->AlignmentRequirement = 0;
4949 rsp->OutputBufferLength =
4950 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4951 }
4952
4953 static int get_file_all_info(struct ksmbd_work *work,
4954 struct smb2_query_info_rsp *rsp,
4955 struct ksmbd_file *fp,
4956 void *rsp_org)
4957 {
4958 struct ksmbd_conn *conn = work->conn;
4959 struct smb2_file_all_info *file_info;
4960 unsigned int delete_pending;
4961 struct kstat stat;
4962 int conv_len;
4963 char *filename;
4964 u64 time;
4965 int ret, buf_free_len, filename_len;
4966 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4967
4968 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4969 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4970 fp->daccess);
4971 return -EACCES;
4972 }
4973
4974 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4975 if (IS_ERR(filename))
4976 return PTR_ERR(filename);
4977
4978 filename_len = strlen(filename);
4979 buf_free_len = smb2_calc_max_out_buf_len(work,
4980 offsetof(struct smb2_query_info_rsp, Buffer) +
4981 offsetof(struct smb2_file_all_info, FileName),
4982 le32_to_cpu(req->OutputBufferLength));
4983 if (buf_free_len < (filename_len + 1) * 2) {
4984 kfree(filename);
4985 return -EINVAL;
4986 }
4987
4988 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4989 AT_STATX_SYNC_AS_STAT);
4990 if (ret) {
4991 kfree(filename);
4992 return ret;
4993 }
4994
4995 ksmbd_debug(SMB, "filename = %s\n", filename);
4996 delete_pending = ksmbd_inode_pending_delete(fp);
4997 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4998
4999 file_info->CreationTime = cpu_to_le64(fp->create_time);
5000 time = ksmbd_UnixTimeToNT(stat.atime);
5001 file_info->LastAccessTime = cpu_to_le64(time);
5002 time = ksmbd_UnixTimeToNT(stat.mtime);
5003 file_info->LastWriteTime = cpu_to_le64(time);
5004 time = ksmbd_UnixTimeToNT(stat.ctime);
5005 file_info->ChangeTime = cpu_to_le64(time);
5006 file_info->Attributes = fp->f_ci->m_fattr;
5007 file_info->Pad1 = 0;
5008 if (ksmbd_stream_fd(fp) == false) {
5009 file_info->AllocationSize =
5010 cpu_to_le64(stat.blocks << 9);
5011 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5012 } else {
5013 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5014 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5015 }
5016 file_info->NumberOfLinks =
5017 cpu_to_le32(get_nlink(&stat) - delete_pending);
5018 file_info->DeletePending = delete_pending;
5019 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5020 file_info->Pad2 = 0;
5021 file_info->IndexNumber = cpu_to_le64(stat.ino);
5022 file_info->EASize = 0;
5023 file_info->AccessFlags = fp->daccess;
5024 if (ksmbd_stream_fd(fp) == false)
5025 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5026 else
5027 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5028 file_info->Mode = fp->coption;
5029 file_info->AlignmentRequirement = 0;
5030 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
5031 min(filename_len, PATH_MAX),
5032 conn->local_nls, 0);
5033 conv_len *= 2;
5034 file_info->FileNameLength = cpu_to_le32(conv_len);
5035 rsp->OutputBufferLength =
5036 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
5037 kfree(filename);
5038 return 0;
5039 }
5040
5041 static void get_file_alternate_info(struct ksmbd_work *work,
5042 struct smb2_query_info_rsp *rsp,
5043 struct ksmbd_file *fp,
5044 void *rsp_org)
5045 {
5046 struct ksmbd_conn *conn = work->conn;
5047 struct smb2_file_alt_name_info *file_info;
5048 struct dentry *dentry = fp->filp->f_path.dentry;
5049 int conv_len;
5050
5051 spin_lock(&dentry->d_lock);
5052 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
5053 conv_len = ksmbd_extract_shortname(conn,
5054 dentry->d_name.name,
5055 file_info->FileName);
5056 spin_unlock(&dentry->d_lock);
5057 file_info->FileNameLength = cpu_to_le32(conv_len);
5058 rsp->OutputBufferLength =
5059 cpu_to_le32(struct_size(file_info, FileName, conv_len));
5060 }
5061
5062 static int get_file_stream_info(struct ksmbd_work *work,
5063 struct smb2_query_info_rsp *rsp,
5064 struct ksmbd_file *fp,
5065 void *rsp_org)
5066 {
5067 struct ksmbd_conn *conn = work->conn;
5068 struct smb2_file_stream_info *file_info;
5069 char *stream_name, *xattr_list = NULL, *stream_buf;
5070 struct kstat stat;
5071 const struct path *path = &fp->filp->f_path;
5072 ssize_t xattr_list_len;
5073 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5074 int buf_free_len;
5075 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5076 int ret;
5077
5078 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5079 AT_STATX_SYNC_AS_STAT);
5080 if (ret)
5081 return ret;
5082
5083 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5084
5085 buf_free_len =
5086 smb2_calc_max_out_buf_len(work,
5087 offsetof(struct smb2_query_info_rsp, Buffer),
5088 le32_to_cpu(req->OutputBufferLength));
5089 if (buf_free_len < 0)
5090 goto out;
5091
5092 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5093 if (xattr_list_len < 0) {
5094 goto out;
5095 } else if (!xattr_list_len) {
5096 ksmbd_debug(SMB, "empty xattr in the file\n");
5097 goto out;
5098 }
5099
5100 while (idx < xattr_list_len) {
5101 stream_name = xattr_list + idx;
5102 streamlen = strlen(stream_name);
5103 idx += streamlen + 1;
5104
5105 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5106
5107 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5108 STREAM_PREFIX, STREAM_PREFIX_LEN))
5109 continue;
5110
5111 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5112 STREAM_PREFIX_LEN);
5113 streamlen = stream_name_len;
5114
5115 /* plus : size */
5116 streamlen += 1;
5117 stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5118 if (!stream_buf)
5119 break;
5120
5121 streamlen = snprintf(stream_buf, streamlen + 1,
5122 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5123
5124 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5125 if (next > buf_free_len) {
5126 kfree(stream_buf);
5127 break;
5128 }
5129
5130 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5131 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5132 stream_buf, streamlen,
5133 conn->local_nls, 0);
5134 streamlen *= 2;
5135 kfree(stream_buf);
5136 file_info->StreamNameLength = cpu_to_le32(streamlen);
5137 file_info->StreamSize = cpu_to_le64(stream_name_len);
5138 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5139
5140 nbytes += next;
5141 buf_free_len -= next;
5142 file_info->NextEntryOffset = cpu_to_le32(next);
5143 }
5144
5145 out:
5146 if (!S_ISDIR(stat.mode) &&
5147 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5148 file_info = (struct smb2_file_stream_info *)
5149 &rsp->Buffer[nbytes];
5150 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5151 "::$DATA", 7, conn->local_nls, 0);
5152 streamlen *= 2;
5153 file_info->StreamNameLength = cpu_to_le32(streamlen);
5154 file_info->StreamSize = cpu_to_le64(stat.size);
5155 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5156 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5157 }
5158
5159 /* last entry offset should be 0 */
5160 file_info->NextEntryOffset = 0;
5161 kvfree(xattr_list);
5162
5163 rsp->OutputBufferLength = cpu_to_le32(nbytes);
5164
5165 return 0;
5166 }
5167
5168 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5169 struct ksmbd_file *fp, void *rsp_org)
5170 {
5171 struct smb2_file_internal_info *file_info;
5172 struct kstat stat;
5173 int ret;
5174
5175 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5176 AT_STATX_SYNC_AS_STAT);
5177 if (ret)
5178 return ret;
5179
5180 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5181 file_info->IndexNumber = cpu_to_le64(stat.ino);
5182 rsp->OutputBufferLength =
5183 cpu_to_le32(sizeof(struct smb2_file_internal_info));
5184
5185 return 0;
5186 }
5187
5188 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5189 struct ksmbd_file *fp, void *rsp_org)
5190 {
5191 struct smb2_file_network_open_info *file_info;
5192 struct kstat stat;
5193 u64 time;
5194 int ret;
5195
5196 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5197 pr_err("no right to read the attributes : 0x%x\n",
5198 fp->daccess);
5199 return -EACCES;
5200 }
5201
5202 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5203 AT_STATX_SYNC_AS_STAT);
5204 if (ret)
5205 return ret;
5206
5207 file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
5208
5209 file_info->CreationTime = cpu_to_le64(fp->create_time);
5210 time = ksmbd_UnixTimeToNT(stat.atime);
5211 file_info->LastAccessTime = cpu_to_le64(time);
5212 time = ksmbd_UnixTimeToNT(stat.mtime);
5213 file_info->LastWriteTime = cpu_to_le64(time);
5214 time = ksmbd_UnixTimeToNT(stat.ctime);
5215 file_info->ChangeTime = cpu_to_le64(time);
5216 file_info->Attributes = fp->f_ci->m_fattr;
5217 if (ksmbd_stream_fd(fp) == false) {
5218 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5219 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5220 } else {
5221 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5222 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5223 }
5224 file_info->Reserved = cpu_to_le32(0);
5225 rsp->OutputBufferLength =
5226 cpu_to_le32(sizeof(struct smb2_file_network_open_info));
5227 return 0;
5228 }
5229
5230 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5231 {
5232 struct smb2_file_ea_info *file_info;
5233
5234 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5235 file_info->EASize = 0;
5236 rsp->OutputBufferLength =
5237 cpu_to_le32(sizeof(struct smb2_file_ea_info));
5238 }
5239
5240 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5241 struct ksmbd_file *fp, void *rsp_org)
5242 {
5243 struct smb2_file_pos_info *file_info;
5244
5245 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5246 if (ksmbd_stream_fd(fp) == false)
5247 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5248 else
5249 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5250
5251 rsp->OutputBufferLength =
5252 cpu_to_le32(sizeof(struct smb2_file_pos_info));
5253 }
5254
5255 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5256 struct ksmbd_file *fp, void *rsp_org)
5257 {
5258 struct smb2_file_mode_info *file_info;
5259
5260 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5261 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5262 rsp->OutputBufferLength =
5263 cpu_to_le32(sizeof(struct smb2_file_mode_info));
5264 }
5265
5266 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5267 struct ksmbd_file *fp, void *rsp_org)
5268 {
5269 struct smb2_file_comp_info *file_info;
5270 struct kstat stat;
5271 int ret;
5272
5273 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5274 AT_STATX_SYNC_AS_STAT);
5275 if (ret)
5276 return ret;
5277
5278 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5279 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5280 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5281 file_info->CompressionUnitShift = 0;
5282 file_info->ChunkShift = 0;
5283 file_info->ClusterShift = 0;
5284 memset(&file_info->Reserved[0], 0, 3);
5285
5286 rsp->OutputBufferLength =
5287 cpu_to_le32(sizeof(struct smb2_file_comp_info));
5288
5289 return 0;
5290 }
5291
5292 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5293 struct ksmbd_file *fp, void *rsp_org)
5294 {
5295 struct smb2_file_attr_tag_info *file_info;
5296
5297 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5298 pr_err("no right to read the attributes : 0x%x\n",
5299 fp->daccess);
5300 return -EACCES;
5301 }
5302
5303 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5304 file_info->FileAttributes = fp->f_ci->m_fattr;
5305 file_info->ReparseTag = 0;
5306 rsp->OutputBufferLength =
5307 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5308 return 0;
5309 }
5310
5311 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5312 struct ksmbd_file *fp, void *rsp_org)
5313 {
5314 struct smb311_posix_qinfo *file_info;
5315 struct inode *inode = file_inode(fp->filp);
5316 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5317 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5318 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5319 struct kstat stat;
5320 u64 time;
5321 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5322 int ret;
5323
5324 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5325 AT_STATX_SYNC_AS_STAT);
5326 if (ret)
5327 return ret;
5328
5329 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5330 file_info->CreationTime = cpu_to_le64(fp->create_time);
5331 time = ksmbd_UnixTimeToNT(stat.atime);
5332 file_info->LastAccessTime = cpu_to_le64(time);
5333 time = ksmbd_UnixTimeToNT(stat.mtime);
5334 file_info->LastWriteTime = cpu_to_le64(time);
5335 time = ksmbd_UnixTimeToNT(stat.ctime);
5336 file_info->ChangeTime = cpu_to_le64(time);
5337 file_info->DosAttributes = fp->f_ci->m_fattr;
5338 file_info->Inode = cpu_to_le64(stat.ino);
5339 if (ksmbd_stream_fd(fp) == false) {
5340 file_info->EndOfFile = cpu_to_le64(stat.size);
5341 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5342 } else {
5343 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5344 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5345 }
5346 file_info->HardLinks = cpu_to_le32(stat.nlink);
5347 file_info->Mode = cpu_to_le32(stat.mode & 0777);
5348 switch (stat.mode & S_IFMT) {
5349 case S_IFDIR:
5350 file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5351 break;
5352 case S_IFLNK:
5353 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5354 break;
5355 case S_IFCHR:
5356 file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5357 break;
5358 case S_IFBLK:
5359 file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5360 break;
5361 case S_IFIFO:
5362 file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5363 break;
5364 case S_IFSOCK:
5365 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5366 }
5367
5368 file_info->DeviceId = cpu_to_le32(stat.rdev);
5369
5370 /*
5371 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5372 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5373 * sub_auth(4 * 1(num_subauth)) + RID(4).
5374 */
5375 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5376 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5377 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5378 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5379
5380 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5381
5382 return 0;
5383 }
5384
5385 static int smb2_get_info_file(struct ksmbd_work *work,
5386 struct smb2_query_info_req *req,
5387 struct smb2_query_info_rsp *rsp)
5388 {
5389 struct ksmbd_file *fp;
5390 int fileinfoclass = 0;
5391 int rc = 0;
5392 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5393
5394 if (test_share_config_flag(work->tcon->share_conf,
5395 KSMBD_SHARE_FLAG_PIPE)) {
5396 /* smb2 info file called for pipe */
5397 rc = smb2_get_info_file_pipe(work->sess, req, rsp,
5398 work->response_buf);
5399 goto iov_pin_out;
5400 }
5401
5402 if (work->next_smb2_rcv_hdr_off) {
5403 if (!has_file_id(req->VolatileFileId)) {
5404 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5405 work->compound_fid);
5406 id = work->compound_fid;
5407 pid = work->compound_pfid;
5408 }
5409 }
5410
5411 if (!has_file_id(id)) {
5412 id = req->VolatileFileId;
5413 pid = req->PersistentFileId;
5414 }
5415
5416 fp = ksmbd_lookup_fd_slow(work, id, pid);
5417 if (!fp)
5418 return -ENOENT;
5419
5420 fileinfoclass = req->FileInfoClass;
5421
5422 switch (fileinfoclass) {
5423 case FILE_ACCESS_INFORMATION:
5424 get_file_access_info(rsp, fp, work->response_buf);
5425 break;
5426
5427 case FILE_BASIC_INFORMATION:
5428 rc = get_file_basic_info(rsp, fp, work->response_buf);
5429 break;
5430
5431 case FILE_STANDARD_INFORMATION:
5432 rc = get_file_standard_info(rsp, fp, work->response_buf);
5433 break;
5434
5435 case FILE_ALIGNMENT_INFORMATION:
5436 get_file_alignment_info(rsp, work->response_buf);
5437 break;
5438
5439 case FILE_ALL_INFORMATION:
5440 rc = get_file_all_info(work, rsp, fp, work->response_buf);
5441 break;
5442
5443 case FILE_ALTERNATE_NAME_INFORMATION:
5444 get_file_alternate_info(work, rsp, fp, work->response_buf);
5445 break;
5446
5447 case FILE_STREAM_INFORMATION:
5448 rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5449 break;
5450
5451 case FILE_INTERNAL_INFORMATION:
5452 rc = get_file_internal_info(rsp, fp, work->response_buf);
5453 break;
5454
5455 case FILE_NETWORK_OPEN_INFORMATION:
5456 rc = get_file_network_open_info(rsp, fp, work->response_buf);
5457 break;
5458
5459 case FILE_EA_INFORMATION:
5460 get_file_ea_info(rsp, work->response_buf);
5461 break;
5462
5463 case FILE_FULL_EA_INFORMATION:
5464 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5465 break;
5466
5467 case FILE_POSITION_INFORMATION:
5468 get_file_position_info(rsp, fp, work->response_buf);
5469 break;
5470
5471 case FILE_MODE_INFORMATION:
5472 get_file_mode_info(rsp, fp, work->response_buf);
5473 break;
5474
5475 case FILE_COMPRESSION_INFORMATION:
5476 rc = get_file_compression_info(rsp, fp, work->response_buf);
5477 break;
5478
5479 case FILE_ATTRIBUTE_TAG_INFORMATION:
5480 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5481 break;
5482 case SMB_FIND_FILE_POSIX_INFO:
5483 if (!work->tcon->posix_extensions) {
5484 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5485 rc = -EOPNOTSUPP;
5486 } else {
5487 rc = find_file_posix_info(rsp, fp, work->response_buf);
5488 }
5489 break;
5490 default:
5491 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5492 fileinfoclass);
5493 rc = -EOPNOTSUPP;
5494 }
5495 if (!rc)
5496 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5497 rsp, work->response_buf);
5498 ksmbd_fd_put(work, fp);
5499
5500 iov_pin_out:
5501 if (!rc)
5502 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5503 offsetof(struct smb2_query_info_rsp, Buffer) +
5504 le32_to_cpu(rsp->OutputBufferLength));
5505 return rc;
5506 }
5507
5508 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5509 struct smb2_query_info_req *req,
5510 struct smb2_query_info_rsp *rsp)
5511 {
5512 struct ksmbd_conn *conn = work->conn;
5513 struct ksmbd_share_config *share = work->tcon->share_conf;
5514 int fsinfoclass = 0;
5515 struct kstatfs stfs;
5516 struct path path;
5517 int rc = 0, len;
5518
5519 if (!share->path)
5520 return -EIO;
5521
5522 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5523 if (rc) {
5524 pr_err("cannot create vfs path\n");
5525 return -EIO;
5526 }
5527
5528 rc = vfs_statfs(&path, &stfs);
5529 if (rc) {
5530 pr_err("cannot do stat of path %s\n", share->path);
5531 path_put(&path);
5532 return -EIO;
5533 }
5534
5535 fsinfoclass = req->FileInfoClass;
5536
5537 switch (fsinfoclass) {
5538 case FS_DEVICE_INFORMATION:
5539 {
5540 FILE_SYSTEM_DEVICE_INFO *info;
5541
5542 info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
5543
5544 info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5545 info->DeviceCharacteristics =
5546 cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5547 if (!test_tree_conn_flag(work->tcon,
5548 KSMBD_TREE_CONN_FLAG_WRITABLE))
5549 info->DeviceCharacteristics |=
5550 cpu_to_le32(FILE_READ_ONLY_DEVICE);
5551 rsp->OutputBufferLength = cpu_to_le32(8);
5552 break;
5553 }
5554 case FS_ATTRIBUTE_INFORMATION:
5555 {
5556 FILE_SYSTEM_ATTRIBUTE_INFO *info;
5557 size_t sz;
5558
5559 info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
5560 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5561 FILE_PERSISTENT_ACLS |
5562 FILE_UNICODE_ON_DISK |
5563 FILE_CASE_PRESERVED_NAMES |
5564 FILE_CASE_SENSITIVE_SEARCH |
5565 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5566
5567 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5568
5569 if (test_share_config_flag(work->tcon->share_conf,
5570 KSMBD_SHARE_FLAG_STREAMS))
5571 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5572
5573 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5574 /*
5575 * some application(potableapp) can not run on ksmbd share
5576 * because only NTFS handle security setting on windows.
5577 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
5578 * ksmbd should show share as NTFS. Later, If needed, we can add
5579 * fs type(s) parameter to change fs type user wanted.
5580 */
5581 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5582 "NTFS", PATH_MAX, conn->local_nls, 0);
5583 len = len * 2;
5584 info->FileSystemNameLen = cpu_to_le32(len);
5585 sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
5586 rsp->OutputBufferLength = cpu_to_le32(sz);
5587 break;
5588 }
5589 case FS_VOLUME_INFORMATION:
5590 {
5591 struct filesystem_vol_info *info;
5592 size_t sz;
5593 unsigned int serial_crc = 0;
5594
5595 info = (struct filesystem_vol_info *)(rsp->Buffer);
5596 info->VolumeCreationTime = 0;
5597 serial_crc = crc32_le(serial_crc, share->name,
5598 strlen(share->name));
5599 serial_crc = crc32_le(serial_crc, share->path,
5600 strlen(share->path));
5601 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5602 strlen(ksmbd_netbios_name()));
5603 /* Taking dummy value of serial number*/
5604 info->SerialNumber = cpu_to_le32(serial_crc);
5605 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5606 share->name, PATH_MAX,
5607 conn->local_nls, 0);
5608 len = len * 2;
5609 info->VolumeLabelSize = cpu_to_le32(len);
5610 info->Reserved = 0;
5611 sz = sizeof(struct filesystem_vol_info) + len;
5612 rsp->OutputBufferLength = cpu_to_le32(sz);
5613 break;
5614 }
5615 case FS_SIZE_INFORMATION:
5616 {
5617 FILE_SYSTEM_SIZE_INFO *info;
5618
5619 info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
5620 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5621 info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
5622 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5623 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5624 rsp->OutputBufferLength = cpu_to_le32(24);
5625 break;
5626 }
5627 case FS_FULL_SIZE_INFORMATION:
5628 {
5629 struct smb2_fs_full_size_info *info;
5630
5631 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5632 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5633 info->CallerAvailableAllocationUnits =
5634 cpu_to_le64(stfs.f_bavail);
5635 info->ActualAvailableAllocationUnits =
5636 cpu_to_le64(stfs.f_bfree);
5637 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5638 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5639 rsp->OutputBufferLength = cpu_to_le32(32);
5640 break;
5641 }
5642 case FS_OBJECT_ID_INFORMATION:
5643 {
5644 struct object_id_info *info;
5645
5646 info = (struct object_id_info *)(rsp->Buffer);
5647
5648 if (path.mnt->mnt_sb->s_uuid_len == 16)
5649 memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
5650 path.mnt->mnt_sb->s_uuid_len);
5651 else
5652 memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
5653
5654 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5655 info->extended_info.version = cpu_to_le32(1);
5656 info->extended_info.release = cpu_to_le32(1);
5657 info->extended_info.rel_date = 0;
5658 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5659 rsp->OutputBufferLength = cpu_to_le32(64);
5660 break;
5661 }
5662 case FS_SECTOR_SIZE_INFORMATION:
5663 {
5664 struct smb3_fs_ss_info *info;
5665 unsigned int sector_size =
5666 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5667
5668 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5669
5670 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5671 info->PhysicalBytesPerSectorForAtomicity =
5672 cpu_to_le32(sector_size);
5673 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5674 info->FSEffPhysicalBytesPerSectorForAtomicity =
5675 cpu_to_le32(sector_size);
5676 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5677 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5678 info->ByteOffsetForSectorAlignment = 0;
5679 info->ByteOffsetForPartitionAlignment = 0;
5680 rsp->OutputBufferLength = cpu_to_le32(28);
5681 break;
5682 }
5683 case FS_CONTROL_INFORMATION:
5684 {
5685 /*
5686 * TODO : The current implementation is based on
5687 * test result with win7(NTFS) server. It's need to
5688 * modify this to get valid Quota values
5689 * from Linux kernel
5690 */
5691 struct smb2_fs_control_info *info;
5692
5693 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5694 info->FreeSpaceStartFiltering = 0;
5695 info->FreeSpaceThreshold = 0;
5696 info->FreeSpaceStopFiltering = 0;
5697 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5698 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5699 info->Padding = 0;
5700 rsp->OutputBufferLength = cpu_to_le32(48);
5701 break;
5702 }
5703 case FS_POSIX_INFORMATION:
5704 {
5705 FILE_SYSTEM_POSIX_INFO *info;
5706
5707 if (!work->tcon->posix_extensions) {
5708 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5709 path_put(&path);
5710 return -EOPNOTSUPP;
5711 } else {
5712 info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
5713 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5714 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5715 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5716 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5717 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5718 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5719 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5720 rsp->OutputBufferLength = cpu_to_le32(56);
5721 }
5722 break;
5723 }
5724 default:
5725 path_put(&path);
5726 return -EOPNOTSUPP;
5727 }
5728 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5729 rsp, work->response_buf);
5730 path_put(&path);
5731
5732 if (!rc)
5733 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5734 offsetof(struct smb2_query_info_rsp, Buffer) +
5735 le32_to_cpu(rsp->OutputBufferLength));
5736 return rc;
5737 }
5738
5739 static int smb2_get_info_sec(struct ksmbd_work *work,
5740 struct smb2_query_info_req *req,
5741 struct smb2_query_info_rsp *rsp)
5742 {
5743 struct ksmbd_file *fp;
5744 struct mnt_idmap *idmap;
5745 struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
5746 struct smb_fattr fattr = {{0}};
5747 struct inode *inode;
5748 __u32 secdesclen = 0;
5749 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5750 int addition_info = le32_to_cpu(req->AdditionalInformation);
5751 int rc = 0, ppntsd_size = 0, max_len;
5752 size_t scratch_len = 0;
5753
5754 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5755 PROTECTED_DACL_SECINFO |
5756 UNPROTECTED_DACL_SECINFO)) {
5757 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5758 addition_info);
5759
5760 pntsd = kzalloc(ALIGN(sizeof(struct smb_ntsd), 8),
5761 KSMBD_DEFAULT_GFP);
5762 if (!pntsd)
5763 return -ENOMEM;
5764
5765 pntsd->revision = cpu_to_le16(1);
5766 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5767 pntsd->osidoffset = 0;
5768 pntsd->gsidoffset = 0;
5769 pntsd->sacloffset = 0;
5770 pntsd->dacloffset = 0;
5771
5772 secdesclen = sizeof(struct smb_ntsd);
5773 goto iov_pin;
5774 }
5775
5776 if (work->next_smb2_rcv_hdr_off) {
5777 if (!has_file_id(req->VolatileFileId)) {
5778 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5779 work->compound_fid);
5780 id = work->compound_fid;
5781 pid = work->compound_pfid;
5782 }
5783 }
5784
5785 if (!has_file_id(id)) {
5786 id = req->VolatileFileId;
5787 pid = req->PersistentFileId;
5788 }
5789
5790 fp = ksmbd_lookup_fd_slow(work, id, pid);
5791 if (!fp)
5792 return -ENOENT;
5793
5794 idmap = file_mnt_idmap(fp->filp);
5795 inode = file_inode(fp->filp);
5796 ksmbd_acls_fattr(&fattr, idmap, inode);
5797
5798 if (test_share_config_flag(work->tcon->share_conf,
5799 KSMBD_SHARE_FLAG_ACL_XATTR))
5800 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5801 fp->filp->f_path.dentry,
5802 &ppntsd);
5803
5804 /* Check if sd buffer size exceeds response buffer size */
5805 max_len = smb2_calc_max_out_buf_len(work,
5806 offsetof(struct smb2_query_info_rsp, Buffer),
5807 le32_to_cpu(req->OutputBufferLength));
5808 if (max_len < 0) {
5809 rc = -EINVAL;
5810 goto release_acl;
5811 }
5812
5813 scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
5814 ppntsd_size, addition_info);
5815 if (!scratch_len || scratch_len == SIZE_MAX) {
5816 rc = -EFBIG;
5817 goto release_acl;
5818 }
5819
5820 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
5821 if (!pntsd) {
5822 rc = -ENOMEM;
5823 goto release_acl;
5824 }
5825
5826 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5827 addition_info, &secdesclen, &fattr);
5828
5829 release_acl:
5830 posix_acl_release(fattr.cf_acls);
5831 posix_acl_release(fattr.cf_dacls);
5832 kfree(ppntsd);
5833 ksmbd_fd_put(work, fp);
5834
5835 if (!rc && ALIGN(secdesclen, 8) > scratch_len)
5836 rc = -EFBIG;
5837 if (rc)
5838 goto err_out;
5839
5840 iov_pin:
5841 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5842 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5843 rsp, work->response_buf);
5844 if (rc)
5845 goto err_out;
5846
5847 rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
5848 offsetof(struct smb2_query_info_rsp, Buffer),
5849 pntsd, secdesclen);
5850 err_out:
5851 if (rc) {
5852 rsp->OutputBufferLength = 0;
5853 kvfree(pntsd);
5854 }
5855
5856 return rc;
5857 }
5858
5859 /**
5860 * smb2_query_info() - handler for smb2 query info command
5861 * @work: smb work containing query info request buffer
5862 *
5863 * Return: 0 on success, otherwise error
5864 */
5865 int smb2_query_info(struct ksmbd_work *work)
5866 {
5867 struct smb2_query_info_req *req;
5868 struct smb2_query_info_rsp *rsp;
5869 int rc = 0;
5870
5871 ksmbd_debug(SMB, "Received request smb2 query info request\n");
5872
5873 WORK_BUFFERS(work, req, rsp);
5874
5875 if (ksmbd_override_fsids(work)) {
5876 rc = -ENOMEM;
5877 goto err_out;
5878 }
5879
5880 rsp->StructureSize = cpu_to_le16(9);
5881 rsp->OutputBufferOffset = cpu_to_le16(72);
5882
5883 switch (req->InfoType) {
5884 case SMB2_O_INFO_FILE:
5885 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5886 rc = smb2_get_info_file(work, req, rsp);
5887 break;
5888 case SMB2_O_INFO_FILESYSTEM:
5889 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5890 rc = smb2_get_info_filesystem(work, req, rsp);
5891 break;
5892 case SMB2_O_INFO_SECURITY:
5893 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5894 rc = smb2_get_info_sec(work, req, rsp);
5895 break;
5896 default:
5897 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5898 req->InfoType);
5899 rc = -EOPNOTSUPP;
5900 }
5901 ksmbd_revert_fsids(work);
5902
5903 err_out:
5904 if (rc < 0) {
5905 if (rc == -EACCES)
5906 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5907 else if (rc == -ENOENT)
5908 rsp->hdr.Status = STATUS_FILE_CLOSED;
5909 else if (rc == -EIO)
5910 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5911 else if (rc == -ENOMEM)
5912 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5913 else if (rc == -EINVAL && rsp->hdr.Status == 0)
5914 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5915 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5916 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5917 smb2_set_err_rsp(work);
5918
5919 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5920 rc);
5921 return rc;
5922 }
5923 return 0;
5924 }
5925
5926 /**
5927 * smb2_close_pipe() - handler for closing IPC pipe
5928 * @work: smb work containing close request buffer
5929 *
5930 * Return: 0
5931 */
5932 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5933 {
5934 u64 id;
5935 struct smb2_close_req *req;
5936 struct smb2_close_rsp *rsp;
5937
5938 WORK_BUFFERS(work, req, rsp);
5939
5940 id = req->VolatileFileId;
5941 ksmbd_session_rpc_close(work->sess, id);
5942
5943 rsp->StructureSize = cpu_to_le16(60);
5944 rsp->Flags = 0;
5945 rsp->Reserved = 0;
5946 rsp->CreationTime = 0;
5947 rsp->LastAccessTime = 0;
5948 rsp->LastWriteTime = 0;
5949 rsp->ChangeTime = 0;
5950 rsp->AllocationSize = 0;
5951 rsp->EndOfFile = 0;
5952 rsp->Attributes = 0;
5953
5954 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5955 sizeof(struct smb2_close_rsp));
5956 }
5957
5958 /**
5959 * smb2_close() - handler for smb2 close file command
5960 * @work: smb work containing close request buffer
5961 *
5962 * Return: 0 on success, otherwise error
5963 */
5964 int smb2_close(struct ksmbd_work *work)
5965 {
5966 u64 volatile_id = KSMBD_NO_FID;
5967 u64 sess_id;
5968 struct smb2_close_req *req;
5969 struct smb2_close_rsp *rsp;
5970 struct ksmbd_conn *conn = work->conn;
5971 struct ksmbd_file *fp;
5972 u64 time;
5973 int err = 0;
5974
5975 ksmbd_debug(SMB, "Received smb2 close request\n");
5976
5977 WORK_BUFFERS(work, req, rsp);
5978
5979 if (test_share_config_flag(work->tcon->share_conf,
5980 KSMBD_SHARE_FLAG_PIPE)) {
5981 ksmbd_debug(SMB, "IPC pipe close request\n");
5982 return smb2_close_pipe(work);
5983 }
5984
5985 sess_id = le64_to_cpu(req->hdr.SessionId);
5986 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5987 sess_id = work->compound_sid;
5988
5989 work->compound_sid = 0;
5990 if (check_session_id(conn, sess_id)) {
5991 work->compound_sid = sess_id;
5992 } else {
5993 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5994 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5995 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5996 err = -EBADF;
5997 goto out;
5998 }
5999
6000 if (work->next_smb2_rcv_hdr_off &&
6001 !has_file_id(req->VolatileFileId)) {
6002 if (!has_file_id(work->compound_fid)) {
6003 /* file already closed, return FILE_CLOSED */
6004 ksmbd_debug(SMB, "file already closed\n");
6005 rsp->hdr.Status = STATUS_FILE_CLOSED;
6006 err = -EBADF;
6007 goto out;
6008 } else {
6009 ksmbd_debug(SMB,
6010 "Compound request set FID = %llu:%llu\n",
6011 work->compound_fid,
6012 work->compound_pfid);
6013 volatile_id = work->compound_fid;
6014
6015 /* file closed, stored id is not valid anymore */
6016 work->compound_fid = KSMBD_NO_FID;
6017 work->compound_pfid = KSMBD_NO_FID;
6018 }
6019 } else {
6020 volatile_id = req->VolatileFileId;
6021 }
6022 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
6023
6024 rsp->StructureSize = cpu_to_le16(60);
6025 rsp->Reserved = 0;
6026
6027 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
6028 struct kstat stat;
6029 int ret;
6030
6031 fp = ksmbd_lookup_fd_fast(work, volatile_id);
6032 if (!fp) {
6033 err = -ENOENT;
6034 goto out;
6035 }
6036
6037 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6038 AT_STATX_SYNC_AS_STAT);
6039 if (ret) {
6040 ksmbd_fd_put(work, fp);
6041 goto out;
6042 }
6043
6044 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
6045 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
6046 cpu_to_le64(stat.blocks << 9);
6047 rsp->EndOfFile = cpu_to_le64(stat.size);
6048 rsp->Attributes = fp->f_ci->m_fattr;
6049 rsp->CreationTime = cpu_to_le64(fp->create_time);
6050 time = ksmbd_UnixTimeToNT(stat.atime);
6051 rsp->LastAccessTime = cpu_to_le64(time);
6052 time = ksmbd_UnixTimeToNT(stat.mtime);
6053 rsp->LastWriteTime = cpu_to_le64(time);
6054 time = ksmbd_UnixTimeToNT(stat.ctime);
6055 rsp->ChangeTime = cpu_to_le64(time);
6056 ksmbd_fd_put(work, fp);
6057 } else {
6058 rsp->Flags = 0;
6059 rsp->AllocationSize = 0;
6060 rsp->EndOfFile = 0;
6061 rsp->Attributes = 0;
6062 rsp->CreationTime = 0;
6063 rsp->LastAccessTime = 0;
6064 rsp->LastWriteTime = 0;
6065 rsp->ChangeTime = 0;
6066 }
6067
6068 err = ksmbd_close_fd(work, volatile_id);
6069 out:
6070 if (!err)
6071 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6072 sizeof(struct smb2_close_rsp));
6073
6074 if (err) {
6075 if (rsp->hdr.Status == 0)
6076 rsp->hdr.Status = STATUS_FILE_CLOSED;
6077 smb2_set_err_rsp(work);
6078 }
6079
6080 return err;
6081 }
6082
6083 /**
6084 * smb2_echo() - handler for smb2 echo(ping) command
6085 * @work: smb work containing echo request buffer
6086 *
6087 * Return: 0 on success, otherwise error
6088 */
6089 int smb2_echo(struct ksmbd_work *work)
6090 {
6091 struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
6092
6093 ksmbd_debug(SMB, "Received smb2 echo request\n");
6094
6095 if (work->next_smb2_rcv_hdr_off)
6096 rsp = ksmbd_resp_buf_next(work);
6097
6098 rsp->StructureSize = cpu_to_le16(4);
6099 rsp->Reserved = 0;
6100 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
6101 }
6102
6103 static int smb2_rename(struct ksmbd_work *work,
6104 struct ksmbd_file *fp,
6105 struct smb2_file_rename_info *file_info,
6106 struct nls_table *local_nls)
6107 {
6108 struct ksmbd_share_config *share = fp->tcon->share_conf;
6109 char *new_name = NULL;
6110 int rc, flags = 0;
6111
6112 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
6113 new_name = smb2_get_name(file_info->FileName,
6114 le32_to_cpu(file_info->FileNameLength),
6115 local_nls);
6116 if (IS_ERR(new_name))
6117 return PTR_ERR(new_name);
6118
6119 if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
6120 int s_type;
6121 char *xattr_stream_name, *stream_name = NULL;
6122 size_t xattr_stream_size;
6123 int len;
6124
6125 rc = parse_stream_name(new_name, &stream_name, &s_type);
6126 if (rc < 0)
6127 goto out;
6128
6129 len = strlen(new_name);
6130 if (len > 0 && new_name[len - 1] != '/') {
6131 pr_err("not allow base filename in rename\n");
6132 rc = -ESHARE;
6133 goto out;
6134 }
6135
6136 rc = ksmbd_vfs_xattr_stream_name(stream_name,
6137 &xattr_stream_name,
6138 &xattr_stream_size,
6139 s_type);
6140 if (rc)
6141 goto out;
6142
6143 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6144 &fp->filp->f_path,
6145 xattr_stream_name,
6146 NULL, 0, 0, true);
6147 if (rc < 0) {
6148 pr_err("failed to store stream name in xattr: %d\n",
6149 rc);
6150 rc = -EINVAL;
6151 goto out;
6152 }
6153
6154 goto out;
6155 }
6156
6157 ksmbd_debug(SMB, "new name %s\n", new_name);
6158 if (ksmbd_share_veto_filename(share, new_name)) {
6159 rc = -ENOENT;
6160 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6161 goto out;
6162 }
6163
6164 if (!file_info->ReplaceIfExists)
6165 flags = RENAME_NOREPLACE;
6166
6167 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6168 if (!rc)
6169 smb_break_all_levII_oplock(work, fp, 0);
6170 out:
6171 kfree(new_name);
6172 return rc;
6173 }
6174
6175 static int smb2_create_link(struct ksmbd_work *work,
6176 struct ksmbd_share_config *share,
6177 struct smb2_file_link_info *file_info,
6178 unsigned int buf_len, struct file *filp,
6179 struct nls_table *local_nls)
6180 {
6181 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6182 struct path path;
6183 int rc;
6184
6185 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6186 le32_to_cpu(file_info->FileNameLength))
6187 return -EINVAL;
6188
6189 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6190 pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6191 if (!pathname)
6192 return -ENOMEM;
6193
6194 link_name = smb2_get_name(file_info->FileName,
6195 le32_to_cpu(file_info->FileNameLength),
6196 local_nls);
6197 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6198 rc = -EINVAL;
6199 goto out;
6200 }
6201
6202 ksmbd_debug(SMB, "link name is %s\n", link_name);
6203 target_name = file_path(filp, pathname, PATH_MAX);
6204 if (IS_ERR(target_name)) {
6205 rc = -EINVAL;
6206 goto out;
6207 }
6208
6209 ksmbd_debug(SMB, "target name is %s\n", target_name);
6210 rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
6211 &path, 0);
6212 if (rc) {
6213 if (rc != -ENOENT)
6214 goto out;
6215 } else {
6216 if (file_info->ReplaceIfExists) {
6217 rc = ksmbd_vfs_remove_file(work, &path);
6218 if (rc) {
6219 rc = -EINVAL;
6220 ksmbd_debug(SMB, "cannot delete %s\n",
6221 link_name);
6222 }
6223 } else {
6224 rc = -EEXIST;
6225 ksmbd_debug(SMB, "link already exists\n");
6226 }
6227 ksmbd_vfs_kern_path_end_removing(&path);
6228 if (rc)
6229 goto out;
6230 }
6231 rc = ksmbd_vfs_link(work, target_name, link_name);
6232 if (rc)
6233 rc = -EINVAL;
6234 out:
6235
6236 if (!IS_ERR(link_name))
6237 kfree(link_name);
6238 kfree(pathname);
6239 return rc;
6240 }
6241
6242 static int set_file_basic_info(struct ksmbd_file *fp,
6243 struct smb2_file_basic_info *file_info,
6244 struct ksmbd_share_config *share)
6245 {
6246 struct iattr attrs;
6247 struct file *filp;
6248 struct inode *inode;
6249 struct mnt_idmap *idmap;
6250 int rc = 0;
6251
6252 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6253 return -EACCES;
6254
6255 attrs.ia_valid = 0;
6256 filp = fp->filp;
6257 inode = file_inode(filp);
6258 idmap = file_mnt_idmap(filp);
6259
6260 if (file_info->CreationTime)
6261 fp->create_time = le64_to_cpu(file_info->CreationTime);
6262
6263 if (file_info->LastAccessTime) {
6264 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6265 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6266 }
6267
6268 if (file_info->ChangeTime)
6269 inode_set_ctime_to_ts(inode,
6270 ksmbd_NTtimeToUnix(file_info->ChangeTime));
6271
6272 if (file_info->LastWriteTime) {
6273 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6274 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6275 }
6276
6277 if (file_info->Attributes) {
6278 if (!S_ISDIR(inode->i_mode) &&
6279 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6280 pr_err("can't change a file to a directory\n");
6281 return -EINVAL;
6282 }
6283
6284 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6285 fp->f_ci->m_fattr = file_info->Attributes |
6286 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6287 }
6288
6289 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6290 (file_info->CreationTime || file_info->Attributes)) {
6291 struct xattr_dos_attrib da = {0};
6292
6293 da.version = 4;
6294 da.itime = fp->itime;
6295 da.create_time = fp->create_time;
6296 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6297 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6298 XATTR_DOSINFO_ITIME;
6299
6300 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6301 true);
6302 if (rc)
6303 ksmbd_debug(SMB,
6304 "failed to restore file attribute in EA\n");
6305 rc = 0;
6306 }
6307
6308 if (attrs.ia_valid) {
6309 struct dentry *dentry = filp->f_path.dentry;
6310 struct inode *inode = d_inode(dentry);
6311
6312 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6313 return -EACCES;
6314
6315 inode_lock(inode);
6316 rc = notify_change(idmap, dentry, &attrs, NULL);
6317 inode_unlock(inode);
6318 }
6319 return rc;
6320 }
6321
6322 static int set_file_allocation_info(struct ksmbd_work *work,
6323 struct ksmbd_file *fp,
6324 struct smb2_file_alloc_info *file_alloc_info)
6325 {
6326 /*
6327 * TODO : It's working fine only when store dos attributes
6328 * is not yes. need to implement a logic which works
6329 * properly with any smb.conf option
6330 */
6331
6332 loff_t alloc_blks;
6333 struct inode *inode;
6334 struct kstat stat;
6335 int rc;
6336
6337 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6338 return -EACCES;
6339
6340 if (ksmbd_stream_fd(fp) == true)
6341 return 0;
6342
6343 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6344 AT_STATX_SYNC_AS_STAT);
6345 if (rc)
6346 return rc;
6347
6348 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6349 inode = file_inode(fp->filp);
6350
6351 if (alloc_blks > stat.blocks) {
6352 smb_break_all_levII_oplock(work, fp, 1);
6353 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6354 alloc_blks * 512);
6355 if (rc && rc != -EOPNOTSUPP) {
6356 pr_err("vfs_fallocate is failed : %d\n", rc);
6357 return rc;
6358 }
6359 } else if (alloc_blks < stat.blocks) {
6360 loff_t size;
6361
6362 /*
6363 * Allocation size could be smaller than original one
6364 * which means allocated blocks in file should be
6365 * deallocated. use truncate to cut out it, but inode
6366 * size is also updated with truncate offset.
6367 * inode size is retained by backup inode size.
6368 */
6369 size = i_size_read(inode);
6370 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6371 if (rc) {
6372 pr_err("truncate failed!, err %d\n", rc);
6373 return rc;
6374 }
6375 if (size < alloc_blks * 512)
6376 i_size_write(inode, size);
6377 }
6378 return 0;
6379 }
6380
6381 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6382 struct smb2_file_eof_info *file_eof_info)
6383 {
6384 loff_t newsize;
6385 struct inode *inode;
6386 int rc;
6387
6388 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6389 return -EACCES;
6390
6391 newsize = le64_to_cpu(file_eof_info->EndOfFile);
6392 inode = file_inode(fp->filp);
6393
6394 /*
6395 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6396 * on FAT32 shared device, truncate execution time is too long
6397 * and network error could cause from windows client. because
6398 * truncate of some filesystem like FAT32 fill zero data in
6399 * truncated range.
6400 */
6401 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6402 ksmbd_stream_fd(fp) == false) {
6403 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6404 rc = ksmbd_vfs_truncate(work, fp, newsize);
6405 if (rc) {
6406 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6407 if (rc != -EAGAIN)
6408 rc = -EBADF;
6409 return rc;
6410 }
6411 }
6412 return 0;
6413 }
6414
6415 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6416 struct smb2_file_rename_info *rename_info,
6417 unsigned int buf_len)
6418 {
6419 if (!(fp->daccess & FILE_DELETE_LE)) {
6420 pr_err("no right to delete : 0x%x\n", fp->daccess);
6421 return -EACCES;
6422 }
6423
6424 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6425 le32_to_cpu(rename_info->FileNameLength))
6426 return -EINVAL;
6427
6428 if (!le32_to_cpu(rename_info->FileNameLength))
6429 return -EINVAL;
6430
6431 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6432 }
6433
6434 static int set_file_disposition_info(struct ksmbd_file *fp,
6435 struct smb2_file_disposition_info *file_info)
6436 {
6437 struct inode *inode;
6438
6439 if (!(fp->daccess & FILE_DELETE_LE)) {
6440 pr_err("no right to delete : 0x%x\n", fp->daccess);
6441 return -EACCES;
6442 }
6443
6444 inode = file_inode(fp->filp);
6445 if (file_info->DeletePending) {
6446 if (S_ISDIR(inode->i_mode) &&
6447 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6448 return -EBUSY;
6449 ksmbd_set_inode_pending_delete(fp);
6450 } else {
6451 ksmbd_clear_inode_pending_delete(fp);
6452 }
6453 return 0;
6454 }
6455
6456 static int set_file_position_info(struct ksmbd_file *fp,
6457 struct smb2_file_pos_info *file_info)
6458 {
6459 loff_t current_byte_offset;
6460 unsigned long sector_size;
6461 struct inode *inode;
6462
6463 inode = file_inode(fp->filp);
6464 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6465 sector_size = inode->i_sb->s_blocksize;
6466
6467 if (current_byte_offset < 0 ||
6468 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6469 current_byte_offset & (sector_size - 1))) {
6470 pr_err("CurrentByteOffset is not valid : %llu\n",
6471 current_byte_offset);
6472 return -EINVAL;
6473 }
6474
6475 if (ksmbd_stream_fd(fp) == false)
6476 fp->filp->f_pos = current_byte_offset;
6477 else {
6478 if (current_byte_offset > XATTR_SIZE_MAX)
6479 current_byte_offset = XATTR_SIZE_MAX;
6480 fp->stream.pos = current_byte_offset;
6481 }
6482 return 0;
6483 }
6484
6485 static int set_file_mode_info(struct ksmbd_file *fp,
6486 struct smb2_file_mode_info *file_info)
6487 {
6488 __le32 mode;
6489
6490 mode = file_info->Mode;
6491
6492 if ((mode & ~FILE_MODE_INFO_MASK)) {
6493 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6494 return -EINVAL;
6495 }
6496
6497 /*
6498 * TODO : need to implement consideration for
6499 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6500 */
6501 ksmbd_vfs_set_fadvise(fp->filp, mode);
6502 fp->coption = mode;
6503 return 0;
6504 }
6505
6506 /**
6507 * smb2_set_info_file() - handler for smb2 set info command
6508 * @work: smb work containing set info command buffer
6509 * @fp: ksmbd_file pointer
6510 * @req: request buffer pointer
6511 * @share: ksmbd_share_config pointer
6512 *
6513 * Return: 0 on success, otherwise error
6514 */
6515 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6516 struct smb2_set_info_req *req,
6517 struct ksmbd_share_config *share)
6518 {
6519 unsigned int buf_len = le32_to_cpu(req->BufferLength);
6520 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6521
6522 switch (req->FileInfoClass) {
6523 case FILE_BASIC_INFORMATION:
6524 {
6525 if (buf_len < sizeof(struct smb2_file_basic_info))
6526 return -EMSGSIZE;
6527
6528 return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6529 }
6530 case FILE_ALLOCATION_INFORMATION:
6531 {
6532 if (buf_len < sizeof(struct smb2_file_alloc_info))
6533 return -EMSGSIZE;
6534
6535 return set_file_allocation_info(work, fp,
6536 (struct smb2_file_alloc_info *)buffer);
6537 }
6538 case FILE_END_OF_FILE_INFORMATION:
6539 {
6540 if (buf_len < sizeof(struct smb2_file_eof_info))
6541 return -EMSGSIZE;
6542
6543 return set_end_of_file_info(work, fp,
6544 (struct smb2_file_eof_info *)buffer);
6545 }
6546 case FILE_RENAME_INFORMATION:
6547 {
6548 if (buf_len < sizeof(struct smb2_file_rename_info))
6549 return -EMSGSIZE;
6550
6551 return set_rename_info(work, fp,
6552 (struct smb2_file_rename_info *)buffer,
6553 buf_len);
6554 }
6555 case FILE_LINK_INFORMATION:
6556 {
6557 if (buf_len < sizeof(struct smb2_file_link_info))
6558 return -EMSGSIZE;
6559
6560 return smb2_create_link(work, work->tcon->share_conf,
6561 (struct smb2_file_link_info *)buffer,
6562 buf_len, fp->filp,
6563 work->conn->local_nls);
6564 }
6565 case FILE_DISPOSITION_INFORMATION:
6566 {
6567 if (buf_len < sizeof(struct smb2_file_disposition_info))
6568 return -EMSGSIZE;
6569
6570 return set_file_disposition_info(fp,
6571 (struct smb2_file_disposition_info *)buffer);
6572 }
6573 case FILE_FULL_EA_INFORMATION:
6574 {
6575 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6576 pr_err("Not permitted to write ext attr: 0x%x\n",
6577 fp->daccess);
6578 return -EACCES;
6579 }
6580
6581 if (buf_len < sizeof(struct smb2_ea_info))
6582 return -EMSGSIZE;
6583
6584 return smb2_set_ea((struct smb2_ea_info *)buffer,
6585 buf_len, &fp->filp->f_path, true);
6586 }
6587 case FILE_POSITION_INFORMATION:
6588 {
6589 if (buf_len < sizeof(struct smb2_file_pos_info))
6590 return -EMSGSIZE;
6591
6592 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6593 }
6594 case FILE_MODE_INFORMATION:
6595 {
6596 if (buf_len < sizeof(struct smb2_file_mode_info))
6597 return -EMSGSIZE;
6598
6599 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6600 }
6601 }
6602
6603 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6604 return -EOPNOTSUPP;
6605 }
6606
6607 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6608 char *buffer, int buf_len)
6609 {
6610 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6611
6612 fp->saccess |= FILE_SHARE_DELETE_LE;
6613
6614 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6615 buf_len, false, true);
6616 }
6617
6618 /**
6619 * smb2_set_info() - handler for smb2 set info command handler
6620 * @work: smb work containing set info request buffer
6621 *
6622 * Return: 0 on success, otherwise error
6623 */
6624 int smb2_set_info(struct ksmbd_work *work)
6625 {
6626 struct smb2_set_info_req *req;
6627 struct smb2_set_info_rsp *rsp;
6628 struct ksmbd_file *fp = NULL;
6629 int rc = 0;
6630 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6631
6632 ksmbd_debug(SMB, "Received smb2 set info request\n");
6633
6634 if (work->next_smb2_rcv_hdr_off) {
6635 req = ksmbd_req_buf_next(work);
6636 rsp = ksmbd_resp_buf_next(work);
6637 if (!has_file_id(req->VolatileFileId)) {
6638 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6639 work->compound_fid);
6640 id = work->compound_fid;
6641 pid = work->compound_pfid;
6642 }
6643 } else {
6644 req = smb_get_msg(work->request_buf);
6645 rsp = smb_get_msg(work->response_buf);
6646 }
6647
6648 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6649 ksmbd_debug(SMB, "User does not have write permission\n");
6650 pr_err("User does not have write permission\n");
6651 rc = -EACCES;
6652 goto err_out;
6653 }
6654
6655 if (!has_file_id(id)) {
6656 id = req->VolatileFileId;
6657 pid = req->PersistentFileId;
6658 }
6659
6660 fp = ksmbd_lookup_fd_slow(work, id, pid);
6661 if (!fp) {
6662 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6663 rc = -ENOENT;
6664 goto err_out;
6665 }
6666
6667 switch (req->InfoType) {
6668 case SMB2_O_INFO_FILE:
6669 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6670 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6671 break;
6672 case SMB2_O_INFO_SECURITY:
6673 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6674 if (ksmbd_override_fsids(work)) {
6675 rc = -ENOMEM;
6676 goto err_out;
6677 }
6678 rc = smb2_set_info_sec(fp,
6679 le32_to_cpu(req->AdditionalInformation),
6680 (char *)req + le16_to_cpu(req->BufferOffset),
6681 le32_to_cpu(req->BufferLength));
6682 ksmbd_revert_fsids(work);
6683 break;
6684 default:
6685 rc = -EOPNOTSUPP;
6686 }
6687
6688 if (rc < 0)
6689 goto err_out;
6690
6691 rsp->StructureSize = cpu_to_le16(2);
6692 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6693 sizeof(struct smb2_set_info_rsp));
6694 if (rc)
6695 goto err_out;
6696 ksmbd_fd_put(work, fp);
6697 return 0;
6698
6699 err_out:
6700 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6701 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6702 else if (rc == -EINVAL)
6703 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6704 else if (rc == -EMSGSIZE)
6705 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6706 else if (rc == -ESHARE)
6707 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6708 else if (rc == -ENOENT)
6709 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6710 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6711 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6712 else if (rc == -EAGAIN)
6713 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6714 else if (rc == -EBADF || rc == -ESTALE)
6715 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6716 else if (rc == -EEXIST)
6717 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6718 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6719 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6720 smb2_set_err_rsp(work);
6721 ksmbd_fd_put(work, fp);
6722 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6723 return rc;
6724 }
6725
6726 /**
6727 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6728 * @work: smb work containing read IPC pipe command buffer
6729 *
6730 * Return: 0 on success, otherwise error
6731 */
6732 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6733 {
6734 int nbytes = 0, err;
6735 u64 id;
6736 struct ksmbd_rpc_command *rpc_resp;
6737 struct smb2_read_req *req;
6738 struct smb2_read_rsp *rsp;
6739
6740 WORK_BUFFERS(work, req, rsp);
6741
6742 id = req->VolatileFileId;
6743
6744 rpc_resp = ksmbd_rpc_read(work->sess, id);
6745 if (rpc_resp) {
6746 void *aux_payload_buf;
6747
6748 if (rpc_resp->flags != KSMBD_RPC_OK) {
6749 err = -EINVAL;
6750 goto out;
6751 }
6752
6753 aux_payload_buf =
6754 kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
6755 if (!aux_payload_buf) {
6756 err = -ENOMEM;
6757 goto out;
6758 }
6759
6760 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6761
6762 nbytes = rpc_resp->payload_sz;
6763 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6764 offsetof(struct smb2_read_rsp, Buffer),
6765 aux_payload_buf, nbytes);
6766 if (err) {
6767 kvfree(aux_payload_buf);
6768 goto out;
6769 }
6770 kvfree(rpc_resp);
6771 } else {
6772 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6773 offsetof(struct smb2_read_rsp, Buffer));
6774 if (err)
6775 goto out;
6776 }
6777
6778 rsp->StructureSize = cpu_to_le16(17);
6779 rsp->DataOffset = 80;
6780 rsp->Reserved = 0;
6781 rsp->DataLength = cpu_to_le32(nbytes);
6782 rsp->DataRemaining = 0;
6783 rsp->Flags = 0;
6784 return 0;
6785
6786 out:
6787 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6788 smb2_set_err_rsp(work);
6789 kvfree(rpc_resp);
6790 return err;
6791 }
6792
6793 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6794 struct smbdirect_buffer_descriptor_v1 *desc,
6795 __le32 Channel,
6796 __le16 ChannelInfoLength)
6797 {
6798 unsigned int i, ch_count;
6799
6800 if (work->conn->dialect == SMB30_PROT_ID &&
6801 Channel != SMB2_CHANNEL_RDMA_V1)
6802 return -EINVAL;
6803
6804 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6805 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6806 for (i = 0; i < ch_count; i++) {
6807 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6808 i,
6809 le32_to_cpu(desc[i].token),
6810 le32_to_cpu(desc[i].length));
6811 }
6812 }
6813 if (!ch_count)
6814 return -EINVAL;
6815
6816 work->need_invalidate_rkey =
6817 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6818 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6819 work->remote_key = le32_to_cpu(desc->token);
6820 return 0;
6821 }
6822
6823 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6824 struct smb2_read_req *req, void *data_buf,
6825 size_t length)
6826 {
6827 int err;
6828
6829 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6830 (struct smbdirect_buffer_descriptor_v1 *)
6831 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6832 le16_to_cpu(req->ReadChannelInfoLength));
6833 if (err)
6834 return err;
6835
6836 return length;
6837 }
6838
6839 /**
6840 * smb2_read() - handler for smb2 read from file
6841 * @work: smb work containing read command buffer
6842 *
6843 * Return: 0 on success, otherwise error
6844 */
6845 int smb2_read(struct ksmbd_work *work)
6846 {
6847 struct ksmbd_conn *conn = work->conn;
6848 struct smb2_read_req *req;
6849 struct smb2_read_rsp *rsp;
6850 struct ksmbd_file *fp = NULL;
6851 loff_t offset;
6852 size_t length, mincount;
6853 ssize_t nbytes = 0, remain_bytes = 0;
6854 int err = 0;
6855 bool is_rdma_channel = false;
6856 unsigned int max_read_size = conn->vals->max_read_size;
6857 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6858 void *aux_payload_buf;
6859
6860 ksmbd_debug(SMB, "Received smb2 read request\n");
6861
6862 if (test_share_config_flag(work->tcon->share_conf,
6863 KSMBD_SHARE_FLAG_PIPE)) {
6864 ksmbd_debug(SMB, "IPC pipe read request\n");
6865 return smb2_read_pipe(work);
6866 }
6867
6868 if (work->next_smb2_rcv_hdr_off) {
6869 req = ksmbd_req_buf_next(work);
6870 rsp = ksmbd_resp_buf_next(work);
6871 if (!has_file_id(req->VolatileFileId)) {
6872 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6873 work->compound_fid);
6874 id = work->compound_fid;
6875 pid = work->compound_pfid;
6876 }
6877 } else {
6878 req = smb_get_msg(work->request_buf);
6879 rsp = smb_get_msg(work->response_buf);
6880 }
6881
6882 if (!has_file_id(id)) {
6883 id = req->VolatileFileId;
6884 pid = req->PersistentFileId;
6885 }
6886
6887 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6888 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6889 is_rdma_channel = true;
6890 max_read_size = get_smbd_max_read_write_size(work->conn->transport);
6891 if (max_read_size == 0) {
6892 err = -EINVAL;
6893 goto out;
6894 }
6895 }
6896
6897 if (is_rdma_channel == true) {
6898 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6899
6900 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6901 err = -EINVAL;
6902 goto out;
6903 }
6904 err = smb2_set_remote_key_for_rdma(work,
6905 (struct smbdirect_buffer_descriptor_v1 *)
6906 ((char *)req + ch_offset),
6907 req->Channel,
6908 req->ReadChannelInfoLength);
6909 if (err)
6910 goto out;
6911 }
6912
6913 fp = ksmbd_lookup_fd_slow(work, id, pid);
6914 if (!fp) {
6915 err = -ENOENT;
6916 goto out;
6917 }
6918
6919 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6920 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6921 err = -EACCES;
6922 goto out;
6923 }
6924
6925 offset = le64_to_cpu(req->Offset);
6926 if (offset < 0) {
6927 err = -EINVAL;
6928 goto out;
6929 }
6930 length = le32_to_cpu(req->Length);
6931 mincount = le32_to_cpu(req->MinimumCount);
6932
6933 if (length > max_read_size) {
6934 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6935 max_read_size);
6936 err = -EINVAL;
6937 goto out;
6938 }
6939
6940 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6941 fp->filp, offset, length);
6942
6943 aux_payload_buf = kvzalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
6944 if (!aux_payload_buf) {
6945 err = -ENOMEM;
6946 goto out;
6947 }
6948
6949 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6950 if (nbytes < 0) {
6951 kvfree(aux_payload_buf);
6952 err = nbytes;
6953 goto out;
6954 }
6955
6956 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6957 kvfree(aux_payload_buf);
6958 rsp->hdr.Status = STATUS_END_OF_FILE;
6959 smb2_set_err_rsp(work);
6960 ksmbd_fd_put(work, fp);
6961 return -ENODATA;
6962 }
6963
6964 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6965 nbytes, offset, mincount);
6966
6967 if (is_rdma_channel == true) {
6968 /* write data to the client using rdma channel */
6969 remain_bytes = smb2_read_rdma_channel(work, req,
6970 aux_payload_buf,
6971 nbytes);
6972 kvfree(aux_payload_buf);
6973 aux_payload_buf = NULL;
6974 nbytes = 0;
6975 if (remain_bytes < 0) {
6976 err = (int)remain_bytes;
6977 goto out;
6978 }
6979 }
6980
6981 rsp->StructureSize = cpu_to_le16(17);
6982 rsp->DataOffset = 80;
6983 rsp->Reserved = 0;
6984 rsp->DataLength = cpu_to_le32(nbytes);
6985 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6986 rsp->Flags = 0;
6987 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6988 offsetof(struct smb2_read_rsp, Buffer),
6989 aux_payload_buf, nbytes);
6990 if (err) {
6991 kvfree(aux_payload_buf);
6992 goto out;
6993 }
6994 ksmbd_fd_put(work, fp);
6995 return 0;
6996
6997 out:
6998 if (err) {
6999 if (err == -EISDIR)
7000 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
7001 else if (err == -EAGAIN)
7002 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7003 else if (err == -ENOENT)
7004 rsp->hdr.Status = STATUS_FILE_CLOSED;
7005 else if (err == -EACCES)
7006 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7007 else if (err == -ESHARE)
7008 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7009 else if (err == -EINVAL)
7010 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7011 else
7012 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7013
7014 smb2_set_err_rsp(work);
7015 }
7016 ksmbd_fd_put(work, fp);
7017 return err;
7018 }
7019
7020 /**
7021 * smb2_write_pipe() - handler for smb2 write on IPC pipe
7022 * @work: smb work containing write IPC pipe command buffer
7023 *
7024 * Return: 0 on success, otherwise error
7025 */
7026 static noinline int smb2_write_pipe(struct ksmbd_work *work)
7027 {
7028 struct smb2_write_req *req;
7029 struct smb2_write_rsp *rsp;
7030 struct ksmbd_rpc_command *rpc_resp;
7031 u64 id = 0;
7032 int err = 0, ret = 0;
7033 char *data_buf;
7034 size_t length;
7035
7036 WORK_BUFFERS(work, req, rsp);
7037
7038 length = le32_to_cpu(req->Length);
7039 id = req->VolatileFileId;
7040
7041 if ((u64)le16_to_cpu(req->DataOffset) + length >
7042 get_rfc1002_len(work->request_buf)) {
7043 pr_err("invalid write data offset %u, smb_len %u\n",
7044 le16_to_cpu(req->DataOffset),
7045 get_rfc1002_len(work->request_buf));
7046 err = -EINVAL;
7047 goto out;
7048 }
7049
7050 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7051 le16_to_cpu(req->DataOffset));
7052
7053 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
7054 if (rpc_resp) {
7055 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7056 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7057 kvfree(rpc_resp);
7058 smb2_set_err_rsp(work);
7059 return -EOPNOTSUPP;
7060 }
7061 if (rpc_resp->flags != KSMBD_RPC_OK) {
7062 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7063 smb2_set_err_rsp(work);
7064 kvfree(rpc_resp);
7065 return ret;
7066 }
7067 kvfree(rpc_resp);
7068 }
7069
7070 rsp->StructureSize = cpu_to_le16(17);
7071 rsp->DataOffset = 0;
7072 rsp->Reserved = 0;
7073 rsp->DataLength = cpu_to_le32(length);
7074 rsp->DataRemaining = 0;
7075 rsp->Reserved2 = 0;
7076 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7077 offsetof(struct smb2_write_rsp, Buffer));
7078 out:
7079 if (err) {
7080 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7081 smb2_set_err_rsp(work);
7082 }
7083
7084 return err;
7085 }
7086
7087 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
7088 struct smb2_write_req *req,
7089 struct ksmbd_file *fp,
7090 loff_t offset, size_t length, bool sync)
7091 {
7092 char *data_buf;
7093 int ret;
7094 ssize_t nbytes;
7095
7096 data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
7097 if (!data_buf)
7098 return -ENOMEM;
7099
7100 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
7101 (struct smbdirect_buffer_descriptor_v1 *)
7102 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
7103 le16_to_cpu(req->WriteChannelInfoLength));
7104 if (ret < 0) {
7105 kvfree(data_buf);
7106 return ret;
7107 }
7108
7109 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
7110 kvfree(data_buf);
7111 if (ret < 0)
7112 return ret;
7113
7114 return nbytes;
7115 }
7116
7117 /**
7118 * smb2_write() - handler for smb2 write from file
7119 * @work: smb work containing write command buffer
7120 *
7121 * Return: 0 on success, otherwise error
7122 */
7123 int smb2_write(struct ksmbd_work *work)
7124 {
7125 struct smb2_write_req *req;
7126 struct smb2_write_rsp *rsp;
7127 struct ksmbd_file *fp = NULL;
7128 loff_t offset;
7129 size_t length;
7130 ssize_t nbytes;
7131 char *data_buf;
7132 bool writethrough = false, is_rdma_channel = false;
7133 int err = 0;
7134 unsigned int max_write_size = work->conn->vals->max_write_size;
7135
7136 ksmbd_debug(SMB, "Received smb2 write request\n");
7137
7138 WORK_BUFFERS(work, req, rsp);
7139
7140 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7141 ksmbd_debug(SMB, "IPC pipe write request\n");
7142 return smb2_write_pipe(work);
7143 }
7144
7145 offset = le64_to_cpu(req->Offset);
7146 if (offset < 0)
7147 return -EINVAL;
7148 length = le32_to_cpu(req->Length);
7149
7150 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7151 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7152 is_rdma_channel = true;
7153 max_write_size = get_smbd_max_read_write_size(work->conn->transport);
7154 if (max_write_size == 0) {
7155 err = -EINVAL;
7156 goto out;
7157 }
7158 length = le32_to_cpu(req->RemainingBytes);
7159 }
7160
7161 if (is_rdma_channel == true) {
7162 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7163
7164 if (req->Length != 0 || req->DataOffset != 0 ||
7165 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7166 err = -EINVAL;
7167 goto out;
7168 }
7169 err = smb2_set_remote_key_for_rdma(work,
7170 (struct smbdirect_buffer_descriptor_v1 *)
7171 ((char *)req + ch_offset),
7172 req->Channel,
7173 req->WriteChannelInfoLength);
7174 if (err)
7175 goto out;
7176 }
7177
7178 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7179 ksmbd_debug(SMB, "User does not have write permission\n");
7180 err = -EACCES;
7181 goto out;
7182 }
7183
7184 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7185 if (!fp) {
7186 err = -ENOENT;
7187 goto out;
7188 }
7189
7190 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7191 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7192 err = -EACCES;
7193 goto out;
7194 }
7195
7196 if (length > max_write_size) {
7197 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7198 max_write_size);
7199 err = -EINVAL;
7200 goto out;
7201 }
7202
7203 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7204 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7205 writethrough = true;
7206
7207 if (is_rdma_channel == false) {
7208 if (le16_to_cpu(req->DataOffset) <
7209 offsetof(struct smb2_write_req, Buffer)) {
7210 err = -EINVAL;
7211 goto out;
7212 }
7213
7214 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7215 le16_to_cpu(req->DataOffset));
7216
7217 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7218 fp->filp, offset, length);
7219 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7220 writethrough, &nbytes);
7221 if (err < 0)
7222 goto out;
7223 } else {
7224 /* read data from the client using rdma channel, and
7225 * write the data.
7226 */
7227 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7228 writethrough);
7229 if (nbytes < 0) {
7230 err = (int)nbytes;
7231 goto out;
7232 }
7233 }
7234
7235 rsp->StructureSize = cpu_to_le16(17);
7236 rsp->DataOffset = 0;
7237 rsp->Reserved = 0;
7238 rsp->DataLength = cpu_to_le32(nbytes);
7239 rsp->DataRemaining = 0;
7240 rsp->Reserved2 = 0;
7241 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7242 if (err)
7243 goto out;
7244 ksmbd_fd_put(work, fp);
7245 return 0;
7246
7247 out:
7248 if (err == -EAGAIN)
7249 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7250 else if (err == -ENOSPC || err == -EFBIG)
7251 rsp->hdr.Status = STATUS_DISK_FULL;
7252 else if (err == -ENOENT)
7253 rsp->hdr.Status = STATUS_FILE_CLOSED;
7254 else if (err == -EACCES)
7255 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7256 else if (err == -ESHARE)
7257 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7258 else if (err == -EINVAL)
7259 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7260 else
7261 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7262
7263 smb2_set_err_rsp(work);
7264 ksmbd_fd_put(work, fp);
7265 return err;
7266 }
7267
7268 /**
7269 * smb2_flush() - handler for smb2 flush file - fsync
7270 * @work: smb work containing flush command buffer
7271 *
7272 * Return: 0 on success, otherwise error
7273 */
7274 int smb2_flush(struct ksmbd_work *work)
7275 {
7276 struct smb2_flush_req *req;
7277 struct smb2_flush_rsp *rsp;
7278 int err;
7279
7280 WORK_BUFFERS(work, req, rsp);
7281
7282 ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7283
7284 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
7285 if (err)
7286 goto out;
7287
7288 rsp->StructureSize = cpu_to_le16(4);
7289 rsp->Reserved = 0;
7290 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7291
7292 out:
7293 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7294 smb2_set_err_rsp(work);
7295 return err;
7296 }
7297
7298 /**
7299 * smb2_cancel() - handler for smb2 cancel command
7300 * @work: smb work containing cancel command buffer
7301 *
7302 * Return: 0 on success, otherwise error
7303 */
7304 int smb2_cancel(struct ksmbd_work *work)
7305 {
7306 struct ksmbd_conn *conn = work->conn;
7307 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
7308 struct smb2_hdr *chdr;
7309 struct ksmbd_work *iter;
7310 struct list_head *command_list;
7311
7312 if (work->next_smb2_rcv_hdr_off)
7313 hdr = ksmbd_resp_buf_next(work);
7314
7315 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7316 hdr->MessageId, hdr->Flags);
7317
7318 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7319 command_list = &conn->async_requests;
7320
7321 spin_lock(&conn->request_lock);
7322 list_for_each_entry(iter, command_list,
7323 async_request_entry) {
7324 chdr = smb_get_msg(iter->request_buf);
7325
7326 if (iter->async_id !=
7327 le64_to_cpu(hdr->Id.AsyncId))
7328 continue;
7329
7330 ksmbd_debug(SMB,
7331 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7332 le64_to_cpu(hdr->Id.AsyncId),
7333 le16_to_cpu(chdr->Command));
7334 iter->state = KSMBD_WORK_CANCELLED;
7335 if (iter->cancel_fn)
7336 iter->cancel_fn(iter->cancel_argv);
7337 break;
7338 }
7339 spin_unlock(&conn->request_lock);
7340 } else {
7341 command_list = &conn->requests;
7342
7343 spin_lock(&conn->request_lock);
7344 list_for_each_entry(iter, command_list, request_entry) {
7345 chdr = smb_get_msg(iter->request_buf);
7346
7347 if (chdr->MessageId != hdr->MessageId ||
7348 iter == work)
7349 continue;
7350
7351 ksmbd_debug(SMB,
7352 "smb2 with mid %llu cancelled command = 0x%x\n",
7353 le64_to_cpu(hdr->MessageId),
7354 le16_to_cpu(chdr->Command));
7355 iter->state = KSMBD_WORK_CANCELLED;
7356 break;
7357 }
7358 spin_unlock(&conn->request_lock);
7359 }
7360
7361 /* For SMB2_CANCEL command itself send no response*/
7362 work->send_no_response = 1;
7363 return 0;
7364 }
7365
7366 struct file_lock *smb_flock_init(struct file *f)
7367 {
7368 struct file_lock *fl;
7369
7370 fl = locks_alloc_lock();
7371 if (!fl)
7372 goto out;
7373
7374 locks_init_lock(fl);
7375
7376 fl->c.flc_owner = f;
7377 fl->c.flc_pid = current->tgid;
7378 fl->c.flc_file = f;
7379 fl->c.flc_flags = FL_POSIX;
7380 fl->fl_ops = NULL;
7381 fl->fl_lmops = NULL;
7382
7383 out:
7384 return fl;
7385 }
7386
7387 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7388 {
7389 int cmd = -EINVAL;
7390
7391 /* Checking for wrong flag combination during lock request*/
7392 switch (flags) {
7393 case SMB2_LOCKFLAG_SHARED:
7394 ksmbd_debug(SMB, "received shared request\n");
7395 cmd = F_SETLKW;
7396 flock->c.flc_type = F_RDLCK;
7397 flock->c.flc_flags |= FL_SLEEP;
7398 break;
7399 case SMB2_LOCKFLAG_EXCLUSIVE:
7400 ksmbd_debug(SMB, "received exclusive request\n");
7401 cmd = F_SETLKW;
7402 flock->c.flc_type = F_WRLCK;
7403 flock->c.flc_flags |= FL_SLEEP;
7404 break;
7405 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7406 ksmbd_debug(SMB,
7407 "received shared & fail immediately request\n");
7408 cmd = F_SETLK;
7409 flock->c.flc_type = F_RDLCK;
7410 break;
7411 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7412 ksmbd_debug(SMB,
7413 "received exclusive & fail immediately request\n");
7414 cmd = F_SETLK;
7415 flock->c.flc_type = F_WRLCK;
7416 break;
7417 case SMB2_LOCKFLAG_UNLOCK:
7418 ksmbd_debug(SMB, "received unlock request\n");
7419 flock->c.flc_type = F_UNLCK;
7420 cmd = F_SETLK;
7421 break;
7422 }
7423
7424 return cmd;
7425 }
7426
7427 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7428 unsigned int cmd, int flags,
7429 struct list_head *lock_list)
7430 {
7431 struct ksmbd_lock *lock;
7432
7433 lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
7434 if (!lock)
7435 return NULL;
7436
7437 lock->cmd = cmd;
7438 lock->fl = flock;
7439 lock->start = flock->fl_start;
7440 lock->end = flock->fl_end;
7441 lock->flags = flags;
7442 if (lock->start == lock->end)
7443 lock->zero_len = 1;
7444 INIT_LIST_HEAD(&lock->clist);
7445 INIT_LIST_HEAD(&lock->flist);
7446 INIT_LIST_HEAD(&lock->llist);
7447 list_add_tail(&lock->llist, lock_list);
7448
7449 return lock;
7450 }
7451
7452 static void smb2_remove_blocked_lock(void **argv)
7453 {
7454 struct file_lock *flock = (struct file_lock *)argv[0];
7455
7456 ksmbd_vfs_posix_lock_unblock(flock);
7457 locks_wake_up(flock);
7458 }
7459
7460 static inline bool lock_defer_pending(struct file_lock *fl)
7461 {
7462 /* check pending lock waiters */
7463 return waitqueue_active(&fl->c.flc_wait);
7464 }
7465
7466 /**
7467 * smb2_lock() - handler for smb2 file lock command
7468 * @work: smb work containing lock command buffer
7469 *
7470 * Return: 0 on success, otherwise error
7471 */
7472 int smb2_lock(struct ksmbd_work *work)
7473 {
7474 struct smb2_lock_req *req;
7475 struct smb2_lock_rsp *rsp;
7476 struct smb2_lock_element *lock_ele;
7477 struct ksmbd_file *fp = NULL;
7478 struct file_lock *flock = NULL;
7479 struct file *filp = NULL;
7480 int lock_count;
7481 int flags = 0;
7482 int cmd = 0;
7483 int err = -EIO, i, rc = 0;
7484 u64 lock_start, lock_length;
7485 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7486 struct ksmbd_conn *conn;
7487 int nolock = 0;
7488 LIST_HEAD(lock_list);
7489 LIST_HEAD(rollback_list);
7490 int prior_lock = 0, bkt;
7491
7492 WORK_BUFFERS(work, req, rsp);
7493
7494 ksmbd_debug(SMB, "Received smb2 lock request\n");
7495 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7496 if (!fp) {
7497 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7498 err = -ENOENT;
7499 goto out2;
7500 }
7501
7502 filp = fp->filp;
7503 lock_count = le16_to_cpu(req->LockCount);
7504 lock_ele = req->locks;
7505
7506 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7507 if (!lock_count) {
7508 err = -EINVAL;
7509 goto out2;
7510 }
7511
7512 for (i = 0; i < lock_count; i++) {
7513 flags = le32_to_cpu(lock_ele[i].Flags);
7514
7515 flock = smb_flock_init(filp);
7516 if (!flock)
7517 goto out;
7518
7519 cmd = smb2_set_flock_flags(flock, flags);
7520
7521 lock_start = le64_to_cpu(lock_ele[i].Offset);
7522 lock_length = le64_to_cpu(lock_ele[i].Length);
7523 if (lock_start > U64_MAX - lock_length) {
7524 pr_err("Invalid lock range requested\n");
7525 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7526 locks_free_lock(flock);
7527 goto out;
7528 }
7529
7530 if (lock_start > OFFSET_MAX)
7531 flock->fl_start = OFFSET_MAX;
7532 else
7533 flock->fl_start = lock_start;
7534
7535 lock_length = le64_to_cpu(lock_ele[i].Length);
7536 if (lock_length > OFFSET_MAX - flock->fl_start)
7537 lock_length = OFFSET_MAX - flock->fl_start;
7538
7539 flock->fl_end = flock->fl_start + lock_length;
7540
7541 if (flock->fl_end < flock->fl_start) {
7542 ksmbd_debug(SMB,
7543 "the end offset(%llx) is smaller than the start offset(%llx)\n",
7544 flock->fl_end, flock->fl_start);
7545 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7546 locks_free_lock(flock);
7547 goto out;
7548 }
7549
7550 /* Check conflict locks in one request */
7551 list_for_each_entry(cmp_lock, &lock_list, llist) {
7552 if (cmp_lock->fl->fl_start <= flock->fl_start &&
7553 cmp_lock->fl->fl_end >= flock->fl_end) {
7554 if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7555 flock->c.flc_type != F_UNLCK) {
7556 pr_err("conflict two locks in one request\n");
7557 err = -EINVAL;
7558 locks_free_lock(flock);
7559 goto out;
7560 }
7561 }
7562 }
7563
7564 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7565 if (!smb_lock) {
7566 err = -EINVAL;
7567 locks_free_lock(flock);
7568 goto out;
7569 }
7570 }
7571
7572 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7573 if (smb_lock->cmd < 0) {
7574 err = -EINVAL;
7575 goto out;
7576 }
7577
7578 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7579 err = -EINVAL;
7580 goto out;
7581 }
7582
7583 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7584 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7585 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7586 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7587 err = -EINVAL;
7588 goto out;
7589 }
7590
7591 prior_lock = smb_lock->flags;
7592
7593 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7594 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7595 goto no_check_cl;
7596
7597 nolock = 1;
7598 /* check locks in connection list */
7599 down_read(&conn_list_lock);
7600 hash_for_each(conn_list, bkt, conn, hlist) {
7601 spin_lock(&conn->llist_lock);
7602 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7603 if (file_inode(cmp_lock->fl->c.flc_file) !=
7604 file_inode(smb_lock->fl->c.flc_file))
7605 continue;
7606
7607 if (lock_is_unlock(smb_lock->fl)) {
7608 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7609 cmp_lock->start == smb_lock->start &&
7610 cmp_lock->end == smb_lock->end &&
7611 !lock_defer_pending(cmp_lock->fl)) {
7612 nolock = 0;
7613 list_del(&cmp_lock->flist);
7614 list_del(&cmp_lock->clist);
7615 spin_unlock(&conn->llist_lock);
7616 up_read(&conn_list_lock);
7617
7618 locks_free_lock(cmp_lock->fl);
7619 kfree(cmp_lock);
7620 goto out_check_cl;
7621 }
7622 continue;
7623 }
7624
7625 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7626 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7627 continue;
7628 } else {
7629 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7630 continue;
7631 }
7632
7633 /* check zero byte lock range */
7634 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7635 cmp_lock->start > smb_lock->start &&
7636 cmp_lock->start < smb_lock->end) {
7637 spin_unlock(&conn->llist_lock);
7638 up_read(&conn_list_lock);
7639 pr_err("previous lock conflict with zero byte lock range\n");
7640 goto out;
7641 }
7642
7643 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7644 smb_lock->start > cmp_lock->start &&
7645 smb_lock->start < cmp_lock->end) {
7646 spin_unlock(&conn->llist_lock);
7647 up_read(&conn_list_lock);
7648 pr_err("current lock conflict with zero byte lock range\n");
7649 goto out;
7650 }
7651
7652 if (((cmp_lock->start <= smb_lock->start &&
7653 cmp_lock->end > smb_lock->start) ||
7654 (cmp_lock->start < smb_lock->end &&
7655 cmp_lock->end >= smb_lock->end)) &&
7656 !cmp_lock->zero_len && !smb_lock->zero_len) {
7657 spin_unlock(&conn->llist_lock);
7658 up_read(&conn_list_lock);
7659 pr_err("Not allow lock operation on exclusive lock range\n");
7660 goto out;
7661 }
7662 }
7663 spin_unlock(&conn->llist_lock);
7664 }
7665 up_read(&conn_list_lock);
7666 out_check_cl:
7667 if (lock_is_unlock(smb_lock->fl) && nolock) {
7668 pr_err("Try to unlock nolocked range\n");
7669 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7670 goto out;
7671 }
7672
7673 no_check_cl:
7674 flock = smb_lock->fl;
7675 list_del(&smb_lock->llist);
7676
7677 if (smb_lock->zero_len) {
7678 err = 0;
7679 goto skip;
7680 }
7681 retry:
7682 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7683 skip:
7684 if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
7685 locks_free_lock(flock);
7686 kfree(smb_lock);
7687 if (!rc) {
7688 ksmbd_debug(SMB, "File unlocked\n");
7689 } else if (rc == -ENOENT) {
7690 rsp->hdr.Status = STATUS_NOT_LOCKED;
7691 err = rc;
7692 goto out;
7693 }
7694 } else {
7695 if (rc == FILE_LOCK_DEFERRED) {
7696 void **argv;
7697
7698 ksmbd_debug(SMB,
7699 "would have to wait for getting lock\n");
7700 list_add(&smb_lock->llist, &rollback_list);
7701
7702 argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
7703 if (!argv) {
7704 err = -ENOMEM;
7705 goto out;
7706 }
7707 argv[0] = flock;
7708
7709 rc = setup_async_work(work,
7710 smb2_remove_blocked_lock,
7711 argv);
7712 if (rc) {
7713 kfree(argv);
7714 err = -ENOMEM;
7715 goto out;
7716 }
7717 spin_lock(&fp->f_lock);
7718 list_add(&work->fp_entry, &fp->blocked_works);
7719 spin_unlock(&fp->f_lock);
7720
7721 smb2_send_interim_resp(work, STATUS_PENDING);
7722
7723 ksmbd_vfs_posix_lock_wait(flock);
7724
7725 spin_lock(&fp->f_lock);
7726 list_del(&work->fp_entry);
7727 spin_unlock(&fp->f_lock);
7728
7729 if (work->state != KSMBD_WORK_ACTIVE) {
7730 list_del(&smb_lock->llist);
7731 locks_free_lock(flock);
7732
7733 if (work->state == KSMBD_WORK_CANCELLED) {
7734 rsp->hdr.Status =
7735 STATUS_CANCELLED;
7736 kfree(smb_lock);
7737 smb2_send_interim_resp(work,
7738 STATUS_CANCELLED);
7739 work->send_no_response = 1;
7740 goto out;
7741 }
7742
7743 rsp->hdr.Status =
7744 STATUS_RANGE_NOT_LOCKED;
7745 kfree(smb_lock);
7746 goto out2;
7747 }
7748
7749 list_del(&smb_lock->llist);
7750 release_async_work(work);
7751 goto retry;
7752 } else if (!rc) {
7753 list_add(&smb_lock->llist, &rollback_list);
7754 spin_lock(&work->conn->llist_lock);
7755 list_add_tail(&smb_lock->clist,
7756 &work->conn->lock_list);
7757 list_add_tail(&smb_lock->flist,
7758 &fp->lock_list);
7759 spin_unlock(&work->conn->llist_lock);
7760 ksmbd_debug(SMB, "successful in taking lock\n");
7761 } else {
7762 locks_free_lock(flock);
7763 kfree(smb_lock);
7764 err = rc;
7765 goto out;
7766 }
7767 }
7768 }
7769
7770 if (atomic_read(&fp->f_ci->op_count) > 1)
7771 smb_break_all_oplock(work, fp);
7772
7773 rsp->StructureSize = cpu_to_le16(4);
7774 ksmbd_debug(SMB, "successful in taking lock\n");
7775 rsp->hdr.Status = STATUS_SUCCESS;
7776 rsp->Reserved = 0;
7777 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7778 if (err)
7779 goto out;
7780
7781 ksmbd_fd_put(work, fp);
7782 return 0;
7783
7784 out:
7785 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7786 locks_free_lock(smb_lock->fl);
7787 list_del(&smb_lock->llist);
7788 kfree(smb_lock);
7789 }
7790
7791 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7792 struct file_lock *rlock = NULL;
7793
7794 rlock = smb_flock_init(filp);
7795 if (rlock) {
7796 rlock->c.flc_type = F_UNLCK;
7797 rlock->fl_start = smb_lock->start;
7798 rlock->fl_end = smb_lock->end;
7799
7800 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7801 if (rc)
7802 pr_err("rollback unlock fail : %d\n", rc);
7803 } else {
7804 pr_err("rollback unlock alloc failed\n");
7805 }
7806
7807 list_del(&smb_lock->llist);
7808 spin_lock(&work->conn->llist_lock);
7809 if (!list_empty(&smb_lock->flist))
7810 list_del(&smb_lock->flist);
7811 list_del(&smb_lock->clist);
7812 spin_unlock(&work->conn->llist_lock);
7813
7814 locks_free_lock(smb_lock->fl);
7815 if (rlock)
7816 locks_free_lock(rlock);
7817 kfree(smb_lock);
7818 }
7819 out2:
7820 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7821
7822 if (!rsp->hdr.Status) {
7823 if (err == -EINVAL)
7824 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7825 else if (err == -ENOMEM)
7826 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7827 else if (err == -ENOENT)
7828 rsp->hdr.Status = STATUS_FILE_CLOSED;
7829 else
7830 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7831 }
7832
7833 smb2_set_err_rsp(work);
7834 ksmbd_fd_put(work, fp);
7835 return err;
7836 }
7837
7838 static int fsctl_copychunk(struct ksmbd_work *work,
7839 struct copychunk_ioctl_req *ci_req,
7840 unsigned int cnt_code,
7841 unsigned int input_count,
7842 unsigned long long volatile_id,
7843 unsigned long long persistent_id,
7844 struct smb2_ioctl_rsp *rsp)
7845 {
7846 struct copychunk_ioctl_rsp *ci_rsp;
7847 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7848 struct srv_copychunk *chunks;
7849 unsigned int i, chunk_count, chunk_count_written = 0;
7850 unsigned int chunk_size_written = 0;
7851 loff_t total_size_written = 0;
7852 int ret = 0;
7853
7854 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7855
7856 rsp->VolatileFileId = volatile_id;
7857 rsp->PersistentFileId = persistent_id;
7858 ci_rsp->ChunksWritten =
7859 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7860 ci_rsp->ChunkBytesWritten =
7861 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7862 ci_rsp->TotalBytesWritten =
7863 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7864
7865 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7866 if (chunk_count == 0)
7867 goto out;
7868 total_size_written = 0;
7869
7870 /* verify the SRV_COPYCHUNK_COPY packet */
7871 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7872 input_count < struct_size(ci_req, Chunks, chunk_count)) {
7873 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7874 return -EINVAL;
7875 }
7876
7877 chunks = &ci_req->Chunks[0];
7878 for (i = 0; i < chunk_count; i++) {
7879 if (le32_to_cpu(chunks[i].Length) == 0 ||
7880 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7881 break;
7882 total_size_written += le32_to_cpu(chunks[i].Length);
7883 }
7884
7885 if (i < chunk_count ||
7886 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7887 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7888 return -EINVAL;
7889 }
7890
7891 src_fp = ksmbd_lookup_foreign_fd(work,
7892 le64_to_cpu(ci_req->SourceKeyU64[0]));
7893 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7894 ret = -EINVAL;
7895 if (!src_fp ||
7896 src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
7897 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7898 goto out;
7899 }
7900
7901 if (!dst_fp) {
7902 rsp->hdr.Status = STATUS_FILE_CLOSED;
7903 goto out;
7904 }
7905
7906 /*
7907 * FILE_READ_DATA should only be included in
7908 * the FSCTL_COPYCHUNK case
7909 */
7910 if (cnt_code == FSCTL_COPYCHUNK &&
7911 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7912 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7913 goto out;
7914 }
7915
7916 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7917 chunks, chunk_count,
7918 &chunk_count_written,
7919 &chunk_size_written,
7920 &total_size_written);
7921 if (ret < 0) {
7922 if (ret == -EACCES)
7923 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7924 if (ret == -EAGAIN)
7925 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7926 else if (ret == -EBADF)
7927 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7928 else if (ret == -EFBIG || ret == -ENOSPC)
7929 rsp->hdr.Status = STATUS_DISK_FULL;
7930 else if (ret == -EINVAL)
7931 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7932 else if (ret == -EISDIR)
7933 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7934 else if (ret == -E2BIG)
7935 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7936 else
7937 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7938 }
7939
7940 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7941 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7942 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7943 out:
7944 ksmbd_fd_put(work, src_fp);
7945 ksmbd_fd_put(work, dst_fp);
7946 return ret;
7947 }
7948
7949 static __be32 idev_ipv4_address(struct in_device *idev)
7950 {
7951 __be32 addr = 0;
7952
7953 struct in_ifaddr *ifa;
7954
7955 rcu_read_lock();
7956 in_dev_for_each_ifa_rcu(ifa, idev) {
7957 if (ifa->ifa_flags & IFA_F_SECONDARY)
7958 continue;
7959
7960 addr = ifa->ifa_address;
7961 break;
7962 }
7963 rcu_read_unlock();
7964 return addr;
7965 }
7966
7967 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7968 struct smb2_ioctl_rsp *rsp,
7969 unsigned int out_buf_len)
7970 {
7971 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7972 int nbytes = 0;
7973 struct net_device *netdev;
7974 struct sockaddr_storage_rsp *sockaddr_storage;
7975 unsigned int flags;
7976 unsigned long long speed;
7977
7978 rtnl_lock();
7979 for_each_netdev(&init_net, netdev) {
7980 bool ipv4_set = false;
7981
7982 if (netdev->type == ARPHRD_LOOPBACK)
7983 continue;
7984
7985 if (!ksmbd_find_netdev_name_iface_list(netdev->name))
7986 continue;
7987
7988 flags = netif_get_flags(netdev);
7989 if (!(flags & IFF_RUNNING))
7990 continue;
7991 ipv6_retry:
7992 if (out_buf_len <
7993 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7994 rtnl_unlock();
7995 return -ENOSPC;
7996 }
7997
7998 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7999 &rsp->Buffer[nbytes];
8000 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
8001
8002 nii_rsp->Capability = 0;
8003 if (netdev->real_num_tx_queues > 1)
8004 nii_rsp->Capability |= RSS_CAPABLE;
8005 if (ksmbd_rdma_capable_netdev(netdev))
8006 nii_rsp->Capability |= RDMA_CAPABLE;
8007
8008 nii_rsp->Next = cpu_to_le32(152);
8009 nii_rsp->Reserved = 0;
8010
8011 if (netdev->ethtool_ops->get_link_ksettings) {
8012 struct ethtool_link_ksettings cmd;
8013
8014 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
8015 speed = cmd.base.speed;
8016 } else {
8017 ksmbd_debug(SMB, "%s %s\n", netdev->name,
8018 "speed is unknown, defaulting to 1Gb/sec");
8019 speed = SPEED_1000;
8020 }
8021
8022 speed *= 1000000;
8023 nii_rsp->LinkSpeed = cpu_to_le64(speed);
8024
8025 sockaddr_storage = (struct sockaddr_storage_rsp *)
8026 nii_rsp->SockAddr_Storage;
8027 memset(sockaddr_storage, 0, 128);
8028
8029 if (!ipv4_set) {
8030 struct in_device *idev;
8031
8032 sockaddr_storage->Family = INTERNETWORK;
8033 sockaddr_storage->addr4.Port = 0;
8034
8035 idev = __in_dev_get_rtnl(netdev);
8036 if (!idev)
8037 continue;
8038 sockaddr_storage->addr4.IPv4Address =
8039 idev_ipv4_address(idev);
8040 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8041 ipv4_set = true;
8042 goto ipv6_retry;
8043 } else {
8044 struct inet6_dev *idev6;
8045 struct inet6_ifaddr *ifa;
8046 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
8047
8048 sockaddr_storage->Family = INTERNETWORKV6;
8049 sockaddr_storage->addr6.Port = 0;
8050 sockaddr_storage->addr6.FlowInfo = 0;
8051
8052 idev6 = __in6_dev_get(netdev);
8053 if (!idev6)
8054 continue;
8055
8056 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
8057 if (ifa->flags & (IFA_F_TENTATIVE |
8058 IFA_F_DEPRECATED))
8059 continue;
8060 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
8061 break;
8062 }
8063 sockaddr_storage->addr6.ScopeId = 0;
8064 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8065 }
8066 }
8067 rtnl_unlock();
8068
8069 /* zero if this is last one */
8070 if (nii_rsp)
8071 nii_rsp->Next = 0;
8072
8073 rsp->PersistentFileId = SMB2_NO_FID;
8074 rsp->VolatileFileId = SMB2_NO_FID;
8075 return nbytes;
8076 }
8077
8078 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
8079 struct validate_negotiate_info_req *neg_req,
8080 struct validate_negotiate_info_rsp *neg_rsp,
8081 unsigned int in_buf_len)
8082 {
8083 int ret = 0;
8084 int dialect;
8085
8086 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
8087 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
8088 return -EINVAL;
8089
8090 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
8091 neg_req->DialectCount);
8092 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
8093 ret = -EINVAL;
8094 goto err_out;
8095 }
8096
8097 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
8098 ret = -EINVAL;
8099 goto err_out;
8100 }
8101
8102 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
8103 ret = -EINVAL;
8104 goto err_out;
8105 }
8106
8107 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
8108 ret = -EINVAL;
8109 goto err_out;
8110 }
8111
8112 neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
8113 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
8114 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
8115 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
8116 err_out:
8117 return ret;
8118 }
8119
8120 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
8121 struct file_allocated_range_buffer *qar_req,
8122 struct file_allocated_range_buffer *qar_rsp,
8123 unsigned int in_count, unsigned int *out_count)
8124 {
8125 struct ksmbd_file *fp;
8126 loff_t start, length;
8127 int ret = 0;
8128
8129 *out_count = 0;
8130 if (in_count == 0)
8131 return -EINVAL;
8132
8133 start = le64_to_cpu(qar_req->file_offset);
8134 length = le64_to_cpu(qar_req->length);
8135
8136 if (start < 0 || length < 0)
8137 return -EINVAL;
8138
8139 fp = ksmbd_lookup_fd_fast(work, id);
8140 if (!fp)
8141 return -ENOENT;
8142
8143 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8144 qar_rsp, in_count, out_count);
8145 if (ret && ret != -E2BIG)
8146 *out_count = 0;
8147
8148 ksmbd_fd_put(work, fp);
8149 return ret;
8150 }
8151
8152 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8153 unsigned int out_buf_len,
8154 struct smb2_ioctl_req *req,
8155 struct smb2_ioctl_rsp *rsp)
8156 {
8157 struct ksmbd_rpc_command *rpc_resp;
8158 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8159 int nbytes = 0;
8160
8161 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8162 le32_to_cpu(req->InputCount));
8163 if (rpc_resp) {
8164 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8165 /*
8166 * set STATUS_SOME_NOT_MAPPED response
8167 * for unknown domain sid.
8168 */
8169 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8170 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8171 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8172 goto out;
8173 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
8174 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8175 goto out;
8176 }
8177
8178 nbytes = rpc_resp->payload_sz;
8179 if (rpc_resp->payload_sz > out_buf_len) {
8180 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8181 nbytes = out_buf_len;
8182 }
8183
8184 if (!rpc_resp->payload_sz) {
8185 rsp->hdr.Status =
8186 STATUS_UNEXPECTED_IO_ERROR;
8187 goto out;
8188 }
8189
8190 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8191 }
8192 out:
8193 kvfree(rpc_resp);
8194 return nbytes;
8195 }
8196
8197 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8198 struct file_sparse *sparse)
8199 {
8200 struct ksmbd_file *fp;
8201 struct mnt_idmap *idmap;
8202 int ret = 0;
8203 __le32 old_fattr;
8204
8205 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8206 ksmbd_debug(SMB, "User does not have write permission\n");
8207 return -EACCES;
8208 }
8209
8210 fp = ksmbd_lookup_fd_fast(work, id);
8211 if (!fp)
8212 return -ENOENT;
8213
8214 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_WRITE_ATTRIBUTES_LE))) {
8215 ret = -EACCES;
8216 goto out;
8217 }
8218
8219 idmap = file_mnt_idmap(fp->filp);
8220
8221 old_fattr = fp->f_ci->m_fattr;
8222 if (sparse->SetSparse)
8223 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8224 else
8225 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8226
8227 if (fp->f_ci->m_fattr != old_fattr &&
8228 test_share_config_flag(work->tcon->share_conf,
8229 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8230 struct xattr_dos_attrib da;
8231
8232 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8233 fp->filp->f_path.dentry, &da);
8234 if (ret <= 0)
8235 goto out;
8236
8237 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8238 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8239 &fp->filp->f_path,
8240 &da, true);
8241 if (ret)
8242 fp->f_ci->m_fattr = old_fattr;
8243 }
8244
8245 out:
8246 ksmbd_fd_put(work, fp);
8247 return ret;
8248 }
8249
8250 static int fsctl_request_resume_key(struct ksmbd_work *work,
8251 struct smb2_ioctl_req *req,
8252 struct resume_key_ioctl_rsp *key_rsp)
8253 {
8254 struct ksmbd_file *fp;
8255
8256 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8257 if (!fp)
8258 return -ENOENT;
8259
8260 memset(key_rsp, 0, sizeof(*key_rsp));
8261 key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
8262 key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
8263 ksmbd_fd_put(work, fp);
8264
8265 return 0;
8266 }
8267
8268 /**
8269 * smb2_ioctl() - handler for smb2 ioctl command
8270 * @work: smb work containing ioctl command buffer
8271 *
8272 * Return: 0 on success, otherwise error
8273 */
8274 int smb2_ioctl(struct ksmbd_work *work)
8275 {
8276 struct smb2_ioctl_req *req;
8277 struct smb2_ioctl_rsp *rsp;
8278 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8279 u64 id = KSMBD_NO_FID;
8280 struct ksmbd_conn *conn = work->conn;
8281 int ret = 0;
8282 char *buffer;
8283
8284 ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8285
8286 if (work->next_smb2_rcv_hdr_off) {
8287 req = ksmbd_req_buf_next(work);
8288 rsp = ksmbd_resp_buf_next(work);
8289 if (!has_file_id(req->VolatileFileId)) {
8290 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8291 work->compound_fid);
8292 id = work->compound_fid;
8293 }
8294 } else {
8295 req = smb_get_msg(work->request_buf);
8296 rsp = smb_get_msg(work->response_buf);
8297 }
8298
8299 if (!has_file_id(id))
8300 id = req->VolatileFileId;
8301
8302 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8303 ret = -EOPNOTSUPP;
8304 goto out;
8305 }
8306
8307 buffer = (char *)req + le32_to_cpu(req->InputOffset);
8308
8309 cnt_code = le32_to_cpu(req->CtlCode);
8310 ret = smb2_calc_max_out_buf_len(work,
8311 offsetof(struct smb2_ioctl_rsp, Buffer),
8312 le32_to_cpu(req->MaxOutputResponse));
8313 if (ret < 0) {
8314 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8315 goto out;
8316 }
8317 out_buf_len = (unsigned int)ret;
8318 in_buf_len = le32_to_cpu(req->InputCount);
8319
8320 switch (cnt_code) {
8321 case FSCTL_DFS_GET_REFERRALS:
8322 case FSCTL_DFS_GET_REFERRALS_EX:
8323 /* Not support DFS yet */
8324 ret = -EOPNOTSUPP;
8325 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8326 goto out2;
8327 case FSCTL_CREATE_OR_GET_OBJECT_ID:
8328 {
8329 struct file_object_buf_type1_ioctl_rsp *obj_buf;
8330
8331 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8332 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8333 &rsp->Buffer[0];
8334
8335 /*
8336 * TODO: This is dummy implementation to pass smbtorture
8337 * Need to check correct response later
8338 */
8339 memset(obj_buf->ObjectId, 0x0, 16);
8340 memset(obj_buf->BirthVolumeId, 0x0, 16);
8341 memset(obj_buf->BirthObjectId, 0x0, 16);
8342 memset(obj_buf->DomainId, 0x0, 16);
8343
8344 break;
8345 }
8346 case FSCTL_PIPE_TRANSCEIVE:
8347 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8348 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8349 break;
8350 case FSCTL_VALIDATE_NEGOTIATE_INFO:
8351 if (conn->dialect < SMB30_PROT_ID) {
8352 ret = -EOPNOTSUPP;
8353 goto out;
8354 }
8355
8356 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8357 Dialects)) {
8358 ret = -EINVAL;
8359 goto out;
8360 }
8361
8362 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8363 ret = -EINVAL;
8364 goto out;
8365 }
8366
8367 ret = fsctl_validate_negotiate_info(conn,
8368 (struct validate_negotiate_info_req *)buffer,
8369 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8370 in_buf_len);
8371 if (ret < 0)
8372 goto out;
8373
8374 nbytes = sizeof(struct validate_negotiate_info_rsp);
8375 rsp->PersistentFileId = SMB2_NO_FID;
8376 rsp->VolatileFileId = SMB2_NO_FID;
8377 break;
8378 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8379 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8380 if (ret < 0)
8381 goto out;
8382 nbytes = ret;
8383 break;
8384 case FSCTL_REQUEST_RESUME_KEY:
8385 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8386 ret = -EINVAL;
8387 goto out;
8388 }
8389
8390 ret = fsctl_request_resume_key(work, req,
8391 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8392 if (ret < 0)
8393 goto out;
8394 rsp->PersistentFileId = req->PersistentFileId;
8395 rsp->VolatileFileId = req->VolatileFileId;
8396 nbytes = sizeof(struct resume_key_ioctl_rsp);
8397 break;
8398 case FSCTL_COPYCHUNK:
8399 case FSCTL_COPYCHUNK_WRITE:
8400 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8401 ksmbd_debug(SMB,
8402 "User does not have write permission\n");
8403 ret = -EACCES;
8404 goto out;
8405 }
8406
8407 if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
8408 ret = -EINVAL;
8409 goto out;
8410 }
8411
8412 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8413 ret = -EINVAL;
8414 goto out;
8415 }
8416
8417 nbytes = sizeof(struct copychunk_ioctl_rsp);
8418 rsp->VolatileFileId = req->VolatileFileId;
8419 rsp->PersistentFileId = req->PersistentFileId;
8420 fsctl_copychunk(work,
8421 (struct copychunk_ioctl_req *)buffer,
8422 le32_to_cpu(req->CtlCode),
8423 le32_to_cpu(req->InputCount),
8424 req->VolatileFileId,
8425 req->PersistentFileId,
8426 rsp);
8427 break;
8428 case FSCTL_SET_SPARSE:
8429 if (in_buf_len < sizeof(struct file_sparse)) {
8430 ret = -EINVAL;
8431 goto out;
8432 }
8433
8434 ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8435 if (ret < 0)
8436 goto out;
8437 break;
8438 case FSCTL_SET_ZERO_DATA:
8439 {
8440 struct file_zero_data_information *zero_data;
8441 struct ksmbd_file *fp;
8442 loff_t off, len, bfz;
8443
8444 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8445 ksmbd_debug(SMB,
8446 "User does not have write permission\n");
8447 ret = -EACCES;
8448 goto out;
8449 }
8450
8451 if (in_buf_len < sizeof(struct file_zero_data_information)) {
8452 ret = -EINVAL;
8453 goto out;
8454 }
8455
8456 zero_data =
8457 (struct file_zero_data_information *)buffer;
8458
8459 off = le64_to_cpu(zero_data->FileOffset);
8460 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8461 if (off < 0 || bfz < 0 || off > bfz) {
8462 ret = -EINVAL;
8463 goto out;
8464 }
8465
8466 len = bfz - off;
8467 if (len) {
8468 fp = ksmbd_lookup_fd_fast(work, id);
8469 if (!fp) {
8470 ret = -ENOENT;
8471 goto out;
8472 }
8473
8474 ret = ksmbd_vfs_zero_data(work, fp, off, len);
8475 ksmbd_fd_put(work, fp);
8476 if (ret < 0)
8477 goto out;
8478 }
8479 break;
8480 }
8481 case FSCTL_QUERY_ALLOCATED_RANGES:
8482 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8483 ret = -EINVAL;
8484 goto out;
8485 }
8486
8487 ret = fsctl_query_allocated_ranges(work, id,
8488 (struct file_allocated_range_buffer *)buffer,
8489 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
8490 out_buf_len /
8491 sizeof(struct file_allocated_range_buffer), &nbytes);
8492 if (ret == -E2BIG) {
8493 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8494 } else if (ret < 0) {
8495 nbytes = 0;
8496 goto out;
8497 }
8498
8499 nbytes *= sizeof(struct file_allocated_range_buffer);
8500 break;
8501 case FSCTL_GET_REPARSE_POINT:
8502 {
8503 struct reparse_data_buffer *reparse_ptr;
8504 struct ksmbd_file *fp;
8505
8506 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8507 fp = ksmbd_lookup_fd_fast(work, id);
8508 if (!fp) {
8509 pr_err("not found fp!!\n");
8510 ret = -ENOENT;
8511 goto out;
8512 }
8513
8514 reparse_ptr->ReparseTag =
8515 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8516 reparse_ptr->ReparseDataLength = 0;
8517 ksmbd_fd_put(work, fp);
8518 nbytes = sizeof(struct reparse_data_buffer);
8519 break;
8520 }
8521 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8522 {
8523 struct ksmbd_file *fp_in, *fp_out = NULL;
8524 struct duplicate_extents_to_file *dup_ext;
8525 loff_t src_off, dst_off, length, cloned;
8526
8527 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8528 ret = -EINVAL;
8529 goto out;
8530 }
8531
8532 dup_ext = (struct duplicate_extents_to_file *)buffer;
8533
8534 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8535 dup_ext->PersistentFileHandle);
8536 if (!fp_in) {
8537 pr_err("not found file handle in duplicate extent to file\n");
8538 ret = -ENOENT;
8539 goto out;
8540 }
8541
8542 fp_out = ksmbd_lookup_fd_fast(work, id);
8543 if (!fp_out) {
8544 pr_err("not found fp\n");
8545 ret = -ENOENT;
8546 goto dup_ext_out;
8547 }
8548
8549 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8550 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8551 length = le64_to_cpu(dup_ext->ByteCount);
8552 /*
8553 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8554 * should fall back to vfs_copy_file_range(). This could be
8555 * beneficial when re-exporting nfs/smb mount, but note that
8556 * this can result in partial copy that returns an error status.
8557 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8558 * fall back to vfs_copy_file_range(), should be avoided when
8559 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8560 */
8561 cloned = vfs_clone_file_range(fp_in->filp, src_off,
8562 fp_out->filp, dst_off, length, 0);
8563 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8564 ret = -EOPNOTSUPP;
8565 goto dup_ext_out;
8566 } else if (cloned != length) {
8567 cloned = vfs_copy_file_range(fp_in->filp, src_off,
8568 fp_out->filp, dst_off,
8569 length, 0);
8570 if (cloned != length) {
8571 if (cloned < 0)
8572 ret = cloned;
8573 else
8574 ret = -EINVAL;
8575 }
8576 }
8577
8578 dup_ext_out:
8579 ksmbd_fd_put(work, fp_in);
8580 ksmbd_fd_put(work, fp_out);
8581 if (ret < 0)
8582 goto out;
8583 break;
8584 }
8585 default:
8586 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8587 cnt_code);
8588 ret = -EOPNOTSUPP;
8589 goto out;
8590 }
8591
8592 rsp->CtlCode = cpu_to_le32(cnt_code);
8593 rsp->InputCount = cpu_to_le32(0);
8594 rsp->InputOffset = cpu_to_le32(112);
8595 rsp->OutputOffset = cpu_to_le32(112);
8596 rsp->OutputCount = cpu_to_le32(nbytes);
8597 rsp->StructureSize = cpu_to_le16(49);
8598 rsp->Reserved = cpu_to_le16(0);
8599 rsp->Flags = cpu_to_le32(0);
8600 rsp->Reserved2 = cpu_to_le32(0);
8601 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8602 if (!ret)
8603 return ret;
8604
8605 out:
8606 if (ret == -EACCES)
8607 rsp->hdr.Status = STATUS_ACCESS_DENIED;
8608 else if (ret == -ENOENT)
8609 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8610 else if (ret == -EOPNOTSUPP)
8611 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8612 else if (ret == -ENOSPC)
8613 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8614 else if (ret < 0 || rsp->hdr.Status == 0)
8615 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8616
8617 out2:
8618 smb2_set_err_rsp(work);
8619 return ret;
8620 }
8621
8622 /**
8623 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8624 * @work: smb work containing oplock break command buffer
8625 *
8626 * Return: 0
8627 */
8628 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8629 {
8630 struct smb2_oplock_break *req;
8631 struct smb2_oplock_break *rsp;
8632 struct ksmbd_file *fp;
8633 struct oplock_info *opinfo = NULL;
8634 __le32 err = 0;
8635 int ret = 0;
8636 u64 volatile_id, persistent_id;
8637 char req_oplevel = 0, rsp_oplevel = 0;
8638 unsigned int oplock_change_type;
8639
8640 WORK_BUFFERS(work, req, rsp);
8641
8642 volatile_id = req->VolatileFid;
8643 persistent_id = req->PersistentFid;
8644 req_oplevel = req->OplockLevel;
8645 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8646 volatile_id, persistent_id, req_oplevel);
8647
8648 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8649 if (!fp) {
8650 rsp->hdr.Status = STATUS_FILE_CLOSED;
8651 smb2_set_err_rsp(work);
8652 return;
8653 }
8654
8655 opinfo = opinfo_get(fp);
8656 if (!opinfo) {
8657 pr_err("unexpected null oplock_info\n");
8658 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8659 smb2_set_err_rsp(work);
8660 ksmbd_fd_put(work, fp);
8661 return;
8662 }
8663
8664 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8665 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8666 goto err_out;
8667 }
8668
8669 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8670 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8671 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8672 goto err_out;
8673 }
8674
8675 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8676 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8677 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8678 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8679 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8680 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8681 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8682 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8683 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8684 oplock_change_type = OPLOCK_READ_TO_NONE;
8685 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8686 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8687 err = STATUS_INVALID_DEVICE_STATE;
8688 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8689 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8690 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8691 oplock_change_type = OPLOCK_WRITE_TO_READ;
8692 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8693 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8694 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8695 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8696 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8697 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8698 oplock_change_type = OPLOCK_READ_TO_NONE;
8699 } else {
8700 oplock_change_type = 0;
8701 }
8702 } else {
8703 oplock_change_type = 0;
8704 }
8705
8706 switch (oplock_change_type) {
8707 case OPLOCK_WRITE_TO_READ:
8708 ret = opinfo_write_to_read(opinfo);
8709 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8710 break;
8711 case OPLOCK_WRITE_TO_NONE:
8712 ret = opinfo_write_to_none(opinfo);
8713 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8714 break;
8715 case OPLOCK_READ_TO_NONE:
8716 ret = opinfo_read_to_none(opinfo);
8717 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8718 break;
8719 default:
8720 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8721 opinfo->level, rsp_oplevel);
8722 }
8723
8724 if (ret < 0) {
8725 rsp->hdr.Status = err;
8726 goto err_out;
8727 }
8728
8729 rsp->StructureSize = cpu_to_le16(24);
8730 rsp->OplockLevel = rsp_oplevel;
8731 rsp->Reserved = 0;
8732 rsp->Reserved2 = 0;
8733 rsp->VolatileFid = volatile_id;
8734 rsp->PersistentFid = persistent_id;
8735 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8736 if (ret) {
8737 err_out:
8738 smb2_set_err_rsp(work);
8739 }
8740
8741 opinfo->op_state = OPLOCK_STATE_NONE;
8742 wake_up_interruptible_all(&opinfo->oplock_q);
8743 opinfo_put(opinfo);
8744 ksmbd_fd_put(work, fp);
8745 }
8746
8747 static int check_lease_state(struct lease *lease, __le32 req_state)
8748 {
8749 if ((lease->new_state ==
8750 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8751 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8752 lease->new_state = req_state;
8753 return 0;
8754 }
8755
8756 if (lease->new_state == req_state)
8757 return 0;
8758
8759 return 1;
8760 }
8761
8762 /**
8763 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8764 * @work: smb work containing lease break command buffer
8765 *
8766 * Return: 0
8767 */
8768 static void smb21_lease_break_ack(struct ksmbd_work *work)
8769 {
8770 struct ksmbd_conn *conn = work->conn;
8771 struct smb2_lease_ack *req;
8772 struct smb2_lease_ack *rsp;
8773 struct oplock_info *opinfo;
8774 __le32 err = 0;
8775 int ret = 0;
8776 unsigned int lease_change_type;
8777 __le32 lease_state;
8778 struct lease *lease;
8779
8780 WORK_BUFFERS(work, req, rsp);
8781
8782 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8783 le32_to_cpu(req->LeaseState));
8784 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8785 if (!opinfo) {
8786 ksmbd_debug(OPLOCK, "file not opened\n");
8787 smb2_set_err_rsp(work);
8788 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8789 return;
8790 }
8791 lease = opinfo->o_lease;
8792
8793 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8794 pr_err("unexpected lease break state 0x%x\n",
8795 opinfo->op_state);
8796 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8797 goto err_out;
8798 }
8799
8800 if (check_lease_state(lease, req->LeaseState)) {
8801 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8802 ksmbd_debug(OPLOCK,
8803 "req lease state: 0x%x, expected state: 0x%x\n",
8804 req->LeaseState, lease->new_state);
8805 goto err_out;
8806 }
8807
8808 if (!atomic_read(&opinfo->breaking_cnt)) {
8809 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8810 goto err_out;
8811 }
8812
8813 /* check for bad lease state */
8814 if (req->LeaseState &
8815 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8816 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8817 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8818 lease_change_type = OPLOCK_WRITE_TO_NONE;
8819 else
8820 lease_change_type = OPLOCK_READ_TO_NONE;
8821 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8822 le32_to_cpu(lease->state),
8823 le32_to_cpu(req->LeaseState));
8824 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8825 req->LeaseState != SMB2_LEASE_NONE_LE) {
8826 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8827 lease_change_type = OPLOCK_READ_TO_NONE;
8828 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8829 le32_to_cpu(lease->state),
8830 le32_to_cpu(req->LeaseState));
8831 } else {
8832 /* valid lease state changes */
8833 err = STATUS_INVALID_DEVICE_STATE;
8834 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8835 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8836 lease_change_type = OPLOCK_WRITE_TO_NONE;
8837 else
8838 lease_change_type = OPLOCK_READ_TO_NONE;
8839 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8840 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8841 lease_change_type = OPLOCK_WRITE_TO_READ;
8842 else
8843 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8844 } else {
8845 lease_change_type = 0;
8846 }
8847 }
8848
8849 switch (lease_change_type) {
8850 case OPLOCK_WRITE_TO_READ:
8851 ret = opinfo_write_to_read(opinfo);
8852 break;
8853 case OPLOCK_READ_HANDLE_TO_READ:
8854 ret = opinfo_read_handle_to_read(opinfo);
8855 break;
8856 case OPLOCK_WRITE_TO_NONE:
8857 ret = opinfo_write_to_none(opinfo);
8858 break;
8859 case OPLOCK_READ_TO_NONE:
8860 ret = opinfo_read_to_none(opinfo);
8861 break;
8862 default:
8863 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8864 le32_to_cpu(lease->state),
8865 le32_to_cpu(req->LeaseState));
8866 }
8867
8868 if (ret < 0) {
8869 rsp->hdr.Status = err;
8870 goto err_out;
8871 }
8872
8873 lease_state = lease->state;
8874
8875 rsp->StructureSize = cpu_to_le16(36);
8876 rsp->Reserved = 0;
8877 rsp->Flags = 0;
8878 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8879 rsp->LeaseState = lease_state;
8880 rsp->LeaseDuration = 0;
8881 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8882 if (ret) {
8883 err_out:
8884 smb2_set_err_rsp(work);
8885 }
8886
8887 opinfo->op_state = OPLOCK_STATE_NONE;
8888 wake_up_interruptible_all(&opinfo->oplock_q);
8889 atomic_dec(&opinfo->breaking_cnt);
8890 wake_up_interruptible_all(&opinfo->oplock_brk);
8891 opinfo_put(opinfo);
8892 }
8893
8894 /**
8895 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8896 * @work: smb work containing oplock/lease break command buffer
8897 *
8898 * Return: 0 on success, otherwise error
8899 */
8900 int smb2_oplock_break(struct ksmbd_work *work)
8901 {
8902 struct smb2_oplock_break *req;
8903 struct smb2_oplock_break *rsp;
8904
8905 ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
8906
8907 WORK_BUFFERS(work, req, rsp);
8908
8909 switch (le16_to_cpu(req->StructureSize)) {
8910 case OP_BREAK_STRUCT_SIZE_20:
8911 smb20_oplock_break_ack(work);
8912 break;
8913 case OP_BREAK_STRUCT_SIZE_21:
8914 smb21_lease_break_ack(work);
8915 break;
8916 default:
8917 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8918 le16_to_cpu(req->StructureSize));
8919 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8920 smb2_set_err_rsp(work);
8921 return -EINVAL;
8922 }
8923
8924 return 0;
8925 }
8926
8927 /**
8928 * smb2_notify() - handler for smb2 notify request
8929 * @work: smb work containing notify command buffer
8930 *
8931 * Return: 0 on success, otherwise error
8932 */
8933 int smb2_notify(struct ksmbd_work *work)
8934 {
8935 struct smb2_change_notify_req *req;
8936 struct smb2_change_notify_rsp *rsp;
8937
8938 ksmbd_debug(SMB, "Received smb2 notify\n");
8939
8940 WORK_BUFFERS(work, req, rsp);
8941
8942 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8943 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8944 smb2_set_err_rsp(work);
8945 return -EIO;
8946 }
8947
8948 smb2_set_err_rsp(work);
8949 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8950 return -EOPNOTSUPP;
8951 }
8952
8953 /**
8954 * smb2_is_sign_req() - handler for checking packet signing status
8955 * @work: smb work containing notify command buffer
8956 * @command: SMB2 command id
8957 *
8958 * Return: true if packed is signed, false otherwise
8959 */
8960 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8961 {
8962 struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
8963
8964 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8965 command != SMB2_NEGOTIATE_HE &&
8966 command != SMB2_SESSION_SETUP_HE &&
8967 command != SMB2_OPLOCK_BREAK_HE)
8968 return true;
8969
8970 return false;
8971 }
8972
8973 /**
8974 * smb2_check_sign_req() - handler for req packet sign processing
8975 * @work: smb work containing notify command buffer
8976 *
8977 * Return: 1 on success, 0 otherwise
8978 */
8979 int smb2_check_sign_req(struct ksmbd_work *work)
8980 {
8981 struct smb2_hdr *hdr;
8982 char signature_req[SMB2_SIGNATURE_SIZE];
8983 char signature[SMB2_HMACSHA256_SIZE];
8984 struct kvec iov[1];
8985 size_t len;
8986
8987 hdr = smb_get_msg(work->request_buf);
8988 if (work->next_smb2_rcv_hdr_off)
8989 hdr = ksmbd_req_buf_next(work);
8990
8991 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8992 len = get_rfc1002_len(work->request_buf);
8993 else if (hdr->NextCommand)
8994 len = le32_to_cpu(hdr->NextCommand);
8995 else
8996 len = get_rfc1002_len(work->request_buf) -
8997 work->next_smb2_rcv_hdr_off;
8998
8999 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9000 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9001
9002 iov[0].iov_base = (char *)&hdr->ProtocolId;
9003 iov[0].iov_len = len;
9004
9005 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
9006 signature);
9007
9008 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9009 pr_err("bad smb2 signature\n");
9010 return 0;
9011 }
9012
9013 return 1;
9014 }
9015
9016 /**
9017 * smb2_set_sign_rsp() - handler for rsp packet sign processing
9018 * @work: smb work containing notify command buffer
9019 *
9020 */
9021 void smb2_set_sign_rsp(struct ksmbd_work *work)
9022 {
9023 struct smb2_hdr *hdr;
9024 char signature[SMB2_HMACSHA256_SIZE];
9025 struct kvec *iov;
9026 int n_vec = 1;
9027
9028 hdr = ksmbd_resp_buf_curr(work);
9029 hdr->Flags |= SMB2_FLAGS_SIGNED;
9030 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9031
9032 if (hdr->Command == SMB2_READ) {
9033 iov = &work->iov[work->iov_idx - 1];
9034 n_vec++;
9035 } else {
9036 iov = &work->iov[work->iov_idx];
9037 }
9038
9039 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
9040 signature);
9041 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9042 }
9043
9044 /**
9045 * smb3_check_sign_req() - handler for req packet sign processing
9046 * @work: smb work containing notify command buffer
9047 *
9048 * Return: 1 on success, 0 otherwise
9049 */
9050 int smb3_check_sign_req(struct ksmbd_work *work)
9051 {
9052 struct ksmbd_conn *conn = work->conn;
9053 char *signing_key;
9054 struct smb2_hdr *hdr;
9055 struct channel *chann;
9056 char signature_req[SMB2_SIGNATURE_SIZE];
9057 char signature[SMB2_CMACAES_SIZE];
9058 struct kvec iov[1];
9059 size_t len;
9060
9061 hdr = smb_get_msg(work->request_buf);
9062 if (work->next_smb2_rcv_hdr_off)
9063 hdr = ksmbd_req_buf_next(work);
9064
9065 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9066 len = get_rfc1002_len(work->request_buf);
9067 else if (hdr->NextCommand)
9068 len = le32_to_cpu(hdr->NextCommand);
9069 else
9070 len = get_rfc1002_len(work->request_buf) -
9071 work->next_smb2_rcv_hdr_off;
9072
9073 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9074 signing_key = work->sess->smb3signingkey;
9075 } else {
9076 chann = lookup_chann_list(work->sess, conn);
9077 if (!chann) {
9078 return 0;
9079 }
9080 signing_key = chann->smb3signingkey;
9081 }
9082
9083 if (!signing_key) {
9084 pr_err("SMB3 signing key is not generated\n");
9085 return 0;
9086 }
9087
9088 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9089 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9090 iov[0].iov_base = (char *)&hdr->ProtocolId;
9091 iov[0].iov_len = len;
9092
9093 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
9094 return 0;
9095
9096 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9097 pr_err("bad smb2 signature\n");
9098 return 0;
9099 }
9100
9101 return 1;
9102 }
9103
9104 /**
9105 * smb3_set_sign_rsp() - handler for rsp packet sign processing
9106 * @work: smb work containing notify command buffer
9107 *
9108 */
9109 void smb3_set_sign_rsp(struct ksmbd_work *work)
9110 {
9111 struct ksmbd_conn *conn = work->conn;
9112 struct smb2_hdr *hdr;
9113 struct channel *chann;
9114 char signature[SMB2_CMACAES_SIZE];
9115 struct kvec *iov;
9116 int n_vec = 1;
9117 char *signing_key;
9118
9119 hdr = ksmbd_resp_buf_curr(work);
9120
9121 if (conn->binding == false &&
9122 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9123 signing_key = work->sess->smb3signingkey;
9124 } else {
9125 chann = lookup_chann_list(work->sess, work->conn);
9126 if (!chann) {
9127 return;
9128 }
9129 signing_key = chann->smb3signingkey;
9130 }
9131
9132 if (!signing_key)
9133 return;
9134
9135 hdr->Flags |= SMB2_FLAGS_SIGNED;
9136 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9137
9138 if (hdr->Command == SMB2_READ) {
9139 iov = &work->iov[work->iov_idx - 1];
9140 n_vec++;
9141 } else {
9142 iov = &work->iov[work->iov_idx];
9143 }
9144
9145 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
9146 signature))
9147 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9148 }
9149
9150 /**
9151 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
9152 * @work: smb work containing response buffer
9153 *
9154 */
9155 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
9156 {
9157 struct ksmbd_conn *conn = work->conn;
9158 struct ksmbd_session *sess = work->sess;
9159 struct smb2_hdr *req, *rsp;
9160
9161 if (conn->dialect != SMB311_PROT_ID)
9162 return;
9163
9164 WORK_BUFFERS(work, req, rsp);
9165
9166 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
9167 conn->preauth_info)
9168 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9169 conn->preauth_info->Preauth_HashValue);
9170
9171 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9172 __u8 *hash_value;
9173
9174 if (conn->binding) {
9175 struct preauth_session *preauth_sess;
9176
9177 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9178 if (!preauth_sess)
9179 return;
9180 hash_value = preauth_sess->Preauth_HashValue;
9181 } else {
9182 hash_value = sess->Preauth_HashValue;
9183 if (!hash_value)
9184 return;
9185 }
9186 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9187 hash_value);
9188 }
9189 }
9190
9191 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9192 {
9193 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9194 struct smb2_hdr *hdr = smb_get_msg(old_buf);
9195 unsigned int orig_len = get_rfc1002_len(old_buf);
9196
9197 /* tr_buf must be cleared by the caller */
9198 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9199 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9200 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9201 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9202 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9203 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9204 else
9205 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9206 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9207 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9208 inc_rfc1001_len(tr_buf, orig_len);
9209 }
9210
9211 int smb3_encrypt_resp(struct ksmbd_work *work)
9212 {
9213 struct kvec *iov = work->iov;
9214 int rc = -ENOMEM;
9215 void *tr_buf;
9216
9217 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9218 if (!tr_buf)
9219 return rc;
9220
9221 /* fill transform header */
9222 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9223
9224 iov[0].iov_base = tr_buf;
9225 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9226 work->tr_buf = tr_buf;
9227
9228 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9229 }
9230
9231 bool smb3_is_transform_hdr(void *buf)
9232 {
9233 struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
9234
9235 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9236 }
9237
9238 int smb3_decrypt_req(struct ksmbd_work *work)
9239 {
9240 struct ksmbd_session *sess;
9241 char *buf = work->request_buf;
9242 unsigned int pdu_length = get_rfc1002_len(buf);
9243 struct kvec iov[2];
9244 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9245 struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
9246 int rc = 0;
9247
9248 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9249 buf_data_size < sizeof(struct smb2_hdr)) {
9250 pr_err("Transform message is too small (%u)\n",
9251 pdu_length);
9252 return -ECONNABORTED;
9253 }
9254
9255 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9256 pr_err("Transform message is broken\n");
9257 return -ECONNABORTED;
9258 }
9259
9260 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9261 if (!sess) {
9262 pr_err("invalid session id(%llx) in transform header\n",
9263 le64_to_cpu(tr_hdr->SessionId));
9264 return -ECONNABORTED;
9265 }
9266 ksmbd_user_session_put(sess);
9267
9268 iov[0].iov_base = buf;
9269 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9270 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9271 iov[1].iov_len = buf_data_size;
9272 rc = ksmbd_crypt_message(work, iov, 2, 0);
9273 if (rc)
9274 return rc;
9275
9276 memmove(buf + 4, iov[1].iov_base, buf_data_size);
9277 *(__be32 *)buf = cpu_to_be32(buf_data_size);
9278
9279 return rc;
9280 }
9281
9282 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9283 {
9284 struct ksmbd_conn *conn = work->conn;
9285 struct ksmbd_session *sess = work->sess;
9286 struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
9287
9288 if (conn->dialect < SMB30_PROT_ID)
9289 return false;
9290
9291 if (work->next_smb2_rcv_hdr_off)
9292 rsp = ksmbd_resp_buf_next(work);
9293
9294 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9295 sess->user && !user_guest(sess->user) &&
9296 rsp->Status == STATUS_SUCCESS)
9297 return true;
9298 return false;
9299 }