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 }
2849
2850 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2851 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2852 dh_info->CreateGuid =
2853 durable_v2_blob->dcontext.CreateGuid;
2854 dh_info->persistent =
2855 le32_to_cpu(durable_v2_blob->dcontext.Flags);
2856 dh_info->timeout =
2857 le32_to_cpu(durable_v2_blob->dcontext.Timeout);
2858 dh_info->type = dh_idx;
2859 }
2860 break;
2861 }
2862 case DURABLE_REQ:
2863 if (dh_info->type == DURABLE_RECONN)
2864 goto out;
2865 if (dh_info->type == DURABLE_RECONN_V2 ||
2866 dh_info->type == DURABLE_REQ_V2) {
2867 err = -EINVAL;
2868 goto out;
2869 }
2870
2871 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2872 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2873 ksmbd_debug(SMB, "Request for durable open\n");
2874 dh_info->type = dh_idx;
2875 }
2876 }
2877 }
2878
2879 out:
2880 return err;
2881 }
2882
2883 /**
2884 * smb2_open() - handler for smb file open request
2885 * @work: smb work containing request buffer
2886 *
2887 * Return: 0 on success, otherwise error
2888 */
2889 int smb2_open(struct ksmbd_work *work)
2890 {
2891 struct ksmbd_conn *conn = work->conn;
2892 struct ksmbd_session *sess = work->sess;
2893 struct ksmbd_tree_connect *tcon = work->tcon;
2894 struct smb2_create_req *req;
2895 struct smb2_create_rsp *rsp;
2896 struct path path;
2897 struct ksmbd_share_config *share = tcon->share_conf;
2898 struct ksmbd_file *fp = NULL;
2899 struct file *filp = NULL;
2900 struct mnt_idmap *idmap = NULL;
2901 struct kstat stat;
2902 struct create_context *context;
2903 struct lease_ctx_info *lc = NULL;
2904 struct create_ea_buf_req *ea_buf = NULL;
2905 struct oplock_info *opinfo;
2906 struct durable_info dh_info = {0};
2907 __le32 *next_ptr = NULL;
2908 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2909 int rc = 0;
2910 int contxt_cnt = 0, query_disk_id = 0;
2911 bool maximal_access_ctxt = false, posix_ctxt = false;
2912 int s_type = 0;
2913 int next_off = 0;
2914 char *name = NULL;
2915 char *stream_name = NULL;
2916 bool file_present = false, created = false, already_permitted = false;
2917 int share_ret, need_truncate = 0;
2918 u64 time;
2919 umode_t posix_mode = 0;
2920 __le32 daccess, maximal_access = 0;
2921 int iov_len = 0;
2922
2923 ksmbd_debug(SMB, "Received smb2 create request\n");
2924
2925 WORK_BUFFERS(work, req, rsp);
2926
2927 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2928 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2929 ksmbd_debug(SMB, "invalid flag in chained command\n");
2930 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2931 smb2_set_err_rsp(work);
2932 return -EINVAL;
2933 }
2934
2935 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2936 ksmbd_debug(SMB, "IPC pipe create request\n");
2937 return create_smb2_pipe(work);
2938 }
2939
2940 if (req->CreateContextsOffset && tcon->posix_extensions) {
2941 context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
2942 if (IS_ERR(context)) {
2943 rc = PTR_ERR(context);
2944 goto err_out2;
2945 } else if (context) {
2946 struct create_posix *posix = (struct create_posix *)context;
2947
2948 if (le16_to_cpu(context->DataOffset) +
2949 le32_to_cpu(context->DataLength) <
2950 sizeof(struct create_posix) - 4) {
2951 rc = -EINVAL;
2952 goto err_out2;
2953 }
2954 ksmbd_debug(SMB, "get posix context\n");
2955
2956 posix_mode = le32_to_cpu(posix->Mode);
2957 posix_ctxt = true;
2958 }
2959 }
2960
2961 if (req->NameLength) {
2962 name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
2963 le16_to_cpu(req->NameLength),
2964 work->conn->local_nls);
2965 if (IS_ERR(name)) {
2966 rc = PTR_ERR(name);
2967 name = NULL;
2968 goto err_out2;
2969 }
2970
2971 ksmbd_debug(SMB, "converted name = %s\n", name);
2972
2973 if (posix_ctxt == false) {
2974 if (strchr(name, ':')) {
2975 if (!test_share_config_flag(work->tcon->share_conf,
2976 KSMBD_SHARE_FLAG_STREAMS)) {
2977 rc = -EBADF;
2978 goto err_out2;
2979 }
2980 rc = parse_stream_name(name, &stream_name, &s_type);
2981 if (rc < 0)
2982 goto err_out2;
2983 }
2984
2985 rc = ksmbd_validate_filename(name);
2986 if (rc < 0)
2987 goto err_out2;
2988 }
2989
2990 if (ksmbd_share_veto_filename(share, name)) {
2991 rc = -ENOENT;
2992 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2993 name);
2994 goto err_out2;
2995 }
2996 } else {
2997 name = kstrdup("", KSMBD_DEFAULT_GFP);
2998 if (!name) {
2999 rc = -ENOMEM;
3000 goto err_out2;
3001 }
3002 }
3003
3004 req_op_level = req->RequestedOplockLevel;
3005
3006 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
3007 req->CreateContextsOffset) {
3008 lc = parse_lease_state(req);
3009 rc = parse_durable_handle_context(work, req, lc, &dh_info);
3010 if (rc) {
3011 ksmbd_debug(SMB, "error parsing durable handle context\n");
3012 goto err_out2;
3013 }
3014
3015 if (dh_info.reconnected == true) {
3016 rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
3017 lc, sess->user, name);
3018 if (rc) {
3019 ksmbd_put_durable_fd(dh_info.fp);
3020 goto err_out2;
3021 }
3022
3023 rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
3024 if (rc) {
3025 ksmbd_put_durable_fd(dh_info.fp);
3026 goto err_out2;
3027 }
3028
3029 fp = dh_info.fp;
3030
3031 if (ksmbd_override_fsids(work)) {
3032 rc = -ENOMEM;
3033 ksmbd_put_durable_fd(dh_info.fp);
3034 goto err_out2;
3035 }
3036
3037 file_info = FILE_OPENED;
3038
3039 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3040 ksmbd_put_durable_fd(fp);
3041 if (rc)
3042 goto err_out2;
3043
3044 goto reconnected_fp;
3045 }
3046 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3047 lc = parse_lease_state(req);
3048
3049 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3050 pr_err("Invalid impersonationlevel : 0x%x\n",
3051 le32_to_cpu(req->ImpersonationLevel));
3052 rc = -EIO;
3053 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3054 goto err_out2;
3055 }
3056
3057 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3058 pr_err("Invalid create options : 0x%x\n",
3059 le32_to_cpu(req->CreateOptions));
3060 rc = -EINVAL;
3061 goto err_out2;
3062 } else {
3063 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3064 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3065 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
3066
3067 if (req->CreateOptions &
3068 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3069 FILE_RESERVE_OPFILTER_LE)) {
3070 rc = -EOPNOTSUPP;
3071 goto err_out2;
3072 }
3073
3074 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3075 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3076 rc = -EINVAL;
3077 goto err_out2;
3078 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3079 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
3080 }
3081 }
3082 }
3083
3084 if (le32_to_cpu(req->CreateDisposition) >
3085 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3086 pr_err("Invalid create disposition : 0x%x\n",
3087 le32_to_cpu(req->CreateDisposition));
3088 rc = -EINVAL;
3089 goto err_out2;
3090 }
3091
3092 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3093 pr_err("Invalid desired access : 0x%x\n",
3094 le32_to_cpu(req->DesiredAccess));
3095 rc = -EACCES;
3096 goto err_out2;
3097 }
3098
3099 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
3100 pr_err("Invalid file attribute : 0x%x\n",
3101 le32_to_cpu(req->FileAttributes));
3102 rc = -EINVAL;
3103 goto err_out2;
3104 }
3105
3106 if (req->CreateContextsOffset) {
3107 /* Parse non-durable handle create contexts */
3108 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3109 if (IS_ERR(context)) {
3110 rc = PTR_ERR(context);
3111 goto err_out2;
3112 } else if (context) {
3113 ea_buf = (struct create_ea_buf_req *)context;
3114 if (le16_to_cpu(context->DataOffset) +
3115 le32_to_cpu(context->DataLength) <
3116 sizeof(struct create_ea_buf_req)) {
3117 rc = -EINVAL;
3118 goto err_out2;
3119 }
3120 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3121 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3122 rc = -EACCES;
3123 goto err_out2;
3124 }
3125 }
3126
3127 context = smb2_find_context_vals(req,
3128 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3129 if (IS_ERR(context)) {
3130 rc = PTR_ERR(context);
3131 goto err_out2;
3132 } else if (context) {
3133 ksmbd_debug(SMB,
3134 "get query maximal access context\n");
3135 maximal_access_ctxt = 1;
3136 }
3137
3138 context = smb2_find_context_vals(req,
3139 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3140 if (IS_ERR(context)) {
3141 rc = PTR_ERR(context);
3142 goto err_out2;
3143 } else if (context) {
3144 ksmbd_debug(SMB, "get timewarp context\n");
3145 rc = -EBADF;
3146 goto err_out2;
3147 }
3148 }
3149
3150 if (ksmbd_override_fsids(work)) {
3151 rc = -ENOMEM;
3152 goto err_out2;
3153 }
3154
3155 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3156 &path, 1);
3157 if (!rc) {
3158 file_present = true;
3159
3160 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3161 /*
3162 * If file exists with under flags, return access
3163 * denied error.
3164 */
3165 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3166 req->CreateDisposition == FILE_OPEN_IF_LE) {
3167 rc = -EACCES;
3168 goto err_out;
3169 }
3170
3171 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3172 ksmbd_debug(SMB,
3173 "User does not have write permission\n");
3174 rc = -EACCES;
3175 goto err_out;
3176 }
3177 } else if (d_is_symlink(path.dentry)) {
3178 rc = -EACCES;
3179 goto err_out;
3180 }
3181
3182 idmap = mnt_idmap(path.mnt);
3183 } else {
3184 if (rc != -ENOENT)
3185 goto err_out;
3186 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3187 name, rc);
3188 rc = 0;
3189 }
3190
3191 if (stream_name) {
3192 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3193 if (s_type == DATA_STREAM) {
3194 rc = -EIO;
3195 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3196 }
3197 } else {
3198 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3199 s_type == DATA_STREAM) {
3200 rc = -EIO;
3201 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3202 }
3203 }
3204
3205 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3206 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3207 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3208 rc = -EIO;
3209 }
3210
3211 if (rc < 0)
3212 goto err_out;
3213 }
3214
3215 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3216 S_ISDIR(d_inode(path.dentry)->i_mode) &&
3217 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3218 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3219 name, req->CreateOptions);
3220 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3221 rc = -EIO;
3222 goto err_out;
3223 }
3224
3225 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3226 !(req->CreateDisposition == FILE_CREATE_LE) &&
3227 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3228 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3229 rc = -EIO;
3230 goto err_out;
3231 }
3232
3233 if (!stream_name && file_present &&
3234 req->CreateDisposition == FILE_CREATE_LE) {
3235 rc = -EEXIST;
3236 goto err_out;
3237 }
3238
3239 daccess = smb_map_generic_desired_access(req->DesiredAccess);
3240
3241 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3242 rc = smb_check_perm_dacl(conn, &path, &daccess,
3243 sess->user->uid);
3244 if (rc)
3245 goto err_out;
3246 }
3247
3248 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3249 if (!file_present) {
3250 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3251 } else {
3252 ksmbd_vfs_query_maximal_access(idmap,
3253 path.dentry,
3254 &daccess);
3255 already_permitted = true;
3256 }
3257 maximal_access = daccess;
3258 }
3259
3260 open_flags = smb2_create_open_flags(file_present, daccess,
3261 req->CreateDisposition,
3262 &may_flags,
3263 req->CreateOptions,
3264 file_present ? d_inode(path.dentry)->i_mode : 0);
3265
3266 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3267 if (open_flags & (O_CREAT | O_TRUNC)) {
3268 ksmbd_debug(SMB,
3269 "User does not have write permission\n");
3270 rc = -EACCES;
3271 goto err_out;
3272 }
3273 }
3274
3275 /*create file if not present */
3276 if (!file_present) {
3277 rc = smb2_creat(work, &path, name, open_flags,
3278 posix_mode,
3279 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3280 if (rc) {
3281 if (rc == -ENOENT) {
3282 rc = -EIO;
3283 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3284 }
3285 goto err_out;
3286 }
3287
3288 created = true;
3289 idmap = mnt_idmap(path.mnt);
3290 if (ea_buf) {
3291 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3292 sizeof(struct smb2_ea_info)) {
3293 rc = -EINVAL;
3294 goto err_out;
3295 }
3296
3297 rc = smb2_set_ea(&ea_buf->ea,
3298 le32_to_cpu(ea_buf->ccontext.DataLength),
3299 &path, false);
3300 if (rc == -EOPNOTSUPP)
3301 rc = 0;
3302 else if (rc)
3303 goto err_out;
3304 }
3305 } else if (!already_permitted) {
3306 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3307 * because execute(search) permission on a parent directory,
3308 * is already granted.
3309 */
3310 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3311 rc = inode_permission(idmap,
3312 d_inode(path.dentry),
3313 may_flags);
3314 if (rc)
3315 goto err_out;
3316
3317 if ((daccess & FILE_DELETE_LE) ||
3318 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3319 rc = inode_permission(idmap,
3320 d_inode(path.dentry->d_parent),
3321 MAY_EXEC | MAY_WRITE);
3322 if (rc)
3323 goto err_out;
3324 }
3325 }
3326 }
3327
3328 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3329 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3330 rc = -EBUSY;
3331 goto err_out;
3332 }
3333
3334 rc = 0;
3335 filp = dentry_open(&path, open_flags, current_cred());
3336 if (IS_ERR(filp)) {
3337 rc = PTR_ERR(filp);
3338 pr_err("dentry open for dir failed, rc %d\n", rc);
3339 goto err_out;
3340 }
3341
3342 if (file_present) {
3343 if (!(open_flags & O_TRUNC))
3344 file_info = FILE_OPENED;
3345 else
3346 file_info = FILE_OVERWRITTEN;
3347
3348 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3349 FILE_SUPERSEDE_LE)
3350 file_info = FILE_SUPERSEDED;
3351 } else if (open_flags & O_CREAT) {
3352 file_info = FILE_CREATED;
3353 }
3354
3355 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3356
3357 /* Obtain Volatile-ID */
3358 fp = ksmbd_open_fd(work, filp);
3359 if (IS_ERR(fp)) {
3360 fput(filp);
3361 rc = PTR_ERR(fp);
3362 fp = NULL;
3363 goto err_out;
3364 }
3365
3366 /* Get Persistent-ID */
3367 ksmbd_open_durable_fd(fp);
3368 if (!has_file_id(fp->persistent_id)) {
3369 rc = -ENOMEM;
3370 goto err_out;
3371 }
3372
3373 fp->cdoption = req->CreateDisposition;
3374 fp->daccess = daccess;
3375 fp->saccess = req->ShareAccess;
3376 fp->coption = req->CreateOptions;
3377
3378 /* Set default windows and posix acls if creating new file */
3379 if (created) {
3380 int posix_acl_rc;
3381 struct inode *inode = d_inode(path.dentry);
3382
3383 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3384 &path,
3385 d_inode(path.dentry->d_parent));
3386 if (posix_acl_rc)
3387 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3388
3389 if (test_share_config_flag(work->tcon->share_conf,
3390 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3391 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3392 sess->user->gid);
3393 }
3394
3395 if (rc) {
3396 rc = smb2_create_sd_buffer(work, req, &path);
3397 if (rc) {
3398 if (posix_acl_rc)
3399 ksmbd_vfs_set_init_posix_acl(idmap,
3400 &path);
3401
3402 if (test_share_config_flag(work->tcon->share_conf,
3403 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3404 struct smb_fattr fattr;
3405 struct smb_ntsd *pntsd;
3406 int pntsd_size;
3407 size_t scratch_len;
3408
3409 ksmbd_acls_fattr(&fattr, idmap, inode);
3410 scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
3411 NULL, 0,
3412 OWNER_SECINFO | GROUP_SECINFO |
3413 DACL_SECINFO);
3414 if (!scratch_len || scratch_len == SIZE_MAX) {
3415 rc = -EFBIG;
3416 posix_acl_release(fattr.cf_acls);
3417 posix_acl_release(fattr.cf_dacls);
3418 goto err_out;
3419 }
3420
3421 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
3422 if (!pntsd) {
3423 rc = -ENOMEM;
3424 posix_acl_release(fattr.cf_acls);
3425 posix_acl_release(fattr.cf_dacls);
3426 goto err_out;
3427 }
3428
3429 rc = build_sec_desc(idmap,
3430 pntsd, NULL, 0,
3431 OWNER_SECINFO |
3432 GROUP_SECINFO |
3433 DACL_SECINFO,
3434 &pntsd_size, &fattr);
3435 posix_acl_release(fattr.cf_acls);
3436 posix_acl_release(fattr.cf_dacls);
3437 if (rc) {
3438 kvfree(pntsd);
3439 goto err_out;
3440 }
3441
3442 rc = ksmbd_vfs_set_sd_xattr(conn,
3443 idmap,
3444 &path,
3445 pntsd,
3446 pntsd_size,
3447 false);
3448 kvfree(pntsd);
3449 if (rc)
3450 pr_err("failed to store ntacl in xattr : %d\n",
3451 rc);
3452 }
3453 }
3454 }
3455 rc = 0;
3456 }
3457
3458 if (stream_name) {
3459 rc = smb2_set_stream_name_xattr(&path,
3460 fp,
3461 stream_name,
3462 s_type);
3463 if (rc)
3464 goto err_out;
3465 file_info = FILE_CREATED;
3466 }
3467
3468 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3469 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3470
3471 fp->is_posix_ctxt = posix_ctxt;
3472
3473 /* fp should be searchable through ksmbd_inode.m_fp_list
3474 * after daccess, saccess, attrib_only, and stream are
3475 * initialized.
3476 */
3477 down_write(&fp->f_ci->m_lock);
3478 list_add(&fp->node, &fp->f_ci->m_fp_list);
3479 up_write(&fp->f_ci->m_lock);
3480
3481 /* Check delete pending among previous fp before oplock break */
3482 if (ksmbd_inode_pending_delete(fp)) {
3483 rc = -EBUSY;
3484 goto err_out;
3485 }
3486
3487 if (file_present || created)
3488 path_put(&path);
3489
3490 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3491 !fp->attrib_only && !stream_name) {
3492 smb_break_all_oplock(work, fp);
3493 need_truncate = 1;
3494 }
3495
3496 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3497 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3498 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3499 !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3500 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3501 rc = share_ret;
3502 goto err_out1;
3503 }
3504 } else {
3505 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3506 if (S_ISDIR(file_inode(filp)->i_mode)) {
3507 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3508 lc->is_dir = true;
3509 }
3510
3511 /*
3512 * Compare parent lease using parent key. If there is no
3513 * a lease that has same parent key, Send lease break
3514 * notification.
3515 */
3516 smb_send_parent_lease_break_noti(fp, lc);
3517
3518 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3519 ksmbd_debug(SMB,
3520 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3521 name, req_op_level, lc->req_state);
3522 rc = find_same_lease_key(sess, fp->f_ci, lc);
3523 if (rc)
3524 goto err_out1;
3525 } else if (open_flags == O_RDONLY &&
3526 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3527 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3528 req_op_level = SMB2_OPLOCK_LEVEL_II;
3529
3530 rc = smb_grant_oplock(work, req_op_level,
3531 fp->persistent_id, fp,
3532 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3533 lc, share_ret);
3534 if (rc < 0)
3535 goto err_out1;
3536 }
3537
3538 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3539 ksmbd_fd_set_delete_on_close(fp, file_info);
3540
3541 if (need_truncate) {
3542 rc = smb2_create_truncate(&fp->filp->f_path);
3543 if (rc)
3544 goto err_out1;
3545 }
3546
3547 if (req->CreateContextsOffset) {
3548 struct create_alloc_size_req *az_req;
3549
3550 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3551 SMB2_CREATE_ALLOCATION_SIZE, 4);
3552 if (IS_ERR(az_req)) {
3553 rc = PTR_ERR(az_req);
3554 goto err_out1;
3555 } else if (az_req) {
3556 loff_t alloc_size;
3557 int err;
3558
3559 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3560 le32_to_cpu(az_req->ccontext.DataLength) <
3561 sizeof(struct create_alloc_size_req)) {
3562 rc = -EINVAL;
3563 goto err_out1;
3564 }
3565 alloc_size = le64_to_cpu(az_req->AllocationSize);
3566 ksmbd_debug(SMB,
3567 "request smb2 create allocate size : %llu\n",
3568 alloc_size);
3569 smb_break_all_levII_oplock(work, fp, 1);
3570 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3571 alloc_size);
3572 if (err < 0)
3573 ksmbd_debug(SMB,
3574 "vfs_fallocate is failed : %d\n",
3575 err);
3576 }
3577
3578 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3579 if (IS_ERR(context)) {
3580 rc = PTR_ERR(context);
3581 goto err_out1;
3582 } else if (context) {
3583 ksmbd_debug(SMB, "get query on disk id context\n");
3584 query_disk_id = 1;
3585 }
3586
3587 if (conn->is_aapl == false) {
3588 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3589 if (IS_ERR(context)) {
3590 rc = PTR_ERR(context);
3591 goto err_out1;
3592 } else if (context)
3593 conn->is_aapl = true;
3594 }
3595 }
3596
3597 rc = ksmbd_vfs_getattr(&path, &stat);
3598 if (rc)
3599 goto err_out1;
3600
3601 if (stat.result_mask & STATX_BTIME)
3602 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3603 else
3604 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3605 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3606 fp->f_ci->m_fattr =
3607 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3608
3609 if (!created)
3610 smb2_update_xattrs(tcon, &path, fp);
3611 else
3612 smb2_new_xattrs(tcon, &path, fp);
3613
3614 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3615
3616 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3617 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3618 test_share_config_flag(work->tcon->share_conf,
3619 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3620 fp->is_persistent = true;
3621 else
3622 fp->is_durable = true;
3623
3624 if (dh_info.type == DURABLE_REQ_V2) {
3625 memcpy(fp->create_guid, dh_info.CreateGuid,
3626 SMB2_CREATE_GUID_SIZE);
3627 if (dh_info.timeout)
3628 fp->durable_timeout =
3629 min_t(unsigned int, dh_info.timeout,
3630 DURABLE_HANDLE_MAX_TIMEOUT);
3631 else
3632 fp->durable_timeout = 60;
3633 }
3634 }
3635
3636 reconnected_fp:
3637 rsp->StructureSize = cpu_to_le16(89);
3638 opinfo = opinfo_get(fp);
3639 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3640 rsp->Flags = 0;
3641 rsp->CreateAction = cpu_to_le32(file_info);
3642 rsp->CreationTime = cpu_to_le64(fp->create_time);
3643 time = ksmbd_UnixTimeToNT(stat.atime);
3644 rsp->LastAccessTime = cpu_to_le64(time);
3645 time = ksmbd_UnixTimeToNT(stat.mtime);
3646 rsp->LastWriteTime = cpu_to_le64(time);
3647 time = ksmbd_UnixTimeToNT(stat.ctime);
3648 rsp->ChangeTime = cpu_to_le64(time);
3649 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3650 cpu_to_le64(stat.blocks << 9);
3651 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3652 rsp->FileAttributes = fp->f_ci->m_fattr;
3653
3654 rsp->Reserved2 = 0;
3655
3656 rsp->PersistentFileId = fp->persistent_id;
3657 rsp->VolatileFileId = fp->volatile_id;
3658
3659 rsp->CreateContextsOffset = 0;
3660 rsp->CreateContextsLength = 0;
3661 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3662
3663 /* If lease is request send lease context response */
3664 if (opinfo && opinfo->is_lease) {
3665 struct create_context *lease_ccontext;
3666
3667 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3668 name, opinfo->o_lease->state);
3669 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3670
3671 lease_ccontext = (struct create_context *)rsp->Buffer;
3672 contxt_cnt++;
3673 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3674 le32_add_cpu(&rsp->CreateContextsLength,
3675 conn->vals->create_lease_size);
3676 iov_len += conn->vals->create_lease_size;
3677 next_ptr = &lease_ccontext->Next;
3678 next_off = conn->vals->create_lease_size;
3679 }
3680 opinfo_put(opinfo);
3681
3682 if (maximal_access_ctxt) {
3683 struct create_context *mxac_ccontext;
3684
3685 if (maximal_access == 0)
3686 ksmbd_vfs_query_maximal_access(idmap,
3687 path.dentry,
3688 &maximal_access);
3689 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3690 le32_to_cpu(rsp->CreateContextsLength));
3691 contxt_cnt++;
3692 create_mxac_rsp_buf(rsp->Buffer +
3693 le32_to_cpu(rsp->CreateContextsLength),
3694 le32_to_cpu(maximal_access));
3695 le32_add_cpu(&rsp->CreateContextsLength,
3696 conn->vals->create_mxac_size);
3697 iov_len += conn->vals->create_mxac_size;
3698 if (next_ptr)
3699 *next_ptr = cpu_to_le32(next_off);
3700 next_ptr = &mxac_ccontext->Next;
3701 next_off = conn->vals->create_mxac_size;
3702 }
3703
3704 if (query_disk_id) {
3705 struct create_context *disk_id_ccontext;
3706
3707 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3708 le32_to_cpu(rsp->CreateContextsLength));
3709 contxt_cnt++;
3710 create_disk_id_rsp_buf(rsp->Buffer +
3711 le32_to_cpu(rsp->CreateContextsLength),
3712 stat.ino, tcon->id);
3713 le32_add_cpu(&rsp->CreateContextsLength,
3714 conn->vals->create_disk_id_size);
3715 iov_len += conn->vals->create_disk_id_size;
3716 if (next_ptr)
3717 *next_ptr = cpu_to_le32(next_off);
3718 next_ptr = &disk_id_ccontext->Next;
3719 next_off = conn->vals->create_disk_id_size;
3720 }
3721
3722 if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3723 struct create_context *durable_ccontext;
3724
3725 durable_ccontext = (struct create_context *)(rsp->Buffer +
3726 le32_to_cpu(rsp->CreateContextsLength));
3727 contxt_cnt++;
3728 if (dh_info.type == DURABLE_REQ) {
3729 create_durable_rsp_buf(rsp->Buffer +
3730 le32_to_cpu(rsp->CreateContextsLength));
3731 le32_add_cpu(&rsp->CreateContextsLength,
3732 conn->vals->create_durable_size);
3733 iov_len += conn->vals->create_durable_size;
3734 } else {
3735 create_durable_v2_rsp_buf(rsp->Buffer +
3736 le32_to_cpu(rsp->CreateContextsLength),
3737 fp);
3738 le32_add_cpu(&rsp->CreateContextsLength,
3739 conn->vals->create_durable_v2_size);
3740 iov_len += conn->vals->create_durable_v2_size;
3741 }
3742
3743 if (next_ptr)
3744 *next_ptr = cpu_to_le32(next_off);
3745 next_ptr = &durable_ccontext->Next;
3746 next_off = conn->vals->create_durable_size;
3747 }
3748
3749 if (posix_ctxt) {
3750 contxt_cnt++;
3751 create_posix_rsp_buf(rsp->Buffer +
3752 le32_to_cpu(rsp->CreateContextsLength),
3753 fp);
3754 le32_add_cpu(&rsp->CreateContextsLength,
3755 conn->vals->create_posix_size);
3756 iov_len += conn->vals->create_posix_size;
3757 if (next_ptr)
3758 *next_ptr = cpu_to_le32(next_off);
3759 }
3760
3761 if (contxt_cnt > 0) {
3762 rsp->CreateContextsOffset =
3763 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3764 }
3765
3766 err_out:
3767 if (rc && (file_present || created))
3768 path_put(&path);
3769
3770 err_out1:
3771 ksmbd_revert_fsids(work);
3772
3773 err_out2:
3774 if (!rc) {
3775 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3776 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3777 }
3778 if (rc) {
3779 if (rc == -EINVAL)
3780 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3781 else if (rc == -EOPNOTSUPP)
3782 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3783 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3784 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3785 else if (rc == -ENOENT)
3786 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3787 else if (rc == -EPERM)
3788 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3789 else if (rc == -EBUSY)
3790 rsp->hdr.Status = STATUS_DELETE_PENDING;
3791 else if (rc == -EBADF)
3792 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3793 else if (rc == -ENOEXEC)
3794 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3795 else if (rc == -ENXIO)
3796 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3797 else if (rc == -EEXIST)
3798 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3799 else if (rc == -EMFILE)
3800 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3801 if (!rsp->hdr.Status)
3802 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3803
3804 if (fp)
3805 ksmbd_fd_put(work, fp);
3806 smb2_set_err_rsp(work);
3807 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3808 }
3809
3810 kfree(name);
3811 kfree(lc);
3812
3813 return rc;
3814 }
3815
3816 static int readdir_info_level_struct_sz(int info_level)
3817 {
3818 switch (info_level) {
3819 case FILE_FULL_DIRECTORY_INFORMATION:
3820 return sizeof(FILE_FULL_DIRECTORY_INFO);
3821 case FILE_BOTH_DIRECTORY_INFORMATION:
3822 return sizeof(FILE_BOTH_DIRECTORY_INFO);
3823 case FILE_DIRECTORY_INFORMATION:
3824 return sizeof(FILE_DIRECTORY_INFO);
3825 case FILE_NAMES_INFORMATION:
3826 return sizeof(struct file_names_info);
3827 case FILEID_FULL_DIRECTORY_INFORMATION:
3828 return sizeof(FILE_ID_FULL_DIR_INFO);
3829 case FILEID_BOTH_DIRECTORY_INFORMATION:
3830 return sizeof(struct file_id_both_directory_info);
3831 case SMB_FIND_FILE_POSIX_INFO:
3832 return sizeof(struct smb2_posix_info);
3833 default:
3834 return -EOPNOTSUPP;
3835 }
3836 }
3837
3838 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3839 {
3840 switch (info_level) {
3841 case FILE_FULL_DIRECTORY_INFORMATION:
3842 {
3843 FILE_FULL_DIRECTORY_INFO *ffdinfo;
3844
3845 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
3846 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3847 d_info->name = ffdinfo->FileName;
3848 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3849 return 0;
3850 }
3851 case FILE_BOTH_DIRECTORY_INFORMATION:
3852 {
3853 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3854
3855 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
3856 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3857 d_info->name = fbdinfo->FileName;
3858 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3859 return 0;
3860 }
3861 case FILE_DIRECTORY_INFORMATION:
3862 {
3863 FILE_DIRECTORY_INFO *fdinfo;
3864
3865 fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
3866 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3867 d_info->name = fdinfo->FileName;
3868 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3869 return 0;
3870 }
3871 case FILE_NAMES_INFORMATION:
3872 {
3873 struct file_names_info *fninfo;
3874
3875 fninfo = (struct file_names_info *)d_info->rptr;
3876 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3877 d_info->name = fninfo->FileName;
3878 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3879 return 0;
3880 }
3881 case FILEID_FULL_DIRECTORY_INFORMATION:
3882 {
3883 FILE_ID_FULL_DIR_INFO *dinfo;
3884
3885 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
3886 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3887 d_info->name = dinfo->FileName;
3888 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3889 return 0;
3890 }
3891 case FILEID_BOTH_DIRECTORY_INFORMATION:
3892 {
3893 struct file_id_both_directory_info *fibdinfo;
3894
3895 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3896 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3897 d_info->name = fibdinfo->FileName;
3898 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3899 return 0;
3900 }
3901 case SMB_FIND_FILE_POSIX_INFO:
3902 {
3903 struct smb2_posix_info *posix_info;
3904
3905 posix_info = (struct smb2_posix_info *)d_info->rptr;
3906 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3907 d_info->name = posix_info->name;
3908 d_info->name_len = le32_to_cpu(posix_info->name_len);
3909 return 0;
3910 }
3911 default:
3912 return -EINVAL;
3913 }
3914 }
3915
3916 /**
3917 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3918 * buffer
3919 * @conn: connection instance
3920 * @info_level: smb information level
3921 * @d_info: structure included variables for query dir
3922 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3923 *
3924 * if directory has many entries, find first can't read it fully.
3925 * find next might be called multiple times to read remaining dir entries
3926 *
3927 * Return: 0 on success, otherwise error
3928 */
3929 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3930 struct ksmbd_dir_info *d_info,
3931 struct ksmbd_kstat *ksmbd_kstat)
3932 {
3933 int next_entry_offset = 0;
3934 char *conv_name;
3935 int conv_len;
3936 void *kstat;
3937 int struct_sz, rc = 0;
3938
3939 conv_name = ksmbd_convert_dir_info_name(d_info,
3940 conn->local_nls,
3941 &conv_len);
3942 if (!conv_name)
3943 return -ENOMEM;
3944
3945 /* Somehow the name has only terminating NULL bytes */
3946 if (conv_len < 0) {
3947 rc = -EINVAL;
3948 goto free_conv_name;
3949 }
3950
3951 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3952 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3953 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3954
3955 if (next_entry_offset > d_info->out_buf_len) {
3956 d_info->out_buf_len = 0;
3957 rc = -ENOSPC;
3958 goto free_conv_name;
3959 }
3960
3961 kstat = d_info->wptr;
3962 if (info_level != FILE_NAMES_INFORMATION)
3963 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3964
3965 switch (info_level) {
3966 case FILE_FULL_DIRECTORY_INFORMATION:
3967 {
3968 FILE_FULL_DIRECTORY_INFO *ffdinfo;
3969
3970 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
3971 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3972 ffdinfo->EaSize =
3973 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3974 if (ffdinfo->EaSize)
3975 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3976 if (d_info->hide_dot_file && d_info->name[0] == '.')
3977 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3978 memcpy(ffdinfo->FileName, conv_name, conv_len);
3979 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3980 break;
3981 }
3982 case FILE_BOTH_DIRECTORY_INFORMATION:
3983 {
3984 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3985
3986 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
3987 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3988 fbdinfo->EaSize =
3989 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3990 if (fbdinfo->EaSize)
3991 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3992 fbdinfo->ShortNameLength = 0;
3993 fbdinfo->Reserved = 0;
3994 if (d_info->hide_dot_file && d_info->name[0] == '.')
3995 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3996 memcpy(fbdinfo->FileName, conv_name, conv_len);
3997 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3998 break;
3999 }
4000 case FILE_DIRECTORY_INFORMATION:
4001 {
4002 FILE_DIRECTORY_INFO *fdinfo;
4003
4004 fdinfo = (FILE_DIRECTORY_INFO *)kstat;
4005 fdinfo->FileNameLength = cpu_to_le32(conv_len);
4006 if (d_info->hide_dot_file && d_info->name[0] == '.')
4007 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4008 memcpy(fdinfo->FileName, conv_name, conv_len);
4009 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4010 break;
4011 }
4012 case FILE_NAMES_INFORMATION:
4013 {
4014 struct file_names_info *fninfo;
4015
4016 fninfo = (struct file_names_info *)kstat;
4017 fninfo->FileNameLength = cpu_to_le32(conv_len);
4018 memcpy(fninfo->FileName, conv_name, conv_len);
4019 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4020 break;
4021 }
4022 case FILEID_FULL_DIRECTORY_INFORMATION:
4023 {
4024 FILE_ID_FULL_DIR_INFO *dinfo;
4025
4026 dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
4027 dinfo->FileNameLength = cpu_to_le32(conv_len);
4028 dinfo->EaSize =
4029 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4030 if (dinfo->EaSize)
4031 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4032 dinfo->Reserved = 0;
4033 if (conn->is_aapl)
4034 dinfo->UniqueId = 0;
4035 else
4036 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4037 if (d_info->hide_dot_file && d_info->name[0] == '.')
4038 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4039 memcpy(dinfo->FileName, conv_name, conv_len);
4040 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4041 break;
4042 }
4043 case FILEID_BOTH_DIRECTORY_INFORMATION:
4044 {
4045 struct file_id_both_directory_info *fibdinfo;
4046
4047 fibdinfo = (struct file_id_both_directory_info *)kstat;
4048 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4049 fibdinfo->EaSize =
4050 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4051 if (fibdinfo->EaSize)
4052 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4053 if (conn->is_aapl)
4054 fibdinfo->UniqueId = 0;
4055 else
4056 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4057 fibdinfo->ShortNameLength = 0;
4058 fibdinfo->Reserved = 0;
4059 fibdinfo->Reserved2 = cpu_to_le16(0);
4060 if (d_info->hide_dot_file && d_info->name[0] == '.')
4061 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4062 memcpy(fibdinfo->FileName, conv_name, conv_len);
4063 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4064 break;
4065 }
4066 case SMB_FIND_FILE_POSIX_INFO:
4067 {
4068 struct smb2_posix_info *posix_info;
4069 u64 time;
4070
4071 posix_info = (struct smb2_posix_info *)kstat;
4072 posix_info->Ignored = 0;
4073 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4074 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4075 posix_info->ChangeTime = cpu_to_le64(time);
4076 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4077 posix_info->LastAccessTime = cpu_to_le64(time);
4078 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4079 posix_info->LastWriteTime = cpu_to_le64(time);
4080 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4081 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4082 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4083 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4084 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4085 switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4086 case S_IFDIR:
4087 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4088 break;
4089 case S_IFLNK:
4090 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4091 break;
4092 case S_IFCHR:
4093 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4094 break;
4095 case S_IFBLK:
4096 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4097 break;
4098 case S_IFIFO:
4099 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4100 break;
4101 case S_IFSOCK:
4102 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4103 }
4104
4105 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4106 posix_info->DosAttributes =
4107 S_ISDIR(ksmbd_kstat->kstat->mode) ?
4108 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4109 if (d_info->hide_dot_file && d_info->name[0] == '.')
4110 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4111 /*
4112 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4113 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4114 * sub_auth(4 * 1(num_subauth)) + RID(4).
4115 */
4116 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4117 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4118 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4119 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4120 memcpy(posix_info->name, conv_name, conv_len);
4121 posix_info->name_len = cpu_to_le32(conv_len);
4122 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4123 break;
4124 }
4125
4126 } /* switch (info_level) */
4127
4128 d_info->last_entry_offset = d_info->data_count;
4129 d_info->data_count += next_entry_offset;
4130 d_info->out_buf_len -= next_entry_offset;
4131 d_info->wptr += next_entry_offset;
4132
4133 ksmbd_debug(SMB,
4134 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4135 info_level, d_info->out_buf_len,
4136 next_entry_offset, d_info->data_count);
4137
4138 free_conv_name:
4139 kfree(conv_name);
4140 return rc;
4141 }
4142
4143 struct smb2_query_dir_private {
4144 struct ksmbd_work *work;
4145 char *search_pattern;
4146 struct ksmbd_file *dir_fp;
4147
4148 struct ksmbd_dir_info *d_info;
4149 int info_level;
4150 };
4151
4152 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4153 {
4154 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
4155 struct kstat kstat;
4156 struct ksmbd_kstat ksmbd_kstat;
4157 int rc;
4158 int i;
4159
4160 for (i = 0; i < priv->d_info->num_entry; i++) {
4161 struct dentry *dent;
4162
4163 if (dentry_name(priv->d_info, priv->info_level))
4164 return -EINVAL;
4165
4166 dent = lookup_one_unlocked(idmap,
4167 &QSTR_LEN(priv->d_info->name,
4168 priv->d_info->name_len),
4169 priv->dir_fp->filp->f_path.dentry);
4170
4171 if (IS_ERR(dent)) {
4172 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4173 priv->d_info->name,
4174 PTR_ERR(dent));
4175 continue;
4176 }
4177 if (unlikely(d_is_negative(dent))) {
4178 dput(dent);
4179 ksmbd_debug(SMB, "Negative dentry `%s'\n",
4180 priv->d_info->name);
4181 continue;
4182 }
4183
4184 ksmbd_kstat.kstat = &kstat;
4185 if (priv->info_level != FILE_NAMES_INFORMATION) {
4186 rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4187 idmap,
4188 dent,
4189 &ksmbd_kstat);
4190 if (rc) {
4191 dput(dent);
4192 continue;
4193 }
4194 }
4195
4196 rc = smb2_populate_readdir_entry(priv->work->conn,
4197 priv->info_level,
4198 priv->d_info,
4199 &ksmbd_kstat);
4200 dput(dent);
4201 if (rc)
4202 return rc;
4203 }
4204 return 0;
4205 }
4206
4207 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4208 int info_level)
4209 {
4210 int struct_sz;
4211 int conv_len;
4212 int next_entry_offset;
4213
4214 struct_sz = readdir_info_level_struct_sz(info_level);
4215 if (struct_sz == -EOPNOTSUPP)
4216 return -EOPNOTSUPP;
4217
4218 conv_len = (d_info->name_len + 1) * 2;
4219 next_entry_offset = ALIGN(struct_sz + conv_len,
4220 KSMBD_DIR_INFO_ALIGNMENT);
4221
4222 if (next_entry_offset > d_info->out_buf_len) {
4223 d_info->out_buf_len = 0;
4224 return -ENOSPC;
4225 }
4226
4227 switch (info_level) {
4228 case FILE_FULL_DIRECTORY_INFORMATION:
4229 {
4230 FILE_FULL_DIRECTORY_INFO *ffdinfo;
4231
4232 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
4233 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4234 ffdinfo->FileName[d_info->name_len] = 0x00;
4235 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4236 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4237 break;
4238 }
4239 case FILE_BOTH_DIRECTORY_INFORMATION:
4240 {
4241 FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4242
4243 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
4244 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4245 fbdinfo->FileName[d_info->name_len] = 0x00;
4246 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4247 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4248 break;
4249 }
4250 case FILE_DIRECTORY_INFORMATION:
4251 {
4252 FILE_DIRECTORY_INFO *fdinfo;
4253
4254 fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
4255 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4256 fdinfo->FileName[d_info->name_len] = 0x00;
4257 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4258 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4259 break;
4260 }
4261 case FILE_NAMES_INFORMATION:
4262 {
4263 struct file_names_info *fninfo;
4264
4265 fninfo = (struct file_names_info *)d_info->wptr;
4266 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4267 fninfo->FileName[d_info->name_len] = 0x00;
4268 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4269 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4270 break;
4271 }
4272 case FILEID_FULL_DIRECTORY_INFORMATION:
4273 {
4274 FILE_ID_FULL_DIR_INFO *dinfo;
4275
4276 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
4277 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4278 dinfo->FileName[d_info->name_len] = 0x00;
4279 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4280 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4281 break;
4282 }
4283 case FILEID_BOTH_DIRECTORY_INFORMATION:
4284 {
4285 struct file_id_both_directory_info *fibdinfo;
4286
4287 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4288 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4289 fibdinfo->FileName[d_info->name_len] = 0x00;
4290 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4291 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4292 break;
4293 }
4294 case SMB_FIND_FILE_POSIX_INFO:
4295 {
4296 struct smb2_posix_info *posix_info;
4297
4298 posix_info = (struct smb2_posix_info *)d_info->wptr;
4299 memcpy(posix_info->name, d_info->name, d_info->name_len);
4300 posix_info->name[d_info->name_len] = 0x00;
4301 posix_info->name_len = cpu_to_le32(d_info->name_len);
4302 posix_info->NextEntryOffset =
4303 cpu_to_le32(next_entry_offset);
4304 break;
4305 }
4306 } /* switch (info_level) */
4307
4308 d_info->num_entry++;
4309 d_info->out_buf_len -= next_entry_offset;
4310 d_info->wptr += next_entry_offset;
4311 return 0;
4312 }
4313
4314 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4315 loff_t offset, u64 ino, unsigned int d_type)
4316 {
4317 struct ksmbd_readdir_data *buf;
4318 struct smb2_query_dir_private *priv;
4319 struct ksmbd_dir_info *d_info;
4320 int rc;
4321
4322 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
4323 priv = buf->private;
4324 d_info = priv->d_info;
4325
4326 /* dot and dotdot entries are already reserved */
4327 if (!strcmp(".", name) || !strcmp("..", name))
4328 return true;
4329 d_info->num_scan++;
4330 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4331 return true;
4332 if (!match_pattern(name, namlen, priv->search_pattern))
4333 return true;
4334
4335 d_info->name = name;
4336 d_info->name_len = namlen;
4337 rc = reserve_populate_dentry(d_info, priv->info_level);
4338 if (rc)
4339 return false;
4340 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4341 d_info->out_buf_len = 0;
4342 return true;
4343 }
4344
4345 static int verify_info_level(int info_level)
4346 {
4347 switch (info_level) {
4348 case FILE_FULL_DIRECTORY_INFORMATION:
4349 case FILE_BOTH_DIRECTORY_INFORMATION:
4350 case FILE_DIRECTORY_INFORMATION:
4351 case FILE_NAMES_INFORMATION:
4352 case FILEID_FULL_DIRECTORY_INFORMATION:
4353 case FILEID_BOTH_DIRECTORY_INFORMATION:
4354 case SMB_FIND_FILE_POSIX_INFO:
4355 break;
4356 default:
4357 return -EOPNOTSUPP;
4358 }
4359
4360 return 0;
4361 }
4362
4363 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4364 {
4365 int free_len;
4366
4367 free_len = (int)(work->response_sz -
4368 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4369 return free_len;
4370 }
4371
4372 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4373 unsigned short hdr2_len,
4374 unsigned int out_buf_len)
4375 {
4376 int free_len;
4377
4378 if (out_buf_len > work->conn->vals->max_trans_size)
4379 return -EINVAL;
4380
4381 free_len = smb2_resp_buf_len(work, hdr2_len);
4382 if (free_len < 0)
4383 return -EINVAL;
4384
4385 return min_t(int, out_buf_len, free_len);
4386 }
4387
4388 int smb2_query_dir(struct ksmbd_work *work)
4389 {
4390 struct ksmbd_conn *conn = work->conn;
4391 struct smb2_query_directory_req *req;
4392 struct smb2_query_directory_rsp *rsp;
4393 struct ksmbd_share_config *share = work->tcon->share_conf;
4394 struct ksmbd_file *dir_fp = NULL;
4395 struct ksmbd_dir_info d_info;
4396 int rc = 0;
4397 char *srch_ptr = NULL;
4398 unsigned char srch_flag;
4399 int buffer_sz;
4400 struct smb2_query_dir_private query_dir_private = {NULL, };
4401
4402 ksmbd_debug(SMB, "Received smb2 query directory request\n");
4403
4404 WORK_BUFFERS(work, req, rsp);
4405
4406 if (ksmbd_override_fsids(work)) {
4407 rsp->hdr.Status = STATUS_NO_MEMORY;
4408 smb2_set_err_rsp(work);
4409 return -ENOMEM;
4410 }
4411
4412 rc = verify_info_level(req->FileInformationClass);
4413 if (rc) {
4414 rc = -EFAULT;
4415 goto err_out2;
4416 }
4417
4418 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4419 if (!dir_fp) {
4420 rc = -EBADF;
4421 goto err_out2;
4422 }
4423
4424 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4425 inode_permission(file_mnt_idmap(dir_fp->filp),
4426 file_inode(dir_fp->filp),
4427 MAY_READ | MAY_EXEC)) {
4428 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4429 rc = -EACCES;
4430 goto err_out2;
4431 }
4432
4433 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4434 pr_err("can't do query dir for a file\n");
4435 rc = -EINVAL;
4436 goto err_out2;
4437 }
4438
4439 srch_flag = req->Flags;
4440 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4441 le16_to_cpu(req->FileNameLength), 1,
4442 conn->local_nls);
4443 if (IS_ERR(srch_ptr)) {
4444 ksmbd_debug(SMB, "Search Pattern not found\n");
4445 rc = -EINVAL;
4446 goto err_out2;
4447 } else {
4448 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4449 }
4450
4451 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4452 ksmbd_debug(SMB, "Restart directory scan\n");
4453 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4454 }
4455
4456 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4457 d_info.wptr = (char *)rsp->Buffer;
4458 d_info.rptr = (char *)rsp->Buffer;
4459 d_info.out_buf_len =
4460 smb2_calc_max_out_buf_len(work,
4461 offsetof(struct smb2_query_directory_rsp, Buffer),
4462 le32_to_cpu(req->OutputBufferLength));
4463 if (d_info.out_buf_len < 0) {
4464 rc = -EINVAL;
4465 goto err_out;
4466 }
4467 d_info.flags = srch_flag;
4468
4469 /*
4470 * reserve dot and dotdot entries in head of buffer
4471 * in first response
4472 */
4473 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4474 dir_fp, &d_info, srch_ptr,
4475 smb2_populate_readdir_entry);
4476 if (rc == -ENOSPC)
4477 rc = 0;
4478 else if (rc)
4479 goto err_out;
4480
4481 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4482 d_info.hide_dot_file = true;
4483
4484 buffer_sz = d_info.out_buf_len;
4485 d_info.rptr = d_info.wptr;
4486 query_dir_private.work = work;
4487 query_dir_private.search_pattern = srch_ptr;
4488 query_dir_private.dir_fp = dir_fp;
4489 query_dir_private.d_info = &d_info;
4490 query_dir_private.info_level = req->FileInformationClass;
4491 dir_fp->readdir_data.private = &query_dir_private;
4492 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4493 again:
4494 d_info.num_scan = 0;
4495 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4496 /*
4497 * num_entry can be 0 if the directory iteration stops before reaching
4498 * the end of the directory and no file is matched with the search
4499 * pattern.
4500 */
4501 if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4502 d_info.out_buf_len > 0)
4503 goto again;
4504 /*
4505 * req->OutputBufferLength is too small to contain even one entry.
4506 * In this case, it immediately returns OutputBufferLength 0 to client.
4507 */
4508 if (!d_info.out_buf_len && !d_info.num_entry)
4509 goto no_buf_len;
4510 if (rc > 0 || rc == -ENOSPC)
4511 rc = 0;
4512 else if (rc)
4513 goto err_out;
4514
4515 d_info.wptr = d_info.rptr;
4516 d_info.out_buf_len = buffer_sz;
4517 rc = process_query_dir_entries(&query_dir_private);
4518 if (rc)
4519 goto err_out;
4520
4521 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4522 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4523 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4524 } else {
4525 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4526 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4527 }
4528 rsp->StructureSize = cpu_to_le16(9);
4529 rsp->OutputBufferOffset = cpu_to_le16(0);
4530 rsp->OutputBufferLength = cpu_to_le32(0);
4531 rsp->Buffer[0] = 0;
4532 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4533 offsetof(struct smb2_query_directory_rsp, Buffer)
4534 + 1);
4535 if (rc)
4536 goto err_out;
4537 } else {
4538 no_buf_len:
4539 ((FILE_DIRECTORY_INFO *)
4540 ((char *)rsp->Buffer + d_info.last_entry_offset))
4541 ->NextEntryOffset = 0;
4542 if (d_info.data_count >= d_info.last_entry_off_align)
4543 d_info.data_count -= d_info.last_entry_off_align;
4544
4545 rsp->StructureSize = cpu_to_le16(9);
4546 rsp->OutputBufferOffset = cpu_to_le16(72);
4547 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4548 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4549 offsetof(struct smb2_query_directory_rsp, Buffer) +
4550 d_info.data_count);
4551 if (rc)
4552 goto err_out;
4553 }
4554
4555 kfree(srch_ptr);
4556 ksmbd_fd_put(work, dir_fp);
4557 ksmbd_revert_fsids(work);
4558 return 0;
4559
4560 err_out:
4561 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4562 kfree(srch_ptr);
4563
4564 err_out2:
4565 if (rc == -EINVAL)
4566 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4567 else if (rc == -EACCES)
4568 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4569 else if (rc == -ENOENT)
4570 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4571 else if (rc == -EBADF)
4572 rsp->hdr.Status = STATUS_FILE_CLOSED;
4573 else if (rc == -ENOMEM)
4574 rsp->hdr.Status = STATUS_NO_MEMORY;
4575 else if (rc == -EFAULT)
4576 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4577 else if (rc == -EIO)
4578 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4579 if (!rsp->hdr.Status)
4580 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4581
4582 smb2_set_err_rsp(work);
4583 ksmbd_fd_put(work, dir_fp);
4584 ksmbd_revert_fsids(work);
4585 return rc;
4586 }
4587
4588 /**
4589 * buffer_check_err() - helper function to check buffer errors
4590 * @reqOutputBufferLength: max buffer length expected in command response
4591 * @rsp: query info response buffer contains output buffer length
4592 * @rsp_org: base response buffer pointer in case of chained response
4593 *
4594 * Return: 0 on success, otherwise error
4595 */
4596 static int buffer_check_err(int reqOutputBufferLength,
4597 struct smb2_query_info_rsp *rsp,
4598 void *rsp_org)
4599 {
4600 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4601 pr_err("Invalid Buffer Size Requested\n");
4602 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4603 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4604 return -EINVAL;
4605 }
4606 return 0;
4607 }
4608
4609 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4610 void *rsp_org)
4611 {
4612 struct smb2_file_standard_info *sinfo;
4613
4614 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4615
4616 sinfo->AllocationSize = cpu_to_le64(4096);
4617 sinfo->EndOfFile = cpu_to_le64(0);
4618 sinfo->NumberOfLinks = cpu_to_le32(1);
4619 sinfo->DeletePending = 1;
4620 sinfo->Directory = 0;
4621 rsp->OutputBufferLength =
4622 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4623 }
4624
4625 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4626 void *rsp_org)
4627 {
4628 struct smb2_file_internal_info *file_info;
4629
4630 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4631
4632 /* any unique number */
4633 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4634 rsp->OutputBufferLength =
4635 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4636 }
4637
4638 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4639 struct smb2_query_info_req *req,
4640 struct smb2_query_info_rsp *rsp,
4641 void *rsp_org)
4642 {
4643 u64 id;
4644 int rc;
4645
4646 /*
4647 * Windows can sometime send query file info request on
4648 * pipe without opening it, checking error condition here
4649 */
4650 id = req->VolatileFileId;
4651
4652 lockdep_assert_not_held(&sess->rpc_lock);
4653
4654 down_read(&sess->rpc_lock);
4655 if (!ksmbd_session_rpc_method(sess, id)) {
4656 up_read(&sess->rpc_lock);
4657 return -ENOENT;
4658 }
4659 up_read(&sess->rpc_lock);
4660
4661 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4662 req->FileInfoClass, req->VolatileFileId);
4663
4664 switch (req->FileInfoClass) {
4665 case FILE_STANDARD_INFORMATION:
4666 get_standard_info_pipe(rsp, rsp_org);
4667 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4668 rsp, rsp_org);
4669 break;
4670 case FILE_INTERNAL_INFORMATION:
4671 get_internal_info_pipe(rsp, id, rsp_org);
4672 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4673 rsp, rsp_org);
4674 break;
4675 default:
4676 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4677 req->FileInfoClass);
4678 rc = -EOPNOTSUPP;
4679 }
4680 return rc;
4681 }
4682
4683 /**
4684 * smb2_get_ea() - handler for smb2 get extended attribute command
4685 * @work: smb work containing query info command buffer
4686 * @fp: ksmbd_file pointer
4687 * @req: get extended attribute request
4688 * @rsp: response buffer pointer
4689 * @rsp_org: base response buffer pointer in case of chained response
4690 *
4691 * Return: 0 on success, otherwise error
4692 */
4693 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4694 struct smb2_query_info_req *req,
4695 struct smb2_query_info_rsp *rsp, void *rsp_org)
4696 {
4697 struct smb2_ea_info *eainfo, *prev_eainfo;
4698 char *name, *ptr, *xattr_list = NULL, *buf;
4699 int rc, name_len, value_len, xattr_list_len, idx;
4700 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4701 struct smb2_ea_info_req *ea_req = NULL;
4702 const struct path *path;
4703 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4704
4705 if (!(fp->daccess & FILE_READ_EA_LE)) {
4706 pr_err("Not permitted to read ext attr : 0x%x\n",
4707 fp->daccess);
4708 return -EACCES;
4709 }
4710
4711 path = &fp->filp->f_path;
4712 /* single EA entry is requested with given user.* name */
4713 if (req->InputBufferLength) {
4714 if (le32_to_cpu(req->InputBufferLength) <=
4715 sizeof(struct smb2_ea_info_req))
4716 return -EINVAL;
4717
4718 ea_req = (struct smb2_ea_info_req *)((char *)req +
4719 le16_to_cpu(req->InputBufferOffset));
4720
4721 if (le32_to_cpu(req->InputBufferLength) <
4722 offsetof(struct smb2_ea_info_req, name) +
4723 ea_req->EaNameLength)
4724 return -EINVAL;
4725 } else {
4726 /* need to send all EAs, if no specific EA is requested*/
4727 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4728 ksmbd_debug(SMB,
4729 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4730 le32_to_cpu(req->Flags));
4731 }
4732
4733 buf_free_len =
4734 smb2_calc_max_out_buf_len(work,
4735 offsetof(struct smb2_query_info_rsp, Buffer),
4736 le32_to_cpu(req->OutputBufferLength));
4737 if (buf_free_len < 0)
4738 return -EINVAL;
4739
4740 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4741 if (rc < 0) {
4742 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4743 goto out;
4744 } else if (!rc) { /* there is no EA in the file */
4745 ksmbd_debug(SMB, "no ea data in the file\n");
4746 goto done;
4747 }
4748 xattr_list_len = rc;
4749
4750 ptr = (char *)rsp->Buffer;
4751 eainfo = (struct smb2_ea_info *)ptr;
4752 prev_eainfo = eainfo;
4753 idx = 0;
4754
4755 while (idx < xattr_list_len) {
4756 name = xattr_list + idx;
4757 name_len = strlen(name);
4758
4759 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4760 idx += name_len + 1;
4761
4762 /*
4763 * CIFS does not support EA other than user.* namespace,
4764 * still keep the framework generic, to list other attrs
4765 * in future.
4766 */
4767 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4768 continue;
4769
4770 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4771 STREAM_PREFIX_LEN))
4772 continue;
4773
4774 if (req->InputBufferLength &&
4775 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4776 ea_req->EaNameLength))
4777 continue;
4778
4779 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4780 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4781 continue;
4782
4783 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4784 name_len -= XATTR_USER_PREFIX_LEN;
4785
4786 ptr = eainfo->name + name_len + 1;
4787 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4788 name_len + 1);
4789 /* bailout if xattr can't fit in buf_free_len */
4790 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4791 name, &buf);
4792 if (value_len <= 0) {
4793 rc = -ENOENT;
4794 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4795 goto out;
4796 }
4797
4798 buf_free_len -= value_len;
4799 if (buf_free_len < 0) {
4800 kfree(buf);
4801 break;
4802 }
4803
4804 memcpy(ptr, buf, value_len);
4805 kfree(buf);
4806
4807 ptr += value_len;
4808 eainfo->Flags = 0;
4809 eainfo->EaNameLength = name_len;
4810
4811 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4812 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4813 name_len);
4814 else
4815 memcpy(eainfo->name, name, name_len);
4816
4817 eainfo->name[name_len] = '\0';
4818 eainfo->EaValueLength = cpu_to_le16(value_len);
4819 next_offset = offsetof(struct smb2_ea_info, name) +
4820 name_len + 1 + value_len;
4821
4822 /* align next xattr entry at 4 byte bundary */
4823 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4824 if (alignment_bytes) {
4825 if (buf_free_len < alignment_bytes)
4826 break;
4827 memset(ptr, '\0', alignment_bytes);
4828 ptr += alignment_bytes;
4829 next_offset += alignment_bytes;
4830 buf_free_len -= alignment_bytes;
4831 }
4832 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4833 prev_eainfo = eainfo;
4834 eainfo = (struct smb2_ea_info *)ptr;
4835 rsp_data_cnt += next_offset;
4836
4837 if (req->InputBufferLength) {
4838 ksmbd_debug(SMB, "single entry requested\n");
4839 break;
4840 }
4841 }
4842
4843 /* no more ea entries */
4844 prev_eainfo->NextEntryOffset = 0;
4845 done:
4846 rc = 0;
4847 if (rsp_data_cnt == 0)
4848 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4849 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4850 out:
4851 kvfree(xattr_list);
4852 return rc;
4853 }
4854
4855 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4856 struct ksmbd_file *fp, void *rsp_org)
4857 {
4858 struct smb2_file_access_info *file_info;
4859
4860 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4861 file_info->AccessFlags = fp->daccess;
4862 rsp->OutputBufferLength =
4863 cpu_to_le32(sizeof(struct smb2_file_access_info));
4864 }
4865
4866 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4867 struct ksmbd_file *fp, void *rsp_org)
4868 {
4869 struct smb2_file_basic_info *basic_info;
4870 struct kstat stat;
4871 u64 time;
4872 int ret;
4873
4874 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4875 pr_err("no right to read the attributes : 0x%x\n",
4876 fp->daccess);
4877 return -EACCES;
4878 }
4879
4880 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4881 AT_STATX_SYNC_AS_STAT);
4882 if (ret)
4883 return ret;
4884
4885 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4886 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4887 time = ksmbd_UnixTimeToNT(stat.atime);
4888 basic_info->LastAccessTime = cpu_to_le64(time);
4889 time = ksmbd_UnixTimeToNT(stat.mtime);
4890 basic_info->LastWriteTime = cpu_to_le64(time);
4891 time = ksmbd_UnixTimeToNT(stat.ctime);
4892 basic_info->ChangeTime = cpu_to_le64(time);
4893 basic_info->Attributes = fp->f_ci->m_fattr;
4894 basic_info->Pad1 = 0;
4895 rsp->OutputBufferLength =
4896 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4897 return 0;
4898 }
4899
4900 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4901 struct ksmbd_file *fp, void *rsp_org)
4902 {
4903 struct smb2_file_standard_info *sinfo;
4904 unsigned int delete_pending;
4905 struct kstat stat;
4906 int ret;
4907
4908 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4909 AT_STATX_SYNC_AS_STAT);
4910 if (ret)
4911 return ret;
4912
4913 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4914 delete_pending = ksmbd_inode_pending_delete(fp);
4915
4916 if (ksmbd_stream_fd(fp) == false) {
4917 sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4918 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4919 } else {
4920 sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
4921 sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
4922 }
4923 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4924 sinfo->DeletePending = delete_pending;
4925 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4926 rsp->OutputBufferLength =
4927 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4928
4929 return 0;
4930 }
4931
4932 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4933 void *rsp_org)
4934 {
4935 struct smb2_file_alignment_info *file_info;
4936
4937 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4938 file_info->AlignmentRequirement = 0;
4939 rsp->OutputBufferLength =
4940 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4941 }
4942
4943 static int get_file_all_info(struct ksmbd_work *work,
4944 struct smb2_query_info_rsp *rsp,
4945 struct ksmbd_file *fp,
4946 void *rsp_org)
4947 {
4948 struct ksmbd_conn *conn = work->conn;
4949 struct smb2_file_all_info *file_info;
4950 unsigned int delete_pending;
4951 struct kstat stat;
4952 int conv_len;
4953 char *filename;
4954 u64 time;
4955 int ret, buf_free_len, filename_len;
4956 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4957
4958 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4959 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4960 fp->daccess);
4961 return -EACCES;
4962 }
4963
4964 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4965 if (IS_ERR(filename))
4966 return PTR_ERR(filename);
4967
4968 filename_len = strlen(filename);
4969 buf_free_len = smb2_calc_max_out_buf_len(work,
4970 offsetof(struct smb2_query_info_rsp, Buffer) +
4971 offsetof(struct smb2_file_all_info, FileName),
4972 le32_to_cpu(req->OutputBufferLength));
4973 if (buf_free_len < (filename_len + 1) * 2) {
4974 kfree(filename);
4975 return -EINVAL;
4976 }
4977
4978 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4979 AT_STATX_SYNC_AS_STAT);
4980 if (ret) {
4981 kfree(filename);
4982 return ret;
4983 }
4984
4985 ksmbd_debug(SMB, "filename = %s\n", filename);
4986 delete_pending = ksmbd_inode_pending_delete(fp);
4987 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4988
4989 file_info->CreationTime = cpu_to_le64(fp->create_time);
4990 time = ksmbd_UnixTimeToNT(stat.atime);
4991 file_info->LastAccessTime = cpu_to_le64(time);
4992 time = ksmbd_UnixTimeToNT(stat.mtime);
4993 file_info->LastWriteTime = cpu_to_le64(time);
4994 time = ksmbd_UnixTimeToNT(stat.ctime);
4995 file_info->ChangeTime = cpu_to_le64(time);
4996 file_info->Attributes = fp->f_ci->m_fattr;
4997 file_info->Pad1 = 0;
4998 if (ksmbd_stream_fd(fp) == false) {
4999 file_info->AllocationSize =
5000 cpu_to_le64(stat.blocks << 9);
5001 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5002 } else {
5003 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5004 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5005 }
5006 file_info->NumberOfLinks =
5007 cpu_to_le32(get_nlink(&stat) - delete_pending);
5008 file_info->DeletePending = delete_pending;
5009 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5010 file_info->Pad2 = 0;
5011 file_info->IndexNumber = cpu_to_le64(stat.ino);
5012 file_info->EASize = 0;
5013 file_info->AccessFlags = fp->daccess;
5014 if (ksmbd_stream_fd(fp) == false)
5015 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5016 else
5017 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5018 file_info->Mode = fp->coption;
5019 file_info->AlignmentRequirement = 0;
5020 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
5021 min(filename_len, PATH_MAX),
5022 conn->local_nls, 0);
5023 conv_len *= 2;
5024 file_info->FileNameLength = cpu_to_le32(conv_len);
5025 rsp->OutputBufferLength =
5026 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
5027 kfree(filename);
5028 return 0;
5029 }
5030
5031 static void get_file_alternate_info(struct ksmbd_work *work,
5032 struct smb2_query_info_rsp *rsp,
5033 struct ksmbd_file *fp,
5034 void *rsp_org)
5035 {
5036 struct ksmbd_conn *conn = work->conn;
5037 struct smb2_file_alt_name_info *file_info;
5038 struct dentry *dentry = fp->filp->f_path.dentry;
5039 int conv_len;
5040
5041 spin_lock(&dentry->d_lock);
5042 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
5043 conv_len = ksmbd_extract_shortname(conn,
5044 dentry->d_name.name,
5045 file_info->FileName);
5046 spin_unlock(&dentry->d_lock);
5047 file_info->FileNameLength = cpu_to_le32(conv_len);
5048 rsp->OutputBufferLength =
5049 cpu_to_le32(struct_size(file_info, FileName, conv_len));
5050 }
5051
5052 static int get_file_stream_info(struct ksmbd_work *work,
5053 struct smb2_query_info_rsp *rsp,
5054 struct ksmbd_file *fp,
5055 void *rsp_org)
5056 {
5057 struct ksmbd_conn *conn = work->conn;
5058 struct smb2_file_stream_info *file_info;
5059 char *stream_name, *xattr_list = NULL, *stream_buf;
5060 struct kstat stat;
5061 const struct path *path = &fp->filp->f_path;
5062 ssize_t xattr_list_len;
5063 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5064 int buf_free_len;
5065 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5066 int ret;
5067
5068 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5069 AT_STATX_SYNC_AS_STAT);
5070 if (ret)
5071 return ret;
5072
5073 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5074
5075 buf_free_len =
5076 smb2_calc_max_out_buf_len(work,
5077 offsetof(struct smb2_query_info_rsp, Buffer),
5078 le32_to_cpu(req->OutputBufferLength));
5079 if (buf_free_len < 0)
5080 goto out;
5081
5082 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5083 if (xattr_list_len < 0) {
5084 goto out;
5085 } else if (!xattr_list_len) {
5086 ksmbd_debug(SMB, "empty xattr in the file\n");
5087 goto out;
5088 }
5089
5090 while (idx < xattr_list_len) {
5091 stream_name = xattr_list + idx;
5092 streamlen = strlen(stream_name);
5093 idx += streamlen + 1;
5094
5095 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5096
5097 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5098 STREAM_PREFIX, STREAM_PREFIX_LEN))
5099 continue;
5100
5101 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5102 STREAM_PREFIX_LEN);
5103 streamlen = stream_name_len;
5104
5105 /* plus : size */
5106 streamlen += 1;
5107 stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5108 if (!stream_buf)
5109 break;
5110
5111 streamlen = snprintf(stream_buf, streamlen + 1,
5112 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5113
5114 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5115 if (next > buf_free_len) {
5116 kfree(stream_buf);
5117 break;
5118 }
5119
5120 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5121 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5122 stream_buf, streamlen,
5123 conn->local_nls, 0);
5124 streamlen *= 2;
5125 kfree(stream_buf);
5126 file_info->StreamNameLength = cpu_to_le32(streamlen);
5127 file_info->StreamSize = cpu_to_le64(stream_name_len);
5128 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5129
5130 nbytes += next;
5131 buf_free_len -= next;
5132 file_info->NextEntryOffset = cpu_to_le32(next);
5133 }
5134
5135 out:
5136 if (!S_ISDIR(stat.mode) &&
5137 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5138 file_info = (struct smb2_file_stream_info *)
5139 &rsp->Buffer[nbytes];
5140 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5141 "::$DATA", 7, conn->local_nls, 0);
5142 streamlen *= 2;
5143 file_info->StreamNameLength = cpu_to_le32(streamlen);
5144 file_info->StreamSize = cpu_to_le64(stat.size);
5145 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5146 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5147 }
5148
5149 /* last entry offset should be 0 */
5150 file_info->NextEntryOffset = 0;
5151 kvfree(xattr_list);
5152
5153 rsp->OutputBufferLength = cpu_to_le32(nbytes);
5154
5155 return 0;
5156 }
5157
5158 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5159 struct ksmbd_file *fp, void *rsp_org)
5160 {
5161 struct smb2_file_internal_info *file_info;
5162 struct kstat stat;
5163 int ret;
5164
5165 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5166 AT_STATX_SYNC_AS_STAT);
5167 if (ret)
5168 return ret;
5169
5170 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5171 file_info->IndexNumber = cpu_to_le64(stat.ino);
5172 rsp->OutputBufferLength =
5173 cpu_to_le32(sizeof(struct smb2_file_internal_info));
5174
5175 return 0;
5176 }
5177
5178 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5179 struct ksmbd_file *fp, void *rsp_org)
5180 {
5181 struct smb2_file_network_open_info *file_info;
5182 struct kstat stat;
5183 u64 time;
5184 int ret;
5185
5186 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5187 pr_err("no right to read the attributes : 0x%x\n",
5188 fp->daccess);
5189 return -EACCES;
5190 }
5191
5192 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5193 AT_STATX_SYNC_AS_STAT);
5194 if (ret)
5195 return ret;
5196
5197 file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
5198
5199 file_info->CreationTime = cpu_to_le64(fp->create_time);
5200 time = ksmbd_UnixTimeToNT(stat.atime);
5201 file_info->LastAccessTime = cpu_to_le64(time);
5202 time = ksmbd_UnixTimeToNT(stat.mtime);
5203 file_info->LastWriteTime = cpu_to_le64(time);
5204 time = ksmbd_UnixTimeToNT(stat.ctime);
5205 file_info->ChangeTime = cpu_to_le64(time);
5206 file_info->Attributes = fp->f_ci->m_fattr;
5207 if (ksmbd_stream_fd(fp) == false) {
5208 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5209 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5210 } else {
5211 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5212 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5213 }
5214 file_info->Reserved = cpu_to_le32(0);
5215 rsp->OutputBufferLength =
5216 cpu_to_le32(sizeof(struct smb2_file_network_open_info));
5217 return 0;
5218 }
5219
5220 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5221 {
5222 struct smb2_file_ea_info *file_info;
5223
5224 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5225 file_info->EASize = 0;
5226 rsp->OutputBufferLength =
5227 cpu_to_le32(sizeof(struct smb2_file_ea_info));
5228 }
5229
5230 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5231 struct ksmbd_file *fp, void *rsp_org)
5232 {
5233 struct smb2_file_pos_info *file_info;
5234
5235 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5236 if (ksmbd_stream_fd(fp) == false)
5237 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5238 else
5239 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5240
5241 rsp->OutputBufferLength =
5242 cpu_to_le32(sizeof(struct smb2_file_pos_info));
5243 }
5244
5245 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5246 struct ksmbd_file *fp, void *rsp_org)
5247 {
5248 struct smb2_file_mode_info *file_info;
5249
5250 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5251 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5252 rsp->OutputBufferLength =
5253 cpu_to_le32(sizeof(struct smb2_file_mode_info));
5254 }
5255
5256 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5257 struct ksmbd_file *fp, void *rsp_org)
5258 {
5259 struct smb2_file_comp_info *file_info;
5260 struct kstat stat;
5261 int ret;
5262
5263 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5264 AT_STATX_SYNC_AS_STAT);
5265 if (ret)
5266 return ret;
5267
5268 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5269 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5270 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5271 file_info->CompressionUnitShift = 0;
5272 file_info->ChunkShift = 0;
5273 file_info->ClusterShift = 0;
5274 memset(&file_info->Reserved[0], 0, 3);
5275
5276 rsp->OutputBufferLength =
5277 cpu_to_le32(sizeof(struct smb2_file_comp_info));
5278
5279 return 0;
5280 }
5281
5282 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5283 struct ksmbd_file *fp, void *rsp_org)
5284 {
5285 struct smb2_file_attr_tag_info *file_info;
5286
5287 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5288 pr_err("no right to read the attributes : 0x%x\n",
5289 fp->daccess);
5290 return -EACCES;
5291 }
5292
5293 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5294 file_info->FileAttributes = fp->f_ci->m_fattr;
5295 file_info->ReparseTag = 0;
5296 rsp->OutputBufferLength =
5297 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5298 return 0;
5299 }
5300
5301 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5302 struct ksmbd_file *fp, void *rsp_org)
5303 {
5304 struct smb311_posix_qinfo *file_info;
5305 struct inode *inode = file_inode(fp->filp);
5306 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5307 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5308 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5309 struct kstat stat;
5310 u64 time;
5311 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5312 int ret;
5313
5314 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5315 AT_STATX_SYNC_AS_STAT);
5316 if (ret)
5317 return ret;
5318
5319 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5320 file_info->CreationTime = cpu_to_le64(fp->create_time);
5321 time = ksmbd_UnixTimeToNT(stat.atime);
5322 file_info->LastAccessTime = cpu_to_le64(time);
5323 time = ksmbd_UnixTimeToNT(stat.mtime);
5324 file_info->LastWriteTime = cpu_to_le64(time);
5325 time = ksmbd_UnixTimeToNT(stat.ctime);
5326 file_info->ChangeTime = cpu_to_le64(time);
5327 file_info->DosAttributes = fp->f_ci->m_fattr;
5328 file_info->Inode = cpu_to_le64(stat.ino);
5329 if (ksmbd_stream_fd(fp) == false) {
5330 file_info->EndOfFile = cpu_to_le64(stat.size);
5331 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5332 } else {
5333 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5334 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5335 }
5336 file_info->HardLinks = cpu_to_le32(stat.nlink);
5337 file_info->Mode = cpu_to_le32(stat.mode & 0777);
5338 switch (stat.mode & S_IFMT) {
5339 case S_IFDIR:
5340 file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5341 break;
5342 case S_IFLNK:
5343 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5344 break;
5345 case S_IFCHR:
5346 file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5347 break;
5348 case S_IFBLK:
5349 file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5350 break;
5351 case S_IFIFO:
5352 file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5353 break;
5354 case S_IFSOCK:
5355 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5356 }
5357
5358 file_info->DeviceId = cpu_to_le32(stat.rdev);
5359
5360 /*
5361 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5362 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5363 * sub_auth(4 * 1(num_subauth)) + RID(4).
5364 */
5365 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5366 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5367 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5368 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5369
5370 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5371
5372 return 0;
5373 }
5374
5375 static int smb2_get_info_file(struct ksmbd_work *work,
5376 struct smb2_query_info_req *req,
5377 struct smb2_query_info_rsp *rsp)
5378 {
5379 struct ksmbd_file *fp;
5380 int fileinfoclass = 0;
5381 int rc = 0;
5382 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5383
5384 if (test_share_config_flag(work->tcon->share_conf,
5385 KSMBD_SHARE_FLAG_PIPE)) {
5386 /* smb2 info file called for pipe */
5387 rc = smb2_get_info_file_pipe(work->sess, req, rsp,
5388 work->response_buf);
5389 goto iov_pin_out;
5390 }
5391
5392 if (work->next_smb2_rcv_hdr_off) {
5393 if (!has_file_id(req->VolatileFileId)) {
5394 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5395 work->compound_fid);
5396 id = work->compound_fid;
5397 pid = work->compound_pfid;
5398 }
5399 }
5400
5401 if (!has_file_id(id)) {
5402 id = req->VolatileFileId;
5403 pid = req->PersistentFileId;
5404 }
5405
5406 fp = ksmbd_lookup_fd_slow(work, id, pid);
5407 if (!fp)
5408 return -ENOENT;
5409
5410 fileinfoclass = req->FileInfoClass;
5411
5412 switch (fileinfoclass) {
5413 case FILE_ACCESS_INFORMATION:
5414 get_file_access_info(rsp, fp, work->response_buf);
5415 break;
5416
5417 case FILE_BASIC_INFORMATION:
5418 rc = get_file_basic_info(rsp, fp, work->response_buf);
5419 break;
5420
5421 case FILE_STANDARD_INFORMATION:
5422 rc = get_file_standard_info(rsp, fp, work->response_buf);
5423 break;
5424
5425 case FILE_ALIGNMENT_INFORMATION:
5426 get_file_alignment_info(rsp, work->response_buf);
5427 break;
5428
5429 case FILE_ALL_INFORMATION:
5430 rc = get_file_all_info(work, rsp, fp, work->response_buf);
5431 break;
5432
5433 case FILE_ALTERNATE_NAME_INFORMATION:
5434 get_file_alternate_info(work, rsp, fp, work->response_buf);
5435 break;
5436
5437 case FILE_STREAM_INFORMATION:
5438 rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5439 break;
5440
5441 case FILE_INTERNAL_INFORMATION:
5442 rc = get_file_internal_info(rsp, fp, work->response_buf);
5443 break;
5444
5445 case FILE_NETWORK_OPEN_INFORMATION:
5446 rc = get_file_network_open_info(rsp, fp, work->response_buf);
5447 break;
5448
5449 case FILE_EA_INFORMATION:
5450 get_file_ea_info(rsp, work->response_buf);
5451 break;
5452
5453 case FILE_FULL_EA_INFORMATION:
5454 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5455 break;
5456
5457 case FILE_POSITION_INFORMATION:
5458 get_file_position_info(rsp, fp, work->response_buf);
5459 break;
5460
5461 case FILE_MODE_INFORMATION:
5462 get_file_mode_info(rsp, fp, work->response_buf);
5463 break;
5464
5465 case FILE_COMPRESSION_INFORMATION:
5466 rc = get_file_compression_info(rsp, fp, work->response_buf);
5467 break;
5468
5469 case FILE_ATTRIBUTE_TAG_INFORMATION:
5470 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5471 break;
5472 case SMB_FIND_FILE_POSIX_INFO:
5473 if (!work->tcon->posix_extensions) {
5474 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5475 rc = -EOPNOTSUPP;
5476 } else {
5477 rc = find_file_posix_info(rsp, fp, work->response_buf);
5478 }
5479 break;
5480 default:
5481 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5482 fileinfoclass);
5483 rc = -EOPNOTSUPP;
5484 }
5485 if (!rc)
5486 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5487 rsp, work->response_buf);
5488 ksmbd_fd_put(work, fp);
5489
5490 iov_pin_out:
5491 if (!rc)
5492 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5493 offsetof(struct smb2_query_info_rsp, Buffer) +
5494 le32_to_cpu(rsp->OutputBufferLength));
5495 return rc;
5496 }
5497
5498 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5499 struct smb2_query_info_req *req,
5500 struct smb2_query_info_rsp *rsp)
5501 {
5502 struct ksmbd_conn *conn = work->conn;
5503 struct ksmbd_share_config *share = work->tcon->share_conf;
5504 int fsinfoclass = 0;
5505 struct kstatfs stfs;
5506 struct path path;
5507 int rc = 0, len;
5508
5509 if (!share->path)
5510 return -EIO;
5511
5512 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5513 if (rc) {
5514 pr_err("cannot create vfs path\n");
5515 return -EIO;
5516 }
5517
5518 rc = vfs_statfs(&path, &stfs);
5519 if (rc) {
5520 pr_err("cannot do stat of path %s\n", share->path);
5521 path_put(&path);
5522 return -EIO;
5523 }
5524
5525 fsinfoclass = req->FileInfoClass;
5526
5527 switch (fsinfoclass) {
5528 case FS_DEVICE_INFORMATION:
5529 {
5530 FILE_SYSTEM_DEVICE_INFO *info;
5531
5532 info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
5533
5534 info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5535 info->DeviceCharacteristics =
5536 cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5537 if (!test_tree_conn_flag(work->tcon,
5538 KSMBD_TREE_CONN_FLAG_WRITABLE))
5539 info->DeviceCharacteristics |=
5540 cpu_to_le32(FILE_READ_ONLY_DEVICE);
5541 rsp->OutputBufferLength = cpu_to_le32(8);
5542 break;
5543 }
5544 case FS_ATTRIBUTE_INFORMATION:
5545 {
5546 FILE_SYSTEM_ATTRIBUTE_INFO *info;
5547 size_t sz;
5548
5549 info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
5550 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5551 FILE_PERSISTENT_ACLS |
5552 FILE_UNICODE_ON_DISK |
5553 FILE_CASE_PRESERVED_NAMES |
5554 FILE_CASE_SENSITIVE_SEARCH |
5555 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5556
5557 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5558
5559 if (test_share_config_flag(work->tcon->share_conf,
5560 KSMBD_SHARE_FLAG_STREAMS))
5561 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5562
5563 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5564 /*
5565 * some application(potableapp) can not run on ksmbd share
5566 * because only NTFS handle security setting on windows.
5567 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
5568 * ksmbd should show share as NTFS. Later, If needed, we can add
5569 * fs type(s) parameter to change fs type user wanted.
5570 */
5571 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5572 "NTFS", PATH_MAX, conn->local_nls, 0);
5573 len = len * 2;
5574 info->FileSystemNameLen = cpu_to_le32(len);
5575 sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
5576 rsp->OutputBufferLength = cpu_to_le32(sz);
5577 break;
5578 }
5579 case FS_VOLUME_INFORMATION:
5580 {
5581 struct filesystem_vol_info *info;
5582 size_t sz;
5583 unsigned int serial_crc = 0;
5584
5585 info = (struct filesystem_vol_info *)(rsp->Buffer);
5586 info->VolumeCreationTime = 0;
5587 serial_crc = crc32_le(serial_crc, share->name,
5588 strlen(share->name));
5589 serial_crc = crc32_le(serial_crc, share->path,
5590 strlen(share->path));
5591 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5592 strlen(ksmbd_netbios_name()));
5593 /* Taking dummy value of serial number*/
5594 info->SerialNumber = cpu_to_le32(serial_crc);
5595 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5596 share->name, PATH_MAX,
5597 conn->local_nls, 0);
5598 len = len * 2;
5599 info->VolumeLabelSize = cpu_to_le32(len);
5600 info->Reserved = 0;
5601 sz = sizeof(struct filesystem_vol_info) + len;
5602 rsp->OutputBufferLength = cpu_to_le32(sz);
5603 break;
5604 }
5605 case FS_SIZE_INFORMATION:
5606 {
5607 FILE_SYSTEM_SIZE_INFO *info;
5608
5609 info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
5610 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5611 info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
5612 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5613 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5614 rsp->OutputBufferLength = cpu_to_le32(24);
5615 break;
5616 }
5617 case FS_FULL_SIZE_INFORMATION:
5618 {
5619 struct smb2_fs_full_size_info *info;
5620
5621 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5622 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5623 info->CallerAvailableAllocationUnits =
5624 cpu_to_le64(stfs.f_bavail);
5625 info->ActualAvailableAllocationUnits =
5626 cpu_to_le64(stfs.f_bfree);
5627 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5628 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5629 rsp->OutputBufferLength = cpu_to_le32(32);
5630 break;
5631 }
5632 case FS_OBJECT_ID_INFORMATION:
5633 {
5634 struct object_id_info *info;
5635
5636 info = (struct object_id_info *)(rsp->Buffer);
5637
5638 if (path.mnt->mnt_sb->s_uuid_len == 16)
5639 memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
5640 path.mnt->mnt_sb->s_uuid_len);
5641 else
5642 memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
5643
5644 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5645 info->extended_info.version = cpu_to_le32(1);
5646 info->extended_info.release = cpu_to_le32(1);
5647 info->extended_info.rel_date = 0;
5648 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5649 rsp->OutputBufferLength = cpu_to_le32(64);
5650 break;
5651 }
5652 case FS_SECTOR_SIZE_INFORMATION:
5653 {
5654 struct smb3_fs_ss_info *info;
5655 unsigned int sector_size =
5656 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5657
5658 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5659
5660 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5661 info->PhysicalBytesPerSectorForAtomicity =
5662 cpu_to_le32(sector_size);
5663 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5664 info->FSEffPhysicalBytesPerSectorForAtomicity =
5665 cpu_to_le32(sector_size);
5666 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5667 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5668 info->ByteOffsetForSectorAlignment = 0;
5669 info->ByteOffsetForPartitionAlignment = 0;
5670 rsp->OutputBufferLength = cpu_to_le32(28);
5671 break;
5672 }
5673 case FS_CONTROL_INFORMATION:
5674 {
5675 /*
5676 * TODO : The current implementation is based on
5677 * test result with win7(NTFS) server. It's need to
5678 * modify this to get valid Quota values
5679 * from Linux kernel
5680 */
5681 struct smb2_fs_control_info *info;
5682
5683 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5684 info->FreeSpaceStartFiltering = 0;
5685 info->FreeSpaceThreshold = 0;
5686 info->FreeSpaceStopFiltering = 0;
5687 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5688 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5689 info->Padding = 0;
5690 rsp->OutputBufferLength = cpu_to_le32(48);
5691 break;
5692 }
5693 case FS_POSIX_INFORMATION:
5694 {
5695 FILE_SYSTEM_POSIX_INFO *info;
5696
5697 if (!work->tcon->posix_extensions) {
5698 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5699 path_put(&path);
5700 return -EOPNOTSUPP;
5701 } else {
5702 info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
5703 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5704 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5705 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5706 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5707 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5708 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5709 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5710 rsp->OutputBufferLength = cpu_to_le32(56);
5711 }
5712 break;
5713 }
5714 default:
5715 path_put(&path);
5716 return -EOPNOTSUPP;
5717 }
5718 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5719 rsp, work->response_buf);
5720 path_put(&path);
5721
5722 if (!rc)
5723 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5724 offsetof(struct smb2_query_info_rsp, Buffer) +
5725 le32_to_cpu(rsp->OutputBufferLength));
5726 return rc;
5727 }
5728
5729 static int smb2_get_info_sec(struct ksmbd_work *work,
5730 struct smb2_query_info_req *req,
5731 struct smb2_query_info_rsp *rsp)
5732 {
5733 struct ksmbd_file *fp;
5734 struct mnt_idmap *idmap;
5735 struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
5736 struct smb_fattr fattr = {{0}};
5737 struct inode *inode;
5738 __u32 secdesclen = 0;
5739 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5740 int addition_info = le32_to_cpu(req->AdditionalInformation);
5741 int rc = 0, ppntsd_size = 0, max_len;
5742 size_t scratch_len = 0;
5743
5744 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5745 PROTECTED_DACL_SECINFO |
5746 UNPROTECTED_DACL_SECINFO)) {
5747 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5748 addition_info);
5749
5750 pntsd = kzalloc(ALIGN(sizeof(struct smb_ntsd), 8),
5751 KSMBD_DEFAULT_GFP);
5752 if (!pntsd)
5753 return -ENOMEM;
5754
5755 pntsd->revision = cpu_to_le16(1);
5756 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5757 pntsd->osidoffset = 0;
5758 pntsd->gsidoffset = 0;
5759 pntsd->sacloffset = 0;
5760 pntsd->dacloffset = 0;
5761
5762 secdesclen = sizeof(struct smb_ntsd);
5763 goto iov_pin;
5764 }
5765
5766 if (work->next_smb2_rcv_hdr_off) {
5767 if (!has_file_id(req->VolatileFileId)) {
5768 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5769 work->compound_fid);
5770 id = work->compound_fid;
5771 pid = work->compound_pfid;
5772 }
5773 }
5774
5775 if (!has_file_id(id)) {
5776 id = req->VolatileFileId;
5777 pid = req->PersistentFileId;
5778 }
5779
5780 fp = ksmbd_lookup_fd_slow(work, id, pid);
5781 if (!fp)
5782 return -ENOENT;
5783
5784 idmap = file_mnt_idmap(fp->filp);
5785 inode = file_inode(fp->filp);
5786 ksmbd_acls_fattr(&fattr, idmap, inode);
5787
5788 if (test_share_config_flag(work->tcon->share_conf,
5789 KSMBD_SHARE_FLAG_ACL_XATTR))
5790 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5791 fp->filp->f_path.dentry,
5792 &ppntsd);
5793
5794 /* Check if sd buffer size exceeds response buffer size */
5795 max_len = smb2_calc_max_out_buf_len(work,
5796 offsetof(struct smb2_query_info_rsp, Buffer),
5797 le32_to_cpu(req->OutputBufferLength));
5798 if (max_len < 0) {
5799 rc = -EINVAL;
5800 goto release_acl;
5801 }
5802
5803 scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
5804 ppntsd_size, addition_info);
5805 if (!scratch_len || scratch_len == SIZE_MAX) {
5806 rc = -EFBIG;
5807 goto release_acl;
5808 }
5809
5810 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
5811 if (!pntsd) {
5812 rc = -ENOMEM;
5813 goto release_acl;
5814 }
5815
5816 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5817 addition_info, &secdesclen, &fattr);
5818
5819 release_acl:
5820 posix_acl_release(fattr.cf_acls);
5821 posix_acl_release(fattr.cf_dacls);
5822 kfree(ppntsd);
5823 ksmbd_fd_put(work, fp);
5824
5825 if (!rc && ALIGN(secdesclen, 8) > scratch_len)
5826 rc = -EFBIG;
5827 if (rc)
5828 goto err_out;
5829
5830 iov_pin:
5831 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5832 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5833 rsp, work->response_buf);
5834 if (rc)
5835 goto err_out;
5836
5837 rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
5838 offsetof(struct smb2_query_info_rsp, Buffer),
5839 pntsd, secdesclen);
5840 err_out:
5841 if (rc) {
5842 rsp->OutputBufferLength = 0;
5843 kvfree(pntsd);
5844 }
5845
5846 return rc;
5847 }
5848
5849 /**
5850 * smb2_query_info() - handler for smb2 query info command
5851 * @work: smb work containing query info request buffer
5852 *
5853 * Return: 0 on success, otherwise error
5854 */
5855 int smb2_query_info(struct ksmbd_work *work)
5856 {
5857 struct smb2_query_info_req *req;
5858 struct smb2_query_info_rsp *rsp;
5859 int rc = 0;
5860
5861 ksmbd_debug(SMB, "Received request smb2 query info request\n");
5862
5863 WORK_BUFFERS(work, req, rsp);
5864
5865 if (ksmbd_override_fsids(work)) {
5866 rc = -ENOMEM;
5867 goto err_out;
5868 }
5869
5870 rsp->StructureSize = cpu_to_le16(9);
5871 rsp->OutputBufferOffset = cpu_to_le16(72);
5872
5873 switch (req->InfoType) {
5874 case SMB2_O_INFO_FILE:
5875 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5876 rc = smb2_get_info_file(work, req, rsp);
5877 break;
5878 case SMB2_O_INFO_FILESYSTEM:
5879 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5880 rc = smb2_get_info_filesystem(work, req, rsp);
5881 break;
5882 case SMB2_O_INFO_SECURITY:
5883 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5884 rc = smb2_get_info_sec(work, req, rsp);
5885 break;
5886 default:
5887 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5888 req->InfoType);
5889 rc = -EOPNOTSUPP;
5890 }
5891 ksmbd_revert_fsids(work);
5892
5893 err_out:
5894 if (rc < 0) {
5895 if (rc == -EACCES)
5896 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5897 else if (rc == -ENOENT)
5898 rsp->hdr.Status = STATUS_FILE_CLOSED;
5899 else if (rc == -EIO)
5900 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5901 else if (rc == -ENOMEM)
5902 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5903 else if (rc == -EINVAL && rsp->hdr.Status == 0)
5904 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5905 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5906 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5907 smb2_set_err_rsp(work);
5908
5909 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5910 rc);
5911 return rc;
5912 }
5913 return 0;
5914 }
5915
5916 /**
5917 * smb2_close_pipe() - handler for closing IPC pipe
5918 * @work: smb work containing close request buffer
5919 *
5920 * Return: 0
5921 */
5922 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5923 {
5924 u64 id;
5925 struct smb2_close_req *req;
5926 struct smb2_close_rsp *rsp;
5927
5928 WORK_BUFFERS(work, req, rsp);
5929
5930 id = req->VolatileFileId;
5931 ksmbd_session_rpc_close(work->sess, id);
5932
5933 rsp->StructureSize = cpu_to_le16(60);
5934 rsp->Flags = 0;
5935 rsp->Reserved = 0;
5936 rsp->CreationTime = 0;
5937 rsp->LastAccessTime = 0;
5938 rsp->LastWriteTime = 0;
5939 rsp->ChangeTime = 0;
5940 rsp->AllocationSize = 0;
5941 rsp->EndOfFile = 0;
5942 rsp->Attributes = 0;
5943
5944 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5945 sizeof(struct smb2_close_rsp));
5946 }
5947
5948 /**
5949 * smb2_close() - handler for smb2 close file command
5950 * @work: smb work containing close request buffer
5951 *
5952 * Return: 0 on success, otherwise error
5953 */
5954 int smb2_close(struct ksmbd_work *work)
5955 {
5956 u64 volatile_id = KSMBD_NO_FID;
5957 u64 sess_id;
5958 struct smb2_close_req *req;
5959 struct smb2_close_rsp *rsp;
5960 struct ksmbd_conn *conn = work->conn;
5961 struct ksmbd_file *fp;
5962 u64 time;
5963 int err = 0;
5964
5965 ksmbd_debug(SMB, "Received smb2 close request\n");
5966
5967 WORK_BUFFERS(work, req, rsp);
5968
5969 if (test_share_config_flag(work->tcon->share_conf,
5970 KSMBD_SHARE_FLAG_PIPE)) {
5971 ksmbd_debug(SMB, "IPC pipe close request\n");
5972 return smb2_close_pipe(work);
5973 }
5974
5975 sess_id = le64_to_cpu(req->hdr.SessionId);
5976 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5977 sess_id = work->compound_sid;
5978
5979 work->compound_sid = 0;
5980 if (check_session_id(conn, sess_id)) {
5981 work->compound_sid = sess_id;
5982 } else {
5983 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5984 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5985 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5986 err = -EBADF;
5987 goto out;
5988 }
5989
5990 if (work->next_smb2_rcv_hdr_off &&
5991 !has_file_id(req->VolatileFileId)) {
5992 if (!has_file_id(work->compound_fid)) {
5993 /* file already closed, return FILE_CLOSED */
5994 ksmbd_debug(SMB, "file already closed\n");
5995 rsp->hdr.Status = STATUS_FILE_CLOSED;
5996 err = -EBADF;
5997 goto out;
5998 } else {
5999 ksmbd_debug(SMB,
6000 "Compound request set FID = %llu:%llu\n",
6001 work->compound_fid,
6002 work->compound_pfid);
6003 volatile_id = work->compound_fid;
6004
6005 /* file closed, stored id is not valid anymore */
6006 work->compound_fid = KSMBD_NO_FID;
6007 work->compound_pfid = KSMBD_NO_FID;
6008 }
6009 } else {
6010 volatile_id = req->VolatileFileId;
6011 }
6012 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
6013
6014 rsp->StructureSize = cpu_to_le16(60);
6015 rsp->Reserved = 0;
6016
6017 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
6018 struct kstat stat;
6019 int ret;
6020
6021 fp = ksmbd_lookup_fd_fast(work, volatile_id);
6022 if (!fp) {
6023 err = -ENOENT;
6024 goto out;
6025 }
6026
6027 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6028 AT_STATX_SYNC_AS_STAT);
6029 if (ret) {
6030 ksmbd_fd_put(work, fp);
6031 goto out;
6032 }
6033
6034 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
6035 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
6036 cpu_to_le64(stat.blocks << 9);
6037 rsp->EndOfFile = cpu_to_le64(stat.size);
6038 rsp->Attributes = fp->f_ci->m_fattr;
6039 rsp->CreationTime = cpu_to_le64(fp->create_time);
6040 time = ksmbd_UnixTimeToNT(stat.atime);
6041 rsp->LastAccessTime = cpu_to_le64(time);
6042 time = ksmbd_UnixTimeToNT(stat.mtime);
6043 rsp->LastWriteTime = cpu_to_le64(time);
6044 time = ksmbd_UnixTimeToNT(stat.ctime);
6045 rsp->ChangeTime = cpu_to_le64(time);
6046 ksmbd_fd_put(work, fp);
6047 } else {
6048 rsp->Flags = 0;
6049 rsp->AllocationSize = 0;
6050 rsp->EndOfFile = 0;
6051 rsp->Attributes = 0;
6052 rsp->CreationTime = 0;
6053 rsp->LastAccessTime = 0;
6054 rsp->LastWriteTime = 0;
6055 rsp->ChangeTime = 0;
6056 }
6057
6058 err = ksmbd_close_fd(work, volatile_id);
6059 out:
6060 if (!err)
6061 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6062 sizeof(struct smb2_close_rsp));
6063
6064 if (err) {
6065 if (rsp->hdr.Status == 0)
6066 rsp->hdr.Status = STATUS_FILE_CLOSED;
6067 smb2_set_err_rsp(work);
6068 }
6069
6070 return err;
6071 }
6072
6073 /**
6074 * smb2_echo() - handler for smb2 echo(ping) command
6075 * @work: smb work containing echo request buffer
6076 *
6077 * Return: 0 on success, otherwise error
6078 */
6079 int smb2_echo(struct ksmbd_work *work)
6080 {
6081 struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
6082
6083 ksmbd_debug(SMB, "Received smb2 echo request\n");
6084
6085 if (work->next_smb2_rcv_hdr_off)
6086 rsp = ksmbd_resp_buf_next(work);
6087
6088 rsp->StructureSize = cpu_to_le16(4);
6089 rsp->Reserved = 0;
6090 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
6091 }
6092
6093 static int smb2_rename(struct ksmbd_work *work,
6094 struct ksmbd_file *fp,
6095 struct smb2_file_rename_info *file_info,
6096 struct nls_table *local_nls)
6097 {
6098 struct ksmbd_share_config *share = fp->tcon->share_conf;
6099 char *new_name = NULL;
6100 int rc, flags = 0;
6101
6102 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
6103 new_name = smb2_get_name(file_info->FileName,
6104 le32_to_cpu(file_info->FileNameLength),
6105 local_nls);
6106 if (IS_ERR(new_name))
6107 return PTR_ERR(new_name);
6108
6109 if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
6110 int s_type;
6111 char *xattr_stream_name, *stream_name = NULL;
6112 size_t xattr_stream_size;
6113 int len;
6114
6115 rc = parse_stream_name(new_name, &stream_name, &s_type);
6116 if (rc < 0)
6117 goto out;
6118
6119 len = strlen(new_name);
6120 if (len > 0 && new_name[len - 1] != '/') {
6121 pr_err("not allow base filename in rename\n");
6122 rc = -ESHARE;
6123 goto out;
6124 }
6125
6126 rc = ksmbd_vfs_xattr_stream_name(stream_name,
6127 &xattr_stream_name,
6128 &xattr_stream_size,
6129 s_type);
6130 if (rc)
6131 goto out;
6132
6133 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6134 &fp->filp->f_path,
6135 xattr_stream_name,
6136 NULL, 0, 0, true);
6137 if (rc < 0) {
6138 pr_err("failed to store stream name in xattr: %d\n",
6139 rc);
6140 rc = -EINVAL;
6141 goto out;
6142 }
6143
6144 goto out;
6145 }
6146
6147 ksmbd_debug(SMB, "new name %s\n", new_name);
6148 if (ksmbd_share_veto_filename(share, new_name)) {
6149 rc = -ENOENT;
6150 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6151 goto out;
6152 }
6153
6154 if (!file_info->ReplaceIfExists)
6155 flags = RENAME_NOREPLACE;
6156
6157 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6158 if (!rc)
6159 smb_break_all_levII_oplock(work, fp, 0);
6160 out:
6161 kfree(new_name);
6162 return rc;
6163 }
6164
6165 static int smb2_create_link(struct ksmbd_work *work,
6166 struct ksmbd_share_config *share,
6167 struct smb2_file_link_info *file_info,
6168 unsigned int buf_len, struct file *filp,
6169 struct nls_table *local_nls)
6170 {
6171 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6172 struct path path;
6173 int rc;
6174
6175 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6176 le32_to_cpu(file_info->FileNameLength))
6177 return -EINVAL;
6178
6179 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6180 pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6181 if (!pathname)
6182 return -ENOMEM;
6183
6184 link_name = smb2_get_name(file_info->FileName,
6185 le32_to_cpu(file_info->FileNameLength),
6186 local_nls);
6187 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6188 rc = -EINVAL;
6189 goto out;
6190 }
6191
6192 ksmbd_debug(SMB, "link name is %s\n", link_name);
6193 target_name = file_path(filp, pathname, PATH_MAX);
6194 if (IS_ERR(target_name)) {
6195 rc = -EINVAL;
6196 goto out;
6197 }
6198
6199 ksmbd_debug(SMB, "target name is %s\n", target_name);
6200 rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
6201 &path, 0);
6202 if (rc) {
6203 if (rc != -ENOENT)
6204 goto out;
6205 } else {
6206 if (file_info->ReplaceIfExists) {
6207 rc = ksmbd_vfs_remove_file(work, &path);
6208 if (rc) {
6209 rc = -EINVAL;
6210 ksmbd_debug(SMB, "cannot delete %s\n",
6211 link_name);
6212 }
6213 } else {
6214 rc = -EEXIST;
6215 ksmbd_debug(SMB, "link already exists\n");
6216 }
6217 ksmbd_vfs_kern_path_end_removing(&path);
6218 if (rc)
6219 goto out;
6220 }
6221 rc = ksmbd_vfs_link(work, target_name, link_name);
6222 if (rc)
6223 rc = -EINVAL;
6224 out:
6225
6226 if (!IS_ERR(link_name))
6227 kfree(link_name);
6228 kfree(pathname);
6229 return rc;
6230 }
6231
6232 static int set_file_basic_info(struct ksmbd_file *fp,
6233 struct smb2_file_basic_info *file_info,
6234 struct ksmbd_share_config *share)
6235 {
6236 struct iattr attrs;
6237 struct file *filp;
6238 struct inode *inode;
6239 struct mnt_idmap *idmap;
6240 int rc = 0;
6241
6242 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6243 return -EACCES;
6244
6245 attrs.ia_valid = 0;
6246 filp = fp->filp;
6247 inode = file_inode(filp);
6248 idmap = file_mnt_idmap(filp);
6249
6250 if (file_info->CreationTime)
6251 fp->create_time = le64_to_cpu(file_info->CreationTime);
6252
6253 if (file_info->LastAccessTime) {
6254 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6255 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6256 }
6257
6258 if (file_info->ChangeTime)
6259 inode_set_ctime_to_ts(inode,
6260 ksmbd_NTtimeToUnix(file_info->ChangeTime));
6261
6262 if (file_info->LastWriteTime) {
6263 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6264 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6265 }
6266
6267 if (file_info->Attributes) {
6268 if (!S_ISDIR(inode->i_mode) &&
6269 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6270 pr_err("can't change a file to a directory\n");
6271 return -EINVAL;
6272 }
6273
6274 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6275 fp->f_ci->m_fattr = file_info->Attributes |
6276 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6277 }
6278
6279 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6280 (file_info->CreationTime || file_info->Attributes)) {
6281 struct xattr_dos_attrib da = {0};
6282
6283 da.version = 4;
6284 da.itime = fp->itime;
6285 da.create_time = fp->create_time;
6286 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6287 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6288 XATTR_DOSINFO_ITIME;
6289
6290 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6291 true);
6292 if (rc)
6293 ksmbd_debug(SMB,
6294 "failed to restore file attribute in EA\n");
6295 rc = 0;
6296 }
6297
6298 if (attrs.ia_valid) {
6299 struct dentry *dentry = filp->f_path.dentry;
6300 struct inode *inode = d_inode(dentry);
6301
6302 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6303 return -EACCES;
6304
6305 inode_lock(inode);
6306 rc = notify_change(idmap, dentry, &attrs, NULL);
6307 inode_unlock(inode);
6308 }
6309 return rc;
6310 }
6311
6312 static int set_file_allocation_info(struct ksmbd_work *work,
6313 struct ksmbd_file *fp,
6314 struct smb2_file_alloc_info *file_alloc_info)
6315 {
6316 /*
6317 * TODO : It's working fine only when store dos attributes
6318 * is not yes. need to implement a logic which works
6319 * properly with any smb.conf option
6320 */
6321
6322 loff_t alloc_blks;
6323 struct inode *inode;
6324 struct kstat stat;
6325 int rc;
6326
6327 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6328 return -EACCES;
6329
6330 if (ksmbd_stream_fd(fp) == true)
6331 return 0;
6332
6333 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6334 AT_STATX_SYNC_AS_STAT);
6335 if (rc)
6336 return rc;
6337
6338 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6339 inode = file_inode(fp->filp);
6340
6341 if (alloc_blks > stat.blocks) {
6342 smb_break_all_levII_oplock(work, fp, 1);
6343 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6344 alloc_blks * 512);
6345 if (rc && rc != -EOPNOTSUPP) {
6346 pr_err("vfs_fallocate is failed : %d\n", rc);
6347 return rc;
6348 }
6349 } else if (alloc_blks < stat.blocks) {
6350 loff_t size;
6351
6352 /*
6353 * Allocation size could be smaller than original one
6354 * which means allocated blocks in file should be
6355 * deallocated. use truncate to cut out it, but inode
6356 * size is also updated with truncate offset.
6357 * inode size is retained by backup inode size.
6358 */
6359 size = i_size_read(inode);
6360 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6361 if (rc) {
6362 pr_err("truncate failed!, err %d\n", rc);
6363 return rc;
6364 }
6365 if (size < alloc_blks * 512)
6366 i_size_write(inode, size);
6367 }
6368 return 0;
6369 }
6370
6371 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6372 struct smb2_file_eof_info *file_eof_info)
6373 {
6374 loff_t newsize;
6375 struct inode *inode;
6376 int rc;
6377
6378 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6379 return -EACCES;
6380
6381 newsize = le64_to_cpu(file_eof_info->EndOfFile);
6382 inode = file_inode(fp->filp);
6383
6384 /*
6385 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6386 * on FAT32 shared device, truncate execution time is too long
6387 * and network error could cause from windows client. because
6388 * truncate of some filesystem like FAT32 fill zero data in
6389 * truncated range.
6390 */
6391 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6392 ksmbd_stream_fd(fp) == false) {
6393 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6394 rc = ksmbd_vfs_truncate(work, fp, newsize);
6395 if (rc) {
6396 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6397 if (rc != -EAGAIN)
6398 rc = -EBADF;
6399 return rc;
6400 }
6401 }
6402 return 0;
6403 }
6404
6405 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6406 struct smb2_file_rename_info *rename_info,
6407 unsigned int buf_len)
6408 {
6409 if (!(fp->daccess & FILE_DELETE_LE)) {
6410 pr_err("no right to delete : 0x%x\n", fp->daccess);
6411 return -EACCES;
6412 }
6413
6414 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6415 le32_to_cpu(rename_info->FileNameLength))
6416 return -EINVAL;
6417
6418 if (!le32_to_cpu(rename_info->FileNameLength))
6419 return -EINVAL;
6420
6421 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6422 }
6423
6424 static int set_file_disposition_info(struct ksmbd_file *fp,
6425 struct smb2_file_disposition_info *file_info)
6426 {
6427 struct inode *inode;
6428
6429 if (!(fp->daccess & FILE_DELETE_LE)) {
6430 pr_err("no right to delete : 0x%x\n", fp->daccess);
6431 return -EACCES;
6432 }
6433
6434 inode = file_inode(fp->filp);
6435 if (file_info->DeletePending) {
6436 if (S_ISDIR(inode->i_mode) &&
6437 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6438 return -EBUSY;
6439 ksmbd_set_inode_pending_delete(fp);
6440 } else {
6441 ksmbd_clear_inode_pending_delete(fp);
6442 }
6443 return 0;
6444 }
6445
6446 static int set_file_position_info(struct ksmbd_file *fp,
6447 struct smb2_file_pos_info *file_info)
6448 {
6449 loff_t current_byte_offset;
6450 unsigned long sector_size;
6451 struct inode *inode;
6452
6453 inode = file_inode(fp->filp);
6454 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6455 sector_size = inode->i_sb->s_blocksize;
6456
6457 if (current_byte_offset < 0 ||
6458 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6459 current_byte_offset & (sector_size - 1))) {
6460 pr_err("CurrentByteOffset is not valid : %llu\n",
6461 current_byte_offset);
6462 return -EINVAL;
6463 }
6464
6465 if (ksmbd_stream_fd(fp) == false)
6466 fp->filp->f_pos = current_byte_offset;
6467 else {
6468 if (current_byte_offset > XATTR_SIZE_MAX)
6469 current_byte_offset = XATTR_SIZE_MAX;
6470 fp->stream.pos = current_byte_offset;
6471 }
6472 return 0;
6473 }
6474
6475 static int set_file_mode_info(struct ksmbd_file *fp,
6476 struct smb2_file_mode_info *file_info)
6477 {
6478 __le32 mode;
6479
6480 mode = file_info->Mode;
6481
6482 if ((mode & ~FILE_MODE_INFO_MASK)) {
6483 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6484 return -EINVAL;
6485 }
6486
6487 /*
6488 * TODO : need to implement consideration for
6489 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6490 */
6491 ksmbd_vfs_set_fadvise(fp->filp, mode);
6492 fp->coption = mode;
6493 return 0;
6494 }
6495
6496 /**
6497 * smb2_set_info_file() - handler for smb2 set info command
6498 * @work: smb work containing set info command buffer
6499 * @fp: ksmbd_file pointer
6500 * @req: request buffer pointer
6501 * @share: ksmbd_share_config pointer
6502 *
6503 * Return: 0 on success, otherwise error
6504 */
6505 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6506 struct smb2_set_info_req *req,
6507 struct ksmbd_share_config *share)
6508 {
6509 unsigned int buf_len = le32_to_cpu(req->BufferLength);
6510 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6511
6512 switch (req->FileInfoClass) {
6513 case FILE_BASIC_INFORMATION:
6514 {
6515 if (buf_len < sizeof(struct smb2_file_basic_info))
6516 return -EMSGSIZE;
6517
6518 return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6519 }
6520 case FILE_ALLOCATION_INFORMATION:
6521 {
6522 if (buf_len < sizeof(struct smb2_file_alloc_info))
6523 return -EMSGSIZE;
6524
6525 return set_file_allocation_info(work, fp,
6526 (struct smb2_file_alloc_info *)buffer);
6527 }
6528 case FILE_END_OF_FILE_INFORMATION:
6529 {
6530 if (buf_len < sizeof(struct smb2_file_eof_info))
6531 return -EMSGSIZE;
6532
6533 return set_end_of_file_info(work, fp,
6534 (struct smb2_file_eof_info *)buffer);
6535 }
6536 case FILE_RENAME_INFORMATION:
6537 {
6538 if (buf_len < sizeof(struct smb2_file_rename_info))
6539 return -EMSGSIZE;
6540
6541 return set_rename_info(work, fp,
6542 (struct smb2_file_rename_info *)buffer,
6543 buf_len);
6544 }
6545 case FILE_LINK_INFORMATION:
6546 {
6547 if (buf_len < sizeof(struct smb2_file_link_info))
6548 return -EMSGSIZE;
6549
6550 return smb2_create_link(work, work->tcon->share_conf,
6551 (struct smb2_file_link_info *)buffer,
6552 buf_len, fp->filp,
6553 work->conn->local_nls);
6554 }
6555 case FILE_DISPOSITION_INFORMATION:
6556 {
6557 if (buf_len < sizeof(struct smb2_file_disposition_info))
6558 return -EMSGSIZE;
6559
6560 return set_file_disposition_info(fp,
6561 (struct smb2_file_disposition_info *)buffer);
6562 }
6563 case FILE_FULL_EA_INFORMATION:
6564 {
6565 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6566 pr_err("Not permitted to write ext attr: 0x%x\n",
6567 fp->daccess);
6568 return -EACCES;
6569 }
6570
6571 if (buf_len < sizeof(struct smb2_ea_info))
6572 return -EMSGSIZE;
6573
6574 return smb2_set_ea((struct smb2_ea_info *)buffer,
6575 buf_len, &fp->filp->f_path, true);
6576 }
6577 case FILE_POSITION_INFORMATION:
6578 {
6579 if (buf_len < sizeof(struct smb2_file_pos_info))
6580 return -EMSGSIZE;
6581
6582 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6583 }
6584 case FILE_MODE_INFORMATION:
6585 {
6586 if (buf_len < sizeof(struct smb2_file_mode_info))
6587 return -EMSGSIZE;
6588
6589 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6590 }
6591 }
6592
6593 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6594 return -EOPNOTSUPP;
6595 }
6596
6597 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6598 char *buffer, int buf_len)
6599 {
6600 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6601
6602 fp->saccess |= FILE_SHARE_DELETE_LE;
6603
6604 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6605 buf_len, false, true);
6606 }
6607
6608 /**
6609 * smb2_set_info() - handler for smb2 set info command handler
6610 * @work: smb work containing set info request buffer
6611 *
6612 * Return: 0 on success, otherwise error
6613 */
6614 int smb2_set_info(struct ksmbd_work *work)
6615 {
6616 struct smb2_set_info_req *req;
6617 struct smb2_set_info_rsp *rsp;
6618 struct ksmbd_file *fp = NULL;
6619 int rc = 0;
6620 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6621
6622 ksmbd_debug(SMB, "Received smb2 set info request\n");
6623
6624 if (work->next_smb2_rcv_hdr_off) {
6625 req = ksmbd_req_buf_next(work);
6626 rsp = ksmbd_resp_buf_next(work);
6627 if (!has_file_id(req->VolatileFileId)) {
6628 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6629 work->compound_fid);
6630 id = work->compound_fid;
6631 pid = work->compound_pfid;
6632 }
6633 } else {
6634 req = smb_get_msg(work->request_buf);
6635 rsp = smb_get_msg(work->response_buf);
6636 }
6637
6638 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6639 ksmbd_debug(SMB, "User does not have write permission\n");
6640 pr_err("User does not have write permission\n");
6641 rc = -EACCES;
6642 goto err_out;
6643 }
6644
6645 if (!has_file_id(id)) {
6646 id = req->VolatileFileId;
6647 pid = req->PersistentFileId;
6648 }
6649
6650 fp = ksmbd_lookup_fd_slow(work, id, pid);
6651 if (!fp) {
6652 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6653 rc = -ENOENT;
6654 goto err_out;
6655 }
6656
6657 switch (req->InfoType) {
6658 case SMB2_O_INFO_FILE:
6659 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6660 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6661 break;
6662 case SMB2_O_INFO_SECURITY:
6663 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6664 if (ksmbd_override_fsids(work)) {
6665 rc = -ENOMEM;
6666 goto err_out;
6667 }
6668 rc = smb2_set_info_sec(fp,
6669 le32_to_cpu(req->AdditionalInformation),
6670 (char *)req + le16_to_cpu(req->BufferOffset),
6671 le32_to_cpu(req->BufferLength));
6672 ksmbd_revert_fsids(work);
6673 break;
6674 default:
6675 rc = -EOPNOTSUPP;
6676 }
6677
6678 if (rc < 0)
6679 goto err_out;
6680
6681 rsp->StructureSize = cpu_to_le16(2);
6682 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6683 sizeof(struct smb2_set_info_rsp));
6684 if (rc)
6685 goto err_out;
6686 ksmbd_fd_put(work, fp);
6687 return 0;
6688
6689 err_out:
6690 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6691 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6692 else if (rc == -EINVAL)
6693 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6694 else if (rc == -EMSGSIZE)
6695 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6696 else if (rc == -ESHARE)
6697 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6698 else if (rc == -ENOENT)
6699 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6700 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6701 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6702 else if (rc == -EAGAIN)
6703 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6704 else if (rc == -EBADF || rc == -ESTALE)
6705 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6706 else if (rc == -EEXIST)
6707 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6708 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6709 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6710 smb2_set_err_rsp(work);
6711 ksmbd_fd_put(work, fp);
6712 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6713 return rc;
6714 }
6715
6716 /**
6717 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6718 * @work: smb work containing read IPC pipe command buffer
6719 *
6720 * Return: 0 on success, otherwise error
6721 */
6722 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6723 {
6724 int nbytes = 0, err;
6725 u64 id;
6726 struct ksmbd_rpc_command *rpc_resp;
6727 struct smb2_read_req *req;
6728 struct smb2_read_rsp *rsp;
6729
6730 WORK_BUFFERS(work, req, rsp);
6731
6732 id = req->VolatileFileId;
6733
6734 rpc_resp = ksmbd_rpc_read(work->sess, id);
6735 if (rpc_resp) {
6736 void *aux_payload_buf;
6737
6738 if (rpc_resp->flags != KSMBD_RPC_OK) {
6739 err = -EINVAL;
6740 goto out;
6741 }
6742
6743 aux_payload_buf =
6744 kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
6745 if (!aux_payload_buf) {
6746 err = -ENOMEM;
6747 goto out;
6748 }
6749
6750 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6751
6752 nbytes = rpc_resp->payload_sz;
6753 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6754 offsetof(struct smb2_read_rsp, Buffer),
6755 aux_payload_buf, nbytes);
6756 if (err) {
6757 kvfree(aux_payload_buf);
6758 goto out;
6759 }
6760 kvfree(rpc_resp);
6761 } else {
6762 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6763 offsetof(struct smb2_read_rsp, Buffer));
6764 if (err)
6765 goto out;
6766 }
6767
6768 rsp->StructureSize = cpu_to_le16(17);
6769 rsp->DataOffset = 80;
6770 rsp->Reserved = 0;
6771 rsp->DataLength = cpu_to_le32(nbytes);
6772 rsp->DataRemaining = 0;
6773 rsp->Flags = 0;
6774 return 0;
6775
6776 out:
6777 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6778 smb2_set_err_rsp(work);
6779 kvfree(rpc_resp);
6780 return err;
6781 }
6782
6783 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6784 struct smbdirect_buffer_descriptor_v1 *desc,
6785 __le32 Channel,
6786 __le16 ChannelInfoLength)
6787 {
6788 unsigned int i, ch_count;
6789
6790 if (work->conn->dialect == SMB30_PROT_ID &&
6791 Channel != SMB2_CHANNEL_RDMA_V1)
6792 return -EINVAL;
6793
6794 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6795 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6796 for (i = 0; i < ch_count; i++) {
6797 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6798 i,
6799 le32_to_cpu(desc[i].token),
6800 le32_to_cpu(desc[i].length));
6801 }
6802 }
6803 if (!ch_count)
6804 return -EINVAL;
6805
6806 work->need_invalidate_rkey =
6807 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6808 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6809 work->remote_key = le32_to_cpu(desc->token);
6810 return 0;
6811 }
6812
6813 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6814 struct smb2_read_req *req, void *data_buf,
6815 size_t length)
6816 {
6817 int err;
6818
6819 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6820 (struct smbdirect_buffer_descriptor_v1 *)
6821 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6822 le16_to_cpu(req->ReadChannelInfoLength));
6823 if (err)
6824 return err;
6825
6826 return length;
6827 }
6828
6829 /**
6830 * smb2_read() - handler for smb2 read from file
6831 * @work: smb work containing read command buffer
6832 *
6833 * Return: 0 on success, otherwise error
6834 */
6835 int smb2_read(struct ksmbd_work *work)
6836 {
6837 struct ksmbd_conn *conn = work->conn;
6838 struct smb2_read_req *req;
6839 struct smb2_read_rsp *rsp;
6840 struct ksmbd_file *fp = NULL;
6841 loff_t offset;
6842 size_t length, mincount;
6843 ssize_t nbytes = 0, remain_bytes = 0;
6844 int err = 0;
6845 bool is_rdma_channel = false;
6846 unsigned int max_read_size = conn->vals->max_read_size;
6847 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6848 void *aux_payload_buf;
6849
6850 ksmbd_debug(SMB, "Received smb2 read request\n");
6851
6852 if (test_share_config_flag(work->tcon->share_conf,
6853 KSMBD_SHARE_FLAG_PIPE)) {
6854 ksmbd_debug(SMB, "IPC pipe read request\n");
6855 return smb2_read_pipe(work);
6856 }
6857
6858 if (work->next_smb2_rcv_hdr_off) {
6859 req = ksmbd_req_buf_next(work);
6860 rsp = ksmbd_resp_buf_next(work);
6861 if (!has_file_id(req->VolatileFileId)) {
6862 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6863 work->compound_fid);
6864 id = work->compound_fid;
6865 pid = work->compound_pfid;
6866 }
6867 } else {
6868 req = smb_get_msg(work->request_buf);
6869 rsp = smb_get_msg(work->response_buf);
6870 }
6871
6872 if (!has_file_id(id)) {
6873 id = req->VolatileFileId;
6874 pid = req->PersistentFileId;
6875 }
6876
6877 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6878 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6879 is_rdma_channel = true;
6880 max_read_size = get_smbd_max_read_write_size(work->conn->transport);
6881 if (max_read_size == 0) {
6882 err = -EINVAL;
6883 goto out;
6884 }
6885 }
6886
6887 if (is_rdma_channel == true) {
6888 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6889
6890 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6891 err = -EINVAL;
6892 goto out;
6893 }
6894 err = smb2_set_remote_key_for_rdma(work,
6895 (struct smbdirect_buffer_descriptor_v1 *)
6896 ((char *)req + ch_offset),
6897 req->Channel,
6898 req->ReadChannelInfoLength);
6899 if (err)
6900 goto out;
6901 }
6902
6903 fp = ksmbd_lookup_fd_slow(work, id, pid);
6904 if (!fp) {
6905 err = -ENOENT;
6906 goto out;
6907 }
6908
6909 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6910 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6911 err = -EACCES;
6912 goto out;
6913 }
6914
6915 offset = le64_to_cpu(req->Offset);
6916 if (offset < 0) {
6917 err = -EINVAL;
6918 goto out;
6919 }
6920 length = le32_to_cpu(req->Length);
6921 mincount = le32_to_cpu(req->MinimumCount);
6922
6923 if (length > max_read_size) {
6924 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6925 max_read_size);
6926 err = -EINVAL;
6927 goto out;
6928 }
6929
6930 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6931 fp->filp, offset, length);
6932
6933 aux_payload_buf = kvzalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
6934 if (!aux_payload_buf) {
6935 err = -ENOMEM;
6936 goto out;
6937 }
6938
6939 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6940 if (nbytes < 0) {
6941 kvfree(aux_payload_buf);
6942 err = nbytes;
6943 goto out;
6944 }
6945
6946 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6947 kvfree(aux_payload_buf);
6948 rsp->hdr.Status = STATUS_END_OF_FILE;
6949 smb2_set_err_rsp(work);
6950 ksmbd_fd_put(work, fp);
6951 return -ENODATA;
6952 }
6953
6954 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6955 nbytes, offset, mincount);
6956
6957 if (is_rdma_channel == true) {
6958 /* write data to the client using rdma channel */
6959 remain_bytes = smb2_read_rdma_channel(work, req,
6960 aux_payload_buf,
6961 nbytes);
6962 kvfree(aux_payload_buf);
6963 aux_payload_buf = NULL;
6964 nbytes = 0;
6965 if (remain_bytes < 0) {
6966 err = (int)remain_bytes;
6967 goto out;
6968 }
6969 }
6970
6971 rsp->StructureSize = cpu_to_le16(17);
6972 rsp->DataOffset = 80;
6973 rsp->Reserved = 0;
6974 rsp->DataLength = cpu_to_le32(nbytes);
6975 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6976 rsp->Flags = 0;
6977 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6978 offsetof(struct smb2_read_rsp, Buffer),
6979 aux_payload_buf, nbytes);
6980 if (err) {
6981 kvfree(aux_payload_buf);
6982 goto out;
6983 }
6984 ksmbd_fd_put(work, fp);
6985 return 0;
6986
6987 out:
6988 if (err) {
6989 if (err == -EISDIR)
6990 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6991 else if (err == -EAGAIN)
6992 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6993 else if (err == -ENOENT)
6994 rsp->hdr.Status = STATUS_FILE_CLOSED;
6995 else if (err == -EACCES)
6996 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6997 else if (err == -ESHARE)
6998 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6999 else if (err == -EINVAL)
7000 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7001 else
7002 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7003
7004 smb2_set_err_rsp(work);
7005 }
7006 ksmbd_fd_put(work, fp);
7007 return err;
7008 }
7009
7010 /**
7011 * smb2_write_pipe() - handler for smb2 write on IPC pipe
7012 * @work: smb work containing write IPC pipe command buffer
7013 *
7014 * Return: 0 on success, otherwise error
7015 */
7016 static noinline int smb2_write_pipe(struct ksmbd_work *work)
7017 {
7018 struct smb2_write_req *req;
7019 struct smb2_write_rsp *rsp;
7020 struct ksmbd_rpc_command *rpc_resp;
7021 u64 id = 0;
7022 int err = 0, ret = 0;
7023 char *data_buf;
7024 size_t length;
7025
7026 WORK_BUFFERS(work, req, rsp);
7027
7028 length = le32_to_cpu(req->Length);
7029 id = req->VolatileFileId;
7030
7031 if ((u64)le16_to_cpu(req->DataOffset) + length >
7032 get_rfc1002_len(work->request_buf)) {
7033 pr_err("invalid write data offset %u, smb_len %u\n",
7034 le16_to_cpu(req->DataOffset),
7035 get_rfc1002_len(work->request_buf));
7036 err = -EINVAL;
7037 goto out;
7038 }
7039
7040 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7041 le16_to_cpu(req->DataOffset));
7042
7043 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
7044 if (rpc_resp) {
7045 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7046 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7047 kvfree(rpc_resp);
7048 smb2_set_err_rsp(work);
7049 return -EOPNOTSUPP;
7050 }
7051 if (rpc_resp->flags != KSMBD_RPC_OK) {
7052 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7053 smb2_set_err_rsp(work);
7054 kvfree(rpc_resp);
7055 return ret;
7056 }
7057 kvfree(rpc_resp);
7058 }
7059
7060 rsp->StructureSize = cpu_to_le16(17);
7061 rsp->DataOffset = 0;
7062 rsp->Reserved = 0;
7063 rsp->DataLength = cpu_to_le32(length);
7064 rsp->DataRemaining = 0;
7065 rsp->Reserved2 = 0;
7066 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7067 offsetof(struct smb2_write_rsp, Buffer));
7068 out:
7069 if (err) {
7070 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7071 smb2_set_err_rsp(work);
7072 }
7073
7074 return err;
7075 }
7076
7077 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
7078 struct smb2_write_req *req,
7079 struct ksmbd_file *fp,
7080 loff_t offset, size_t length, bool sync)
7081 {
7082 char *data_buf;
7083 int ret;
7084 ssize_t nbytes;
7085
7086 data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
7087 if (!data_buf)
7088 return -ENOMEM;
7089
7090 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
7091 (struct smbdirect_buffer_descriptor_v1 *)
7092 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
7093 le16_to_cpu(req->WriteChannelInfoLength));
7094 if (ret < 0) {
7095 kvfree(data_buf);
7096 return ret;
7097 }
7098
7099 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
7100 kvfree(data_buf);
7101 if (ret < 0)
7102 return ret;
7103
7104 return nbytes;
7105 }
7106
7107 /**
7108 * smb2_write() - handler for smb2 write from file
7109 * @work: smb work containing write command buffer
7110 *
7111 * Return: 0 on success, otherwise error
7112 */
7113 int smb2_write(struct ksmbd_work *work)
7114 {
7115 struct smb2_write_req *req;
7116 struct smb2_write_rsp *rsp;
7117 struct ksmbd_file *fp = NULL;
7118 loff_t offset;
7119 size_t length;
7120 ssize_t nbytes;
7121 char *data_buf;
7122 bool writethrough = false, is_rdma_channel = false;
7123 int err = 0;
7124 unsigned int max_write_size = work->conn->vals->max_write_size;
7125
7126 ksmbd_debug(SMB, "Received smb2 write request\n");
7127
7128 WORK_BUFFERS(work, req, rsp);
7129
7130 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7131 ksmbd_debug(SMB, "IPC pipe write request\n");
7132 return smb2_write_pipe(work);
7133 }
7134
7135 offset = le64_to_cpu(req->Offset);
7136 if (offset < 0)
7137 return -EINVAL;
7138 length = le32_to_cpu(req->Length);
7139
7140 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7141 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7142 is_rdma_channel = true;
7143 max_write_size = get_smbd_max_read_write_size(work->conn->transport);
7144 if (max_write_size == 0) {
7145 err = -EINVAL;
7146 goto out;
7147 }
7148 length = le32_to_cpu(req->RemainingBytes);
7149 }
7150
7151 if (is_rdma_channel == true) {
7152 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7153
7154 if (req->Length != 0 || req->DataOffset != 0 ||
7155 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7156 err = -EINVAL;
7157 goto out;
7158 }
7159 err = smb2_set_remote_key_for_rdma(work,
7160 (struct smbdirect_buffer_descriptor_v1 *)
7161 ((char *)req + ch_offset),
7162 req->Channel,
7163 req->WriteChannelInfoLength);
7164 if (err)
7165 goto out;
7166 }
7167
7168 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7169 ksmbd_debug(SMB, "User does not have write permission\n");
7170 err = -EACCES;
7171 goto out;
7172 }
7173
7174 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7175 if (!fp) {
7176 err = -ENOENT;
7177 goto out;
7178 }
7179
7180 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7181 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7182 err = -EACCES;
7183 goto out;
7184 }
7185
7186 if (length > max_write_size) {
7187 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7188 max_write_size);
7189 err = -EINVAL;
7190 goto out;
7191 }
7192
7193 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7194 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7195 writethrough = true;
7196
7197 if (is_rdma_channel == false) {
7198 if (le16_to_cpu(req->DataOffset) <
7199 offsetof(struct smb2_write_req, Buffer)) {
7200 err = -EINVAL;
7201 goto out;
7202 }
7203
7204 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7205 le16_to_cpu(req->DataOffset));
7206
7207 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7208 fp->filp, offset, length);
7209 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7210 writethrough, &nbytes);
7211 if (err < 0)
7212 goto out;
7213 } else {
7214 /* read data from the client using rdma channel, and
7215 * write the data.
7216 */
7217 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7218 writethrough);
7219 if (nbytes < 0) {
7220 err = (int)nbytes;
7221 goto out;
7222 }
7223 }
7224
7225 rsp->StructureSize = cpu_to_le16(17);
7226 rsp->DataOffset = 0;
7227 rsp->Reserved = 0;
7228 rsp->DataLength = cpu_to_le32(nbytes);
7229 rsp->DataRemaining = 0;
7230 rsp->Reserved2 = 0;
7231 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7232 if (err)
7233 goto out;
7234 ksmbd_fd_put(work, fp);
7235 return 0;
7236
7237 out:
7238 if (err == -EAGAIN)
7239 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7240 else if (err == -ENOSPC || err == -EFBIG)
7241 rsp->hdr.Status = STATUS_DISK_FULL;
7242 else if (err == -ENOENT)
7243 rsp->hdr.Status = STATUS_FILE_CLOSED;
7244 else if (err == -EACCES)
7245 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7246 else if (err == -ESHARE)
7247 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7248 else if (err == -EINVAL)
7249 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7250 else
7251 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7252
7253 smb2_set_err_rsp(work);
7254 ksmbd_fd_put(work, fp);
7255 return err;
7256 }
7257
7258 /**
7259 * smb2_flush() - handler for smb2 flush file - fsync
7260 * @work: smb work containing flush command buffer
7261 *
7262 * Return: 0 on success, otherwise error
7263 */
7264 int smb2_flush(struct ksmbd_work *work)
7265 {
7266 struct smb2_flush_req *req;
7267 struct smb2_flush_rsp *rsp;
7268 int err;
7269
7270 WORK_BUFFERS(work, req, rsp);
7271
7272 ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7273
7274 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
7275 if (err)
7276 goto out;
7277
7278 rsp->StructureSize = cpu_to_le16(4);
7279 rsp->Reserved = 0;
7280 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7281
7282 out:
7283 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7284 smb2_set_err_rsp(work);
7285 return err;
7286 }
7287
7288 /**
7289 * smb2_cancel() - handler for smb2 cancel command
7290 * @work: smb work containing cancel command buffer
7291 *
7292 * Return: 0 on success, otherwise error
7293 */
7294 int smb2_cancel(struct ksmbd_work *work)
7295 {
7296 struct ksmbd_conn *conn = work->conn;
7297 struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
7298 struct smb2_hdr *chdr;
7299 struct ksmbd_work *iter;
7300 struct list_head *command_list;
7301
7302 if (work->next_smb2_rcv_hdr_off)
7303 hdr = ksmbd_resp_buf_next(work);
7304
7305 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7306 hdr->MessageId, hdr->Flags);
7307
7308 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7309 command_list = &conn->async_requests;
7310
7311 spin_lock(&conn->request_lock);
7312 list_for_each_entry(iter, command_list,
7313 async_request_entry) {
7314 chdr = smb_get_msg(iter->request_buf);
7315
7316 if (iter->async_id !=
7317 le64_to_cpu(hdr->Id.AsyncId))
7318 continue;
7319
7320 ksmbd_debug(SMB,
7321 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7322 le64_to_cpu(hdr->Id.AsyncId),
7323 le16_to_cpu(chdr->Command));
7324 iter->state = KSMBD_WORK_CANCELLED;
7325 if (iter->cancel_fn)
7326 iter->cancel_fn(iter->cancel_argv);
7327 break;
7328 }
7329 spin_unlock(&conn->request_lock);
7330 } else {
7331 command_list = &conn->requests;
7332
7333 spin_lock(&conn->request_lock);
7334 list_for_each_entry(iter, command_list, request_entry) {
7335 chdr = smb_get_msg(iter->request_buf);
7336
7337 if (chdr->MessageId != hdr->MessageId ||
7338 iter == work)
7339 continue;
7340
7341 ksmbd_debug(SMB,
7342 "smb2 with mid %llu cancelled command = 0x%x\n",
7343 le64_to_cpu(hdr->MessageId),
7344 le16_to_cpu(chdr->Command));
7345 iter->state = KSMBD_WORK_CANCELLED;
7346 break;
7347 }
7348 spin_unlock(&conn->request_lock);
7349 }
7350
7351 /* For SMB2_CANCEL command itself send no response*/
7352 work->send_no_response = 1;
7353 return 0;
7354 }
7355
7356 struct file_lock *smb_flock_init(struct file *f)
7357 {
7358 struct file_lock *fl;
7359
7360 fl = locks_alloc_lock();
7361 if (!fl)
7362 goto out;
7363
7364 locks_init_lock(fl);
7365
7366 fl->c.flc_owner = f;
7367 fl->c.flc_pid = current->tgid;
7368 fl->c.flc_file = f;
7369 fl->c.flc_flags = FL_POSIX;
7370 fl->fl_ops = NULL;
7371 fl->fl_lmops = NULL;
7372
7373 out:
7374 return fl;
7375 }
7376
7377 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7378 {
7379 int cmd = -EINVAL;
7380
7381 /* Checking for wrong flag combination during lock request*/
7382 switch (flags) {
7383 case SMB2_LOCKFLAG_SHARED:
7384 ksmbd_debug(SMB, "received shared request\n");
7385 cmd = F_SETLKW;
7386 flock->c.flc_type = F_RDLCK;
7387 flock->c.flc_flags |= FL_SLEEP;
7388 break;
7389 case SMB2_LOCKFLAG_EXCLUSIVE:
7390 ksmbd_debug(SMB, "received exclusive request\n");
7391 cmd = F_SETLKW;
7392 flock->c.flc_type = F_WRLCK;
7393 flock->c.flc_flags |= FL_SLEEP;
7394 break;
7395 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7396 ksmbd_debug(SMB,
7397 "received shared & fail immediately request\n");
7398 cmd = F_SETLK;
7399 flock->c.flc_type = F_RDLCK;
7400 break;
7401 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7402 ksmbd_debug(SMB,
7403 "received exclusive & fail immediately request\n");
7404 cmd = F_SETLK;
7405 flock->c.flc_type = F_WRLCK;
7406 break;
7407 case SMB2_LOCKFLAG_UNLOCK:
7408 ksmbd_debug(SMB, "received unlock request\n");
7409 flock->c.flc_type = F_UNLCK;
7410 cmd = F_SETLK;
7411 break;
7412 }
7413
7414 return cmd;
7415 }
7416
7417 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7418 unsigned int cmd, int flags,
7419 struct list_head *lock_list)
7420 {
7421 struct ksmbd_lock *lock;
7422
7423 lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
7424 if (!lock)
7425 return NULL;
7426
7427 lock->cmd = cmd;
7428 lock->fl = flock;
7429 lock->start = flock->fl_start;
7430 lock->end = flock->fl_end;
7431 lock->flags = flags;
7432 if (lock->start == lock->end)
7433 lock->zero_len = 1;
7434 INIT_LIST_HEAD(&lock->clist);
7435 INIT_LIST_HEAD(&lock->flist);
7436 INIT_LIST_HEAD(&lock->llist);
7437 list_add_tail(&lock->llist, lock_list);
7438
7439 return lock;
7440 }
7441
7442 static void smb2_remove_blocked_lock(void **argv)
7443 {
7444 struct file_lock *flock = (struct file_lock *)argv[0];
7445
7446 ksmbd_vfs_posix_lock_unblock(flock);
7447 locks_wake_up(flock);
7448 }
7449
7450 static inline bool lock_defer_pending(struct file_lock *fl)
7451 {
7452 /* check pending lock waiters */
7453 return waitqueue_active(&fl->c.flc_wait);
7454 }
7455
7456 /**
7457 * smb2_lock() - handler for smb2 file lock command
7458 * @work: smb work containing lock command buffer
7459 *
7460 * Return: 0 on success, otherwise error
7461 */
7462 int smb2_lock(struct ksmbd_work *work)
7463 {
7464 struct smb2_lock_req *req;
7465 struct smb2_lock_rsp *rsp;
7466 struct smb2_lock_element *lock_ele;
7467 struct ksmbd_file *fp = NULL;
7468 struct file_lock *flock = NULL;
7469 struct file *filp = NULL;
7470 int lock_count;
7471 int flags = 0;
7472 int cmd = 0;
7473 int err = -EIO, i, rc = 0;
7474 u64 lock_start, lock_length;
7475 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7476 struct ksmbd_conn *conn;
7477 int nolock = 0;
7478 LIST_HEAD(lock_list);
7479 LIST_HEAD(rollback_list);
7480 int prior_lock = 0, bkt;
7481
7482 WORK_BUFFERS(work, req, rsp);
7483
7484 ksmbd_debug(SMB, "Received smb2 lock request\n");
7485 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7486 if (!fp) {
7487 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7488 err = -ENOENT;
7489 goto out2;
7490 }
7491
7492 filp = fp->filp;
7493 lock_count = le16_to_cpu(req->LockCount);
7494 lock_ele = req->locks;
7495
7496 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7497 if (!lock_count) {
7498 err = -EINVAL;
7499 goto out2;
7500 }
7501
7502 for (i = 0; i < lock_count; i++) {
7503 flags = le32_to_cpu(lock_ele[i].Flags);
7504
7505 flock = smb_flock_init(filp);
7506 if (!flock)
7507 goto out;
7508
7509 cmd = smb2_set_flock_flags(flock, flags);
7510
7511 lock_start = le64_to_cpu(lock_ele[i].Offset);
7512 lock_length = le64_to_cpu(lock_ele[i].Length);
7513 if (lock_start > U64_MAX - lock_length) {
7514 pr_err("Invalid lock range requested\n");
7515 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7516 locks_free_lock(flock);
7517 goto out;
7518 }
7519
7520 if (lock_start > OFFSET_MAX)
7521 flock->fl_start = OFFSET_MAX;
7522 else
7523 flock->fl_start = lock_start;
7524
7525 lock_length = le64_to_cpu(lock_ele[i].Length);
7526 if (lock_length > OFFSET_MAX - flock->fl_start)
7527 lock_length = OFFSET_MAX - flock->fl_start;
7528
7529 flock->fl_end = flock->fl_start + lock_length;
7530
7531 if (flock->fl_end < flock->fl_start) {
7532 ksmbd_debug(SMB,
7533 "the end offset(%llx) is smaller than the start offset(%llx)\n",
7534 flock->fl_end, flock->fl_start);
7535 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7536 locks_free_lock(flock);
7537 goto out;
7538 }
7539
7540 /* Check conflict locks in one request */
7541 list_for_each_entry(cmp_lock, &lock_list, llist) {
7542 if (cmp_lock->fl->fl_start <= flock->fl_start &&
7543 cmp_lock->fl->fl_end >= flock->fl_end) {
7544 if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7545 flock->c.flc_type != F_UNLCK) {
7546 pr_err("conflict two locks in one request\n");
7547 err = -EINVAL;
7548 locks_free_lock(flock);
7549 goto out;
7550 }
7551 }
7552 }
7553
7554 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7555 if (!smb_lock) {
7556 err = -EINVAL;
7557 locks_free_lock(flock);
7558 goto out;
7559 }
7560 }
7561
7562 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7563 if (smb_lock->cmd < 0) {
7564 err = -EINVAL;
7565 goto out;
7566 }
7567
7568 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7569 err = -EINVAL;
7570 goto out;
7571 }
7572
7573 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7574 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7575 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7576 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7577 err = -EINVAL;
7578 goto out;
7579 }
7580
7581 prior_lock = smb_lock->flags;
7582
7583 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7584 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7585 goto no_check_cl;
7586
7587 nolock = 1;
7588 /* check locks in connection list */
7589 down_read(&conn_list_lock);
7590 hash_for_each(conn_list, bkt, conn, hlist) {
7591 spin_lock(&conn->llist_lock);
7592 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7593 if (file_inode(cmp_lock->fl->c.flc_file) !=
7594 file_inode(smb_lock->fl->c.flc_file))
7595 continue;
7596
7597 if (lock_is_unlock(smb_lock->fl)) {
7598 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7599 cmp_lock->start == smb_lock->start &&
7600 cmp_lock->end == smb_lock->end &&
7601 !lock_defer_pending(cmp_lock->fl)) {
7602 nolock = 0;
7603 list_del(&cmp_lock->flist);
7604 list_del(&cmp_lock->clist);
7605 spin_unlock(&conn->llist_lock);
7606 up_read(&conn_list_lock);
7607
7608 locks_free_lock(cmp_lock->fl);
7609 kfree(cmp_lock);
7610 goto out_check_cl;
7611 }
7612 continue;
7613 }
7614
7615 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7616 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7617 continue;
7618 } else {
7619 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7620 continue;
7621 }
7622
7623 /* check zero byte lock range */
7624 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7625 cmp_lock->start > smb_lock->start &&
7626 cmp_lock->start < smb_lock->end) {
7627 spin_unlock(&conn->llist_lock);
7628 up_read(&conn_list_lock);
7629 pr_err("previous lock conflict with zero byte lock range\n");
7630 goto out;
7631 }
7632
7633 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7634 smb_lock->start > cmp_lock->start &&
7635 smb_lock->start < cmp_lock->end) {
7636 spin_unlock(&conn->llist_lock);
7637 up_read(&conn_list_lock);
7638 pr_err("current lock conflict with zero byte lock range\n");
7639 goto out;
7640 }
7641
7642 if (((cmp_lock->start <= smb_lock->start &&
7643 cmp_lock->end > smb_lock->start) ||
7644 (cmp_lock->start < smb_lock->end &&
7645 cmp_lock->end >= smb_lock->end)) &&
7646 !cmp_lock->zero_len && !smb_lock->zero_len) {
7647 spin_unlock(&conn->llist_lock);
7648 up_read(&conn_list_lock);
7649 pr_err("Not allow lock operation on exclusive lock range\n");
7650 goto out;
7651 }
7652 }
7653 spin_unlock(&conn->llist_lock);
7654 }
7655 up_read(&conn_list_lock);
7656 out_check_cl:
7657 if (lock_is_unlock(smb_lock->fl) && nolock) {
7658 pr_err("Try to unlock nolocked range\n");
7659 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7660 goto out;
7661 }
7662
7663 no_check_cl:
7664 flock = smb_lock->fl;
7665 list_del(&smb_lock->llist);
7666
7667 if (smb_lock->zero_len) {
7668 err = 0;
7669 goto skip;
7670 }
7671 retry:
7672 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7673 skip:
7674 if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
7675 locks_free_lock(flock);
7676 kfree(smb_lock);
7677 if (!rc) {
7678 ksmbd_debug(SMB, "File unlocked\n");
7679 } else if (rc == -ENOENT) {
7680 rsp->hdr.Status = STATUS_NOT_LOCKED;
7681 err = rc;
7682 goto out;
7683 }
7684 } else {
7685 if (rc == FILE_LOCK_DEFERRED) {
7686 void **argv;
7687
7688 ksmbd_debug(SMB,
7689 "would have to wait for getting lock\n");
7690 list_add(&smb_lock->llist, &rollback_list);
7691
7692 argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
7693 if (!argv) {
7694 err = -ENOMEM;
7695 goto out;
7696 }
7697 argv[0] = flock;
7698
7699 rc = setup_async_work(work,
7700 smb2_remove_blocked_lock,
7701 argv);
7702 if (rc) {
7703 kfree(argv);
7704 err = -ENOMEM;
7705 goto out;
7706 }
7707 spin_lock(&fp->f_lock);
7708 list_add(&work->fp_entry, &fp->blocked_works);
7709 spin_unlock(&fp->f_lock);
7710
7711 smb2_send_interim_resp(work, STATUS_PENDING);
7712
7713 ksmbd_vfs_posix_lock_wait(flock);
7714
7715 spin_lock(&fp->f_lock);
7716 list_del(&work->fp_entry);
7717 spin_unlock(&fp->f_lock);
7718
7719 if (work->state != KSMBD_WORK_ACTIVE) {
7720 list_del(&smb_lock->llist);
7721 locks_free_lock(flock);
7722
7723 if (work->state == KSMBD_WORK_CANCELLED) {
7724 rsp->hdr.Status =
7725 STATUS_CANCELLED;
7726 kfree(smb_lock);
7727 smb2_send_interim_resp(work,
7728 STATUS_CANCELLED);
7729 work->send_no_response = 1;
7730 goto out;
7731 }
7732
7733 rsp->hdr.Status =
7734 STATUS_RANGE_NOT_LOCKED;
7735 kfree(smb_lock);
7736 goto out2;
7737 }
7738
7739 list_del(&smb_lock->llist);
7740 release_async_work(work);
7741 goto retry;
7742 } else if (!rc) {
7743 list_add(&smb_lock->llist, &rollback_list);
7744 spin_lock(&work->conn->llist_lock);
7745 list_add_tail(&smb_lock->clist,
7746 &work->conn->lock_list);
7747 list_add_tail(&smb_lock->flist,
7748 &fp->lock_list);
7749 spin_unlock(&work->conn->llist_lock);
7750 ksmbd_debug(SMB, "successful in taking lock\n");
7751 } else {
7752 locks_free_lock(flock);
7753 kfree(smb_lock);
7754 err = rc;
7755 goto out;
7756 }
7757 }
7758 }
7759
7760 if (atomic_read(&fp->f_ci->op_count) > 1)
7761 smb_break_all_oplock(work, fp);
7762
7763 rsp->StructureSize = cpu_to_le16(4);
7764 ksmbd_debug(SMB, "successful in taking lock\n");
7765 rsp->hdr.Status = STATUS_SUCCESS;
7766 rsp->Reserved = 0;
7767 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7768 if (err)
7769 goto out;
7770
7771 ksmbd_fd_put(work, fp);
7772 return 0;
7773
7774 out:
7775 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7776 locks_free_lock(smb_lock->fl);
7777 list_del(&smb_lock->llist);
7778 kfree(smb_lock);
7779 }
7780
7781 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7782 struct file_lock *rlock = NULL;
7783
7784 rlock = smb_flock_init(filp);
7785 if (rlock) {
7786 rlock->c.flc_type = F_UNLCK;
7787 rlock->fl_start = smb_lock->start;
7788 rlock->fl_end = smb_lock->end;
7789
7790 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7791 if (rc)
7792 pr_err("rollback unlock fail : %d\n", rc);
7793 } else {
7794 pr_err("rollback unlock alloc failed\n");
7795 }
7796
7797 list_del(&smb_lock->llist);
7798 spin_lock(&work->conn->llist_lock);
7799 if (!list_empty(&smb_lock->flist))
7800 list_del(&smb_lock->flist);
7801 list_del(&smb_lock->clist);
7802 spin_unlock(&work->conn->llist_lock);
7803
7804 locks_free_lock(smb_lock->fl);
7805 if (rlock)
7806 locks_free_lock(rlock);
7807 kfree(smb_lock);
7808 }
7809 out2:
7810 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7811
7812 if (!rsp->hdr.Status) {
7813 if (err == -EINVAL)
7814 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7815 else if (err == -ENOMEM)
7816 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7817 else if (err == -ENOENT)
7818 rsp->hdr.Status = STATUS_FILE_CLOSED;
7819 else
7820 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7821 }
7822
7823 smb2_set_err_rsp(work);
7824 ksmbd_fd_put(work, fp);
7825 return err;
7826 }
7827
7828 static int fsctl_copychunk(struct ksmbd_work *work,
7829 struct copychunk_ioctl_req *ci_req,
7830 unsigned int cnt_code,
7831 unsigned int input_count,
7832 unsigned long long volatile_id,
7833 unsigned long long persistent_id,
7834 struct smb2_ioctl_rsp *rsp)
7835 {
7836 struct copychunk_ioctl_rsp *ci_rsp;
7837 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7838 struct srv_copychunk *chunks;
7839 unsigned int i, chunk_count, chunk_count_written = 0;
7840 unsigned int chunk_size_written = 0;
7841 loff_t total_size_written = 0;
7842 int ret = 0;
7843
7844 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7845
7846 rsp->VolatileFileId = volatile_id;
7847 rsp->PersistentFileId = persistent_id;
7848 ci_rsp->ChunksWritten =
7849 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7850 ci_rsp->ChunkBytesWritten =
7851 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7852 ci_rsp->TotalBytesWritten =
7853 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7854
7855 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7856 if (chunk_count == 0)
7857 goto out;
7858 total_size_written = 0;
7859
7860 /* verify the SRV_COPYCHUNK_COPY packet */
7861 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7862 input_count < struct_size(ci_req, Chunks, chunk_count)) {
7863 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7864 return -EINVAL;
7865 }
7866
7867 chunks = &ci_req->Chunks[0];
7868 for (i = 0; i < chunk_count; i++) {
7869 if (le32_to_cpu(chunks[i].Length) == 0 ||
7870 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7871 break;
7872 total_size_written += le32_to_cpu(chunks[i].Length);
7873 }
7874
7875 if (i < chunk_count ||
7876 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7877 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7878 return -EINVAL;
7879 }
7880
7881 src_fp = ksmbd_lookup_foreign_fd(work,
7882 le64_to_cpu(ci_req->SourceKeyU64[0]));
7883 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7884 ret = -EINVAL;
7885 if (!src_fp ||
7886 src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
7887 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7888 goto out;
7889 }
7890
7891 if (!dst_fp) {
7892 rsp->hdr.Status = STATUS_FILE_CLOSED;
7893 goto out;
7894 }
7895
7896 /*
7897 * FILE_READ_DATA should only be included in
7898 * the FSCTL_COPYCHUNK case
7899 */
7900 if (cnt_code == FSCTL_COPYCHUNK &&
7901 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7902 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7903 goto out;
7904 }
7905
7906 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7907 chunks, chunk_count,
7908 &chunk_count_written,
7909 &chunk_size_written,
7910 &total_size_written);
7911 if (ret < 0) {
7912 if (ret == -EACCES)
7913 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7914 if (ret == -EAGAIN)
7915 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7916 else if (ret == -EBADF)
7917 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7918 else if (ret == -EFBIG || ret == -ENOSPC)
7919 rsp->hdr.Status = STATUS_DISK_FULL;
7920 else if (ret == -EINVAL)
7921 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7922 else if (ret == -EISDIR)
7923 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7924 else if (ret == -E2BIG)
7925 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7926 else
7927 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7928 }
7929
7930 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7931 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7932 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7933 out:
7934 ksmbd_fd_put(work, src_fp);
7935 ksmbd_fd_put(work, dst_fp);
7936 return ret;
7937 }
7938
7939 static __be32 idev_ipv4_address(struct in_device *idev)
7940 {
7941 __be32 addr = 0;
7942
7943 struct in_ifaddr *ifa;
7944
7945 rcu_read_lock();
7946 in_dev_for_each_ifa_rcu(ifa, idev) {
7947 if (ifa->ifa_flags & IFA_F_SECONDARY)
7948 continue;
7949
7950 addr = ifa->ifa_address;
7951 break;
7952 }
7953 rcu_read_unlock();
7954 return addr;
7955 }
7956
7957 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7958 struct smb2_ioctl_rsp *rsp,
7959 unsigned int out_buf_len)
7960 {
7961 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7962 int nbytes = 0;
7963 struct net_device *netdev;
7964 struct sockaddr_storage_rsp *sockaddr_storage;
7965 unsigned int flags;
7966 unsigned long long speed;
7967
7968 rtnl_lock();
7969 for_each_netdev(&init_net, netdev) {
7970 bool ipv4_set = false;
7971
7972 if (netdev->type == ARPHRD_LOOPBACK)
7973 continue;
7974
7975 if (!ksmbd_find_netdev_name_iface_list(netdev->name))
7976 continue;
7977
7978 flags = netif_get_flags(netdev);
7979 if (!(flags & IFF_RUNNING))
7980 continue;
7981 ipv6_retry:
7982 if (out_buf_len <
7983 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7984 rtnl_unlock();
7985 return -ENOSPC;
7986 }
7987
7988 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7989 &rsp->Buffer[nbytes];
7990 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7991
7992 nii_rsp->Capability = 0;
7993 if (netdev->real_num_tx_queues > 1)
7994 nii_rsp->Capability |= RSS_CAPABLE;
7995 if (ksmbd_rdma_capable_netdev(netdev))
7996 nii_rsp->Capability |= RDMA_CAPABLE;
7997
7998 nii_rsp->Next = cpu_to_le32(152);
7999 nii_rsp->Reserved = 0;
8000
8001 if (netdev->ethtool_ops->get_link_ksettings) {
8002 struct ethtool_link_ksettings cmd;
8003
8004 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
8005 speed = cmd.base.speed;
8006 } else {
8007 ksmbd_debug(SMB, "%s %s\n", netdev->name,
8008 "speed is unknown, defaulting to 1Gb/sec");
8009 speed = SPEED_1000;
8010 }
8011
8012 speed *= 1000000;
8013 nii_rsp->LinkSpeed = cpu_to_le64(speed);
8014
8015 sockaddr_storage = (struct sockaddr_storage_rsp *)
8016 nii_rsp->SockAddr_Storage;
8017 memset(sockaddr_storage, 0, 128);
8018
8019 if (!ipv4_set) {
8020 struct in_device *idev;
8021
8022 sockaddr_storage->Family = INTERNETWORK;
8023 sockaddr_storage->addr4.Port = 0;
8024
8025 idev = __in_dev_get_rtnl(netdev);
8026 if (!idev)
8027 continue;
8028 sockaddr_storage->addr4.IPv4Address =
8029 idev_ipv4_address(idev);
8030 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8031 ipv4_set = true;
8032 goto ipv6_retry;
8033 } else {
8034 struct inet6_dev *idev6;
8035 struct inet6_ifaddr *ifa;
8036 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
8037
8038 sockaddr_storage->Family = INTERNETWORKV6;
8039 sockaddr_storage->addr6.Port = 0;
8040 sockaddr_storage->addr6.FlowInfo = 0;
8041
8042 idev6 = __in6_dev_get(netdev);
8043 if (!idev6)
8044 continue;
8045
8046 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
8047 if (ifa->flags & (IFA_F_TENTATIVE |
8048 IFA_F_DEPRECATED))
8049 continue;
8050 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
8051 break;
8052 }
8053 sockaddr_storage->addr6.ScopeId = 0;
8054 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8055 }
8056 }
8057 rtnl_unlock();
8058
8059 /* zero if this is last one */
8060 if (nii_rsp)
8061 nii_rsp->Next = 0;
8062
8063 rsp->PersistentFileId = SMB2_NO_FID;
8064 rsp->VolatileFileId = SMB2_NO_FID;
8065 return nbytes;
8066 }
8067
8068 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
8069 struct validate_negotiate_info_req *neg_req,
8070 struct validate_negotiate_info_rsp *neg_rsp,
8071 unsigned int in_buf_len)
8072 {
8073 int ret = 0;
8074 int dialect;
8075
8076 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
8077 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
8078 return -EINVAL;
8079
8080 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
8081 neg_req->DialectCount);
8082 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
8083 ret = -EINVAL;
8084 goto err_out;
8085 }
8086
8087 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
8088 ret = -EINVAL;
8089 goto err_out;
8090 }
8091
8092 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
8093 ret = -EINVAL;
8094 goto err_out;
8095 }
8096
8097 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
8098 ret = -EINVAL;
8099 goto err_out;
8100 }
8101
8102 neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
8103 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
8104 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
8105 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
8106 err_out:
8107 return ret;
8108 }
8109
8110 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
8111 struct file_allocated_range_buffer *qar_req,
8112 struct file_allocated_range_buffer *qar_rsp,
8113 unsigned int in_count, unsigned int *out_count)
8114 {
8115 struct ksmbd_file *fp;
8116 loff_t start, length;
8117 int ret = 0;
8118
8119 *out_count = 0;
8120 if (in_count == 0)
8121 return -EINVAL;
8122
8123 start = le64_to_cpu(qar_req->file_offset);
8124 length = le64_to_cpu(qar_req->length);
8125
8126 if (start < 0 || length < 0)
8127 return -EINVAL;
8128
8129 fp = ksmbd_lookup_fd_fast(work, id);
8130 if (!fp)
8131 return -ENOENT;
8132
8133 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8134 qar_rsp, in_count, out_count);
8135 if (ret && ret != -E2BIG)
8136 *out_count = 0;
8137
8138 ksmbd_fd_put(work, fp);
8139 return ret;
8140 }
8141
8142 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8143 unsigned int out_buf_len,
8144 struct smb2_ioctl_req *req,
8145 struct smb2_ioctl_rsp *rsp)
8146 {
8147 struct ksmbd_rpc_command *rpc_resp;
8148 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8149 int nbytes = 0;
8150
8151 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8152 le32_to_cpu(req->InputCount));
8153 if (rpc_resp) {
8154 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8155 /*
8156 * set STATUS_SOME_NOT_MAPPED response
8157 * for unknown domain sid.
8158 */
8159 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8160 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8161 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8162 goto out;
8163 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
8164 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8165 goto out;
8166 }
8167
8168 nbytes = rpc_resp->payload_sz;
8169 if (rpc_resp->payload_sz > out_buf_len) {
8170 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8171 nbytes = out_buf_len;
8172 }
8173
8174 if (!rpc_resp->payload_sz) {
8175 rsp->hdr.Status =
8176 STATUS_UNEXPECTED_IO_ERROR;
8177 goto out;
8178 }
8179
8180 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8181 }
8182 out:
8183 kvfree(rpc_resp);
8184 return nbytes;
8185 }
8186
8187 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8188 struct file_sparse *sparse)
8189 {
8190 struct ksmbd_file *fp;
8191 struct mnt_idmap *idmap;
8192 int ret = 0;
8193 __le32 old_fattr;
8194
8195 fp = ksmbd_lookup_fd_fast(work, id);
8196 if (!fp)
8197 return -ENOENT;
8198 idmap = file_mnt_idmap(fp->filp);
8199
8200 old_fattr = fp->f_ci->m_fattr;
8201 if (sparse->SetSparse)
8202 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8203 else
8204 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8205
8206 if (fp->f_ci->m_fattr != old_fattr &&
8207 test_share_config_flag(work->tcon->share_conf,
8208 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8209 struct xattr_dos_attrib da;
8210
8211 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8212 fp->filp->f_path.dentry, &da);
8213 if (ret <= 0)
8214 goto out;
8215
8216 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8217 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8218 &fp->filp->f_path,
8219 &da, true);
8220 if (ret)
8221 fp->f_ci->m_fattr = old_fattr;
8222 }
8223
8224 out:
8225 ksmbd_fd_put(work, fp);
8226 return ret;
8227 }
8228
8229 static int fsctl_request_resume_key(struct ksmbd_work *work,
8230 struct smb2_ioctl_req *req,
8231 struct resume_key_ioctl_rsp *key_rsp)
8232 {
8233 struct ksmbd_file *fp;
8234
8235 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8236 if (!fp)
8237 return -ENOENT;
8238
8239 memset(key_rsp, 0, sizeof(*key_rsp));
8240 key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
8241 key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
8242 ksmbd_fd_put(work, fp);
8243
8244 return 0;
8245 }
8246
8247 /**
8248 * smb2_ioctl() - handler for smb2 ioctl command
8249 * @work: smb work containing ioctl command buffer
8250 *
8251 * Return: 0 on success, otherwise error
8252 */
8253 int smb2_ioctl(struct ksmbd_work *work)
8254 {
8255 struct smb2_ioctl_req *req;
8256 struct smb2_ioctl_rsp *rsp;
8257 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8258 u64 id = KSMBD_NO_FID;
8259 struct ksmbd_conn *conn = work->conn;
8260 int ret = 0;
8261 char *buffer;
8262
8263 ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8264
8265 if (work->next_smb2_rcv_hdr_off) {
8266 req = ksmbd_req_buf_next(work);
8267 rsp = ksmbd_resp_buf_next(work);
8268 if (!has_file_id(req->VolatileFileId)) {
8269 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8270 work->compound_fid);
8271 id = work->compound_fid;
8272 }
8273 } else {
8274 req = smb_get_msg(work->request_buf);
8275 rsp = smb_get_msg(work->response_buf);
8276 }
8277
8278 if (!has_file_id(id))
8279 id = req->VolatileFileId;
8280
8281 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8282 ret = -EOPNOTSUPP;
8283 goto out;
8284 }
8285
8286 buffer = (char *)req + le32_to_cpu(req->InputOffset);
8287
8288 cnt_code = le32_to_cpu(req->CtlCode);
8289 ret = smb2_calc_max_out_buf_len(work,
8290 offsetof(struct smb2_ioctl_rsp, Buffer),
8291 le32_to_cpu(req->MaxOutputResponse));
8292 if (ret < 0) {
8293 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8294 goto out;
8295 }
8296 out_buf_len = (unsigned int)ret;
8297 in_buf_len = le32_to_cpu(req->InputCount);
8298
8299 switch (cnt_code) {
8300 case FSCTL_DFS_GET_REFERRALS:
8301 case FSCTL_DFS_GET_REFERRALS_EX:
8302 /* Not support DFS yet */
8303 ret = -EOPNOTSUPP;
8304 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8305 goto out2;
8306 case FSCTL_CREATE_OR_GET_OBJECT_ID:
8307 {
8308 struct file_object_buf_type1_ioctl_rsp *obj_buf;
8309
8310 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8311 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8312 &rsp->Buffer[0];
8313
8314 /*
8315 * TODO: This is dummy implementation to pass smbtorture
8316 * Need to check correct response later
8317 */
8318 memset(obj_buf->ObjectId, 0x0, 16);
8319 memset(obj_buf->BirthVolumeId, 0x0, 16);
8320 memset(obj_buf->BirthObjectId, 0x0, 16);
8321 memset(obj_buf->DomainId, 0x0, 16);
8322
8323 break;
8324 }
8325 case FSCTL_PIPE_TRANSCEIVE:
8326 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8327 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8328 break;
8329 case FSCTL_VALIDATE_NEGOTIATE_INFO:
8330 if (conn->dialect < SMB30_PROT_ID) {
8331 ret = -EOPNOTSUPP;
8332 goto out;
8333 }
8334
8335 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8336 Dialects)) {
8337 ret = -EINVAL;
8338 goto out;
8339 }
8340
8341 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8342 ret = -EINVAL;
8343 goto out;
8344 }
8345
8346 ret = fsctl_validate_negotiate_info(conn,
8347 (struct validate_negotiate_info_req *)buffer,
8348 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8349 in_buf_len);
8350 if (ret < 0)
8351 goto out;
8352
8353 nbytes = sizeof(struct validate_negotiate_info_rsp);
8354 rsp->PersistentFileId = SMB2_NO_FID;
8355 rsp->VolatileFileId = SMB2_NO_FID;
8356 break;
8357 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8358 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8359 if (ret < 0)
8360 goto out;
8361 nbytes = ret;
8362 break;
8363 case FSCTL_REQUEST_RESUME_KEY:
8364 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8365 ret = -EINVAL;
8366 goto out;
8367 }
8368
8369 ret = fsctl_request_resume_key(work, req,
8370 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8371 if (ret < 0)
8372 goto out;
8373 rsp->PersistentFileId = req->PersistentFileId;
8374 rsp->VolatileFileId = req->VolatileFileId;
8375 nbytes = sizeof(struct resume_key_ioctl_rsp);
8376 break;
8377 case FSCTL_COPYCHUNK:
8378 case FSCTL_COPYCHUNK_WRITE:
8379 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8380 ksmbd_debug(SMB,
8381 "User does not have write permission\n");
8382 ret = -EACCES;
8383 goto out;
8384 }
8385
8386 if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
8387 ret = -EINVAL;
8388 goto out;
8389 }
8390
8391 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8392 ret = -EINVAL;
8393 goto out;
8394 }
8395
8396 nbytes = sizeof(struct copychunk_ioctl_rsp);
8397 rsp->VolatileFileId = req->VolatileFileId;
8398 rsp->PersistentFileId = req->PersistentFileId;
8399 fsctl_copychunk(work,
8400 (struct copychunk_ioctl_req *)buffer,
8401 le32_to_cpu(req->CtlCode),
8402 le32_to_cpu(req->InputCount),
8403 req->VolatileFileId,
8404 req->PersistentFileId,
8405 rsp);
8406 break;
8407 case FSCTL_SET_SPARSE:
8408 if (in_buf_len < sizeof(struct file_sparse)) {
8409 ret = -EINVAL;
8410 goto out;
8411 }
8412
8413 ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8414 if (ret < 0)
8415 goto out;
8416 break;
8417 case FSCTL_SET_ZERO_DATA:
8418 {
8419 struct file_zero_data_information *zero_data;
8420 struct ksmbd_file *fp;
8421 loff_t off, len, bfz;
8422
8423 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8424 ksmbd_debug(SMB,
8425 "User does not have write permission\n");
8426 ret = -EACCES;
8427 goto out;
8428 }
8429
8430 if (in_buf_len < sizeof(struct file_zero_data_information)) {
8431 ret = -EINVAL;
8432 goto out;
8433 }
8434
8435 zero_data =
8436 (struct file_zero_data_information *)buffer;
8437
8438 off = le64_to_cpu(zero_data->FileOffset);
8439 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8440 if (off < 0 || bfz < 0 || off > bfz) {
8441 ret = -EINVAL;
8442 goto out;
8443 }
8444
8445 len = bfz - off;
8446 if (len) {
8447 fp = ksmbd_lookup_fd_fast(work, id);
8448 if (!fp) {
8449 ret = -ENOENT;
8450 goto out;
8451 }
8452
8453 ret = ksmbd_vfs_zero_data(work, fp, off, len);
8454 ksmbd_fd_put(work, fp);
8455 if (ret < 0)
8456 goto out;
8457 }
8458 break;
8459 }
8460 case FSCTL_QUERY_ALLOCATED_RANGES:
8461 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8462 ret = -EINVAL;
8463 goto out;
8464 }
8465
8466 ret = fsctl_query_allocated_ranges(work, id,
8467 (struct file_allocated_range_buffer *)buffer,
8468 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
8469 out_buf_len /
8470 sizeof(struct file_allocated_range_buffer), &nbytes);
8471 if (ret == -E2BIG) {
8472 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8473 } else if (ret < 0) {
8474 nbytes = 0;
8475 goto out;
8476 }
8477
8478 nbytes *= sizeof(struct file_allocated_range_buffer);
8479 break;
8480 case FSCTL_GET_REPARSE_POINT:
8481 {
8482 struct reparse_data_buffer *reparse_ptr;
8483 struct ksmbd_file *fp;
8484
8485 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8486 fp = ksmbd_lookup_fd_fast(work, id);
8487 if (!fp) {
8488 pr_err("not found fp!!\n");
8489 ret = -ENOENT;
8490 goto out;
8491 }
8492
8493 reparse_ptr->ReparseTag =
8494 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8495 reparse_ptr->ReparseDataLength = 0;
8496 ksmbd_fd_put(work, fp);
8497 nbytes = sizeof(struct reparse_data_buffer);
8498 break;
8499 }
8500 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8501 {
8502 struct ksmbd_file *fp_in, *fp_out = NULL;
8503 struct duplicate_extents_to_file *dup_ext;
8504 loff_t src_off, dst_off, length, cloned;
8505
8506 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8507 ret = -EINVAL;
8508 goto out;
8509 }
8510
8511 dup_ext = (struct duplicate_extents_to_file *)buffer;
8512
8513 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8514 dup_ext->PersistentFileHandle);
8515 if (!fp_in) {
8516 pr_err("not found file handle in duplicate extent to file\n");
8517 ret = -ENOENT;
8518 goto out;
8519 }
8520
8521 fp_out = ksmbd_lookup_fd_fast(work, id);
8522 if (!fp_out) {
8523 pr_err("not found fp\n");
8524 ret = -ENOENT;
8525 goto dup_ext_out;
8526 }
8527
8528 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8529 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8530 length = le64_to_cpu(dup_ext->ByteCount);
8531 /*
8532 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8533 * should fall back to vfs_copy_file_range(). This could be
8534 * beneficial when re-exporting nfs/smb mount, but note that
8535 * this can result in partial copy that returns an error status.
8536 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8537 * fall back to vfs_copy_file_range(), should be avoided when
8538 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8539 */
8540 cloned = vfs_clone_file_range(fp_in->filp, src_off,
8541 fp_out->filp, dst_off, length, 0);
8542 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8543 ret = -EOPNOTSUPP;
8544 goto dup_ext_out;
8545 } else if (cloned != length) {
8546 cloned = vfs_copy_file_range(fp_in->filp, src_off,
8547 fp_out->filp, dst_off,
8548 length, 0);
8549 if (cloned != length) {
8550 if (cloned < 0)
8551 ret = cloned;
8552 else
8553 ret = -EINVAL;
8554 }
8555 }
8556
8557 dup_ext_out:
8558 ksmbd_fd_put(work, fp_in);
8559 ksmbd_fd_put(work, fp_out);
8560 if (ret < 0)
8561 goto out;
8562 break;
8563 }
8564 default:
8565 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8566 cnt_code);
8567 ret = -EOPNOTSUPP;
8568 goto out;
8569 }
8570
8571 rsp->CtlCode = cpu_to_le32(cnt_code);
8572 rsp->InputCount = cpu_to_le32(0);
8573 rsp->InputOffset = cpu_to_le32(112);
8574 rsp->OutputOffset = cpu_to_le32(112);
8575 rsp->OutputCount = cpu_to_le32(nbytes);
8576 rsp->StructureSize = cpu_to_le16(49);
8577 rsp->Reserved = cpu_to_le16(0);
8578 rsp->Flags = cpu_to_le32(0);
8579 rsp->Reserved2 = cpu_to_le32(0);
8580 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8581 if (!ret)
8582 return ret;
8583
8584 out:
8585 if (ret == -EACCES)
8586 rsp->hdr.Status = STATUS_ACCESS_DENIED;
8587 else if (ret == -ENOENT)
8588 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8589 else if (ret == -EOPNOTSUPP)
8590 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8591 else if (ret == -ENOSPC)
8592 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8593 else if (ret < 0 || rsp->hdr.Status == 0)
8594 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8595
8596 out2:
8597 smb2_set_err_rsp(work);
8598 return ret;
8599 }
8600
8601 /**
8602 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8603 * @work: smb work containing oplock break command buffer
8604 *
8605 * Return: 0
8606 */
8607 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8608 {
8609 struct smb2_oplock_break *req;
8610 struct smb2_oplock_break *rsp;
8611 struct ksmbd_file *fp;
8612 struct oplock_info *opinfo = NULL;
8613 __le32 err = 0;
8614 int ret = 0;
8615 u64 volatile_id, persistent_id;
8616 char req_oplevel = 0, rsp_oplevel = 0;
8617 unsigned int oplock_change_type;
8618
8619 WORK_BUFFERS(work, req, rsp);
8620
8621 volatile_id = req->VolatileFid;
8622 persistent_id = req->PersistentFid;
8623 req_oplevel = req->OplockLevel;
8624 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8625 volatile_id, persistent_id, req_oplevel);
8626
8627 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8628 if (!fp) {
8629 rsp->hdr.Status = STATUS_FILE_CLOSED;
8630 smb2_set_err_rsp(work);
8631 return;
8632 }
8633
8634 opinfo = opinfo_get(fp);
8635 if (!opinfo) {
8636 pr_err("unexpected null oplock_info\n");
8637 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8638 smb2_set_err_rsp(work);
8639 ksmbd_fd_put(work, fp);
8640 return;
8641 }
8642
8643 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8644 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8645 goto err_out;
8646 }
8647
8648 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8649 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8650 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8651 goto err_out;
8652 }
8653
8654 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8655 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8656 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8657 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8658 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8659 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8660 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8661 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8662 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8663 oplock_change_type = OPLOCK_READ_TO_NONE;
8664 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8665 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8666 err = STATUS_INVALID_DEVICE_STATE;
8667 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8668 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8669 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8670 oplock_change_type = OPLOCK_WRITE_TO_READ;
8671 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8672 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8673 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8674 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8675 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8676 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8677 oplock_change_type = OPLOCK_READ_TO_NONE;
8678 } else {
8679 oplock_change_type = 0;
8680 }
8681 } else {
8682 oplock_change_type = 0;
8683 }
8684
8685 switch (oplock_change_type) {
8686 case OPLOCK_WRITE_TO_READ:
8687 ret = opinfo_write_to_read(opinfo);
8688 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8689 break;
8690 case OPLOCK_WRITE_TO_NONE:
8691 ret = opinfo_write_to_none(opinfo);
8692 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8693 break;
8694 case OPLOCK_READ_TO_NONE:
8695 ret = opinfo_read_to_none(opinfo);
8696 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8697 break;
8698 default:
8699 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8700 opinfo->level, rsp_oplevel);
8701 }
8702
8703 if (ret < 0) {
8704 rsp->hdr.Status = err;
8705 goto err_out;
8706 }
8707
8708 rsp->StructureSize = cpu_to_le16(24);
8709 rsp->OplockLevel = rsp_oplevel;
8710 rsp->Reserved = 0;
8711 rsp->Reserved2 = 0;
8712 rsp->VolatileFid = volatile_id;
8713 rsp->PersistentFid = persistent_id;
8714 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8715 if (ret) {
8716 err_out:
8717 smb2_set_err_rsp(work);
8718 }
8719
8720 opinfo->op_state = OPLOCK_STATE_NONE;
8721 wake_up_interruptible_all(&opinfo->oplock_q);
8722 opinfo_put(opinfo);
8723 ksmbd_fd_put(work, fp);
8724 }
8725
8726 static int check_lease_state(struct lease *lease, __le32 req_state)
8727 {
8728 if ((lease->new_state ==
8729 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8730 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8731 lease->new_state = req_state;
8732 return 0;
8733 }
8734
8735 if (lease->new_state == req_state)
8736 return 0;
8737
8738 return 1;
8739 }
8740
8741 /**
8742 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8743 * @work: smb work containing lease break command buffer
8744 *
8745 * Return: 0
8746 */
8747 static void smb21_lease_break_ack(struct ksmbd_work *work)
8748 {
8749 struct ksmbd_conn *conn = work->conn;
8750 struct smb2_lease_ack *req;
8751 struct smb2_lease_ack *rsp;
8752 struct oplock_info *opinfo;
8753 __le32 err = 0;
8754 int ret = 0;
8755 unsigned int lease_change_type;
8756 __le32 lease_state;
8757 struct lease *lease;
8758
8759 WORK_BUFFERS(work, req, rsp);
8760
8761 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8762 le32_to_cpu(req->LeaseState));
8763 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8764 if (!opinfo) {
8765 ksmbd_debug(OPLOCK, "file not opened\n");
8766 smb2_set_err_rsp(work);
8767 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8768 return;
8769 }
8770 lease = opinfo->o_lease;
8771
8772 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8773 pr_err("unexpected lease break state 0x%x\n",
8774 opinfo->op_state);
8775 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8776 goto err_out;
8777 }
8778
8779 if (check_lease_state(lease, req->LeaseState)) {
8780 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8781 ksmbd_debug(OPLOCK,
8782 "req lease state: 0x%x, expected state: 0x%x\n",
8783 req->LeaseState, lease->new_state);
8784 goto err_out;
8785 }
8786
8787 if (!atomic_read(&opinfo->breaking_cnt)) {
8788 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8789 goto err_out;
8790 }
8791
8792 /* check for bad lease state */
8793 if (req->LeaseState &
8794 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8795 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8796 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8797 lease_change_type = OPLOCK_WRITE_TO_NONE;
8798 else
8799 lease_change_type = OPLOCK_READ_TO_NONE;
8800 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8801 le32_to_cpu(lease->state),
8802 le32_to_cpu(req->LeaseState));
8803 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8804 req->LeaseState != SMB2_LEASE_NONE_LE) {
8805 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8806 lease_change_type = OPLOCK_READ_TO_NONE;
8807 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8808 le32_to_cpu(lease->state),
8809 le32_to_cpu(req->LeaseState));
8810 } else {
8811 /* valid lease state changes */
8812 err = STATUS_INVALID_DEVICE_STATE;
8813 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8814 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8815 lease_change_type = OPLOCK_WRITE_TO_NONE;
8816 else
8817 lease_change_type = OPLOCK_READ_TO_NONE;
8818 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8819 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8820 lease_change_type = OPLOCK_WRITE_TO_READ;
8821 else
8822 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8823 } else {
8824 lease_change_type = 0;
8825 }
8826 }
8827
8828 switch (lease_change_type) {
8829 case OPLOCK_WRITE_TO_READ:
8830 ret = opinfo_write_to_read(opinfo);
8831 break;
8832 case OPLOCK_READ_HANDLE_TO_READ:
8833 ret = opinfo_read_handle_to_read(opinfo);
8834 break;
8835 case OPLOCK_WRITE_TO_NONE:
8836 ret = opinfo_write_to_none(opinfo);
8837 break;
8838 case OPLOCK_READ_TO_NONE:
8839 ret = opinfo_read_to_none(opinfo);
8840 break;
8841 default:
8842 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8843 le32_to_cpu(lease->state),
8844 le32_to_cpu(req->LeaseState));
8845 }
8846
8847 if (ret < 0) {
8848 rsp->hdr.Status = err;
8849 goto err_out;
8850 }
8851
8852 lease_state = lease->state;
8853
8854 rsp->StructureSize = cpu_to_le16(36);
8855 rsp->Reserved = 0;
8856 rsp->Flags = 0;
8857 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8858 rsp->LeaseState = lease_state;
8859 rsp->LeaseDuration = 0;
8860 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8861 if (ret) {
8862 err_out:
8863 smb2_set_err_rsp(work);
8864 }
8865
8866 opinfo->op_state = OPLOCK_STATE_NONE;
8867 wake_up_interruptible_all(&opinfo->oplock_q);
8868 atomic_dec(&opinfo->breaking_cnt);
8869 wake_up_interruptible_all(&opinfo->oplock_brk);
8870 opinfo_put(opinfo);
8871 }
8872
8873 /**
8874 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8875 * @work: smb work containing oplock/lease break command buffer
8876 *
8877 * Return: 0 on success, otherwise error
8878 */
8879 int smb2_oplock_break(struct ksmbd_work *work)
8880 {
8881 struct smb2_oplock_break *req;
8882 struct smb2_oplock_break *rsp;
8883
8884 ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
8885
8886 WORK_BUFFERS(work, req, rsp);
8887
8888 switch (le16_to_cpu(req->StructureSize)) {
8889 case OP_BREAK_STRUCT_SIZE_20:
8890 smb20_oplock_break_ack(work);
8891 break;
8892 case OP_BREAK_STRUCT_SIZE_21:
8893 smb21_lease_break_ack(work);
8894 break;
8895 default:
8896 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8897 le16_to_cpu(req->StructureSize));
8898 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8899 smb2_set_err_rsp(work);
8900 return -EINVAL;
8901 }
8902
8903 return 0;
8904 }
8905
8906 /**
8907 * smb2_notify() - handler for smb2 notify request
8908 * @work: smb work containing notify command buffer
8909 *
8910 * Return: 0 on success, otherwise error
8911 */
8912 int smb2_notify(struct ksmbd_work *work)
8913 {
8914 struct smb2_change_notify_req *req;
8915 struct smb2_change_notify_rsp *rsp;
8916
8917 ksmbd_debug(SMB, "Received smb2 notify\n");
8918
8919 WORK_BUFFERS(work, req, rsp);
8920
8921 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8922 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8923 smb2_set_err_rsp(work);
8924 return -EIO;
8925 }
8926
8927 smb2_set_err_rsp(work);
8928 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8929 return -EOPNOTSUPP;
8930 }
8931
8932 /**
8933 * smb2_is_sign_req() - handler for checking packet signing status
8934 * @work: smb work containing notify command buffer
8935 * @command: SMB2 command id
8936 *
8937 * Return: true if packed is signed, false otherwise
8938 */
8939 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8940 {
8941 struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
8942
8943 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8944 command != SMB2_NEGOTIATE_HE &&
8945 command != SMB2_SESSION_SETUP_HE &&
8946 command != SMB2_OPLOCK_BREAK_HE)
8947 return true;
8948
8949 return false;
8950 }
8951
8952 /**
8953 * smb2_check_sign_req() - handler for req packet sign processing
8954 * @work: smb work containing notify command buffer
8955 *
8956 * Return: 1 on success, 0 otherwise
8957 */
8958 int smb2_check_sign_req(struct ksmbd_work *work)
8959 {
8960 struct smb2_hdr *hdr;
8961 char signature_req[SMB2_SIGNATURE_SIZE];
8962 char signature[SMB2_HMACSHA256_SIZE];
8963 struct kvec iov[1];
8964 size_t len;
8965
8966 hdr = smb_get_msg(work->request_buf);
8967 if (work->next_smb2_rcv_hdr_off)
8968 hdr = ksmbd_req_buf_next(work);
8969
8970 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8971 len = get_rfc1002_len(work->request_buf);
8972 else if (hdr->NextCommand)
8973 len = le32_to_cpu(hdr->NextCommand);
8974 else
8975 len = get_rfc1002_len(work->request_buf) -
8976 work->next_smb2_rcv_hdr_off;
8977
8978 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8979 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8980
8981 iov[0].iov_base = (char *)&hdr->ProtocolId;
8982 iov[0].iov_len = len;
8983
8984 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8985 signature);
8986
8987 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8988 pr_err("bad smb2 signature\n");
8989 return 0;
8990 }
8991
8992 return 1;
8993 }
8994
8995 /**
8996 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8997 * @work: smb work containing notify command buffer
8998 *
8999 */
9000 void smb2_set_sign_rsp(struct ksmbd_work *work)
9001 {
9002 struct smb2_hdr *hdr;
9003 char signature[SMB2_HMACSHA256_SIZE];
9004 struct kvec *iov;
9005 int n_vec = 1;
9006
9007 hdr = ksmbd_resp_buf_curr(work);
9008 hdr->Flags |= SMB2_FLAGS_SIGNED;
9009 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9010
9011 if (hdr->Command == SMB2_READ) {
9012 iov = &work->iov[work->iov_idx - 1];
9013 n_vec++;
9014 } else {
9015 iov = &work->iov[work->iov_idx];
9016 }
9017
9018 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
9019 signature);
9020 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9021 }
9022
9023 /**
9024 * smb3_check_sign_req() - handler for req packet sign processing
9025 * @work: smb work containing notify command buffer
9026 *
9027 * Return: 1 on success, 0 otherwise
9028 */
9029 int smb3_check_sign_req(struct ksmbd_work *work)
9030 {
9031 struct ksmbd_conn *conn = work->conn;
9032 char *signing_key;
9033 struct smb2_hdr *hdr;
9034 struct channel *chann;
9035 char signature_req[SMB2_SIGNATURE_SIZE];
9036 char signature[SMB2_CMACAES_SIZE];
9037 struct kvec iov[1];
9038 size_t len;
9039
9040 hdr = smb_get_msg(work->request_buf);
9041 if (work->next_smb2_rcv_hdr_off)
9042 hdr = ksmbd_req_buf_next(work);
9043
9044 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9045 len = get_rfc1002_len(work->request_buf);
9046 else if (hdr->NextCommand)
9047 len = le32_to_cpu(hdr->NextCommand);
9048 else
9049 len = get_rfc1002_len(work->request_buf) -
9050 work->next_smb2_rcv_hdr_off;
9051
9052 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9053 signing_key = work->sess->smb3signingkey;
9054 } else {
9055 chann = lookup_chann_list(work->sess, conn);
9056 if (!chann) {
9057 return 0;
9058 }
9059 signing_key = chann->smb3signingkey;
9060 }
9061
9062 if (!signing_key) {
9063 pr_err("SMB3 signing key is not generated\n");
9064 return 0;
9065 }
9066
9067 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9068 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9069 iov[0].iov_base = (char *)&hdr->ProtocolId;
9070 iov[0].iov_len = len;
9071
9072 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
9073 return 0;
9074
9075 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9076 pr_err("bad smb2 signature\n");
9077 return 0;
9078 }
9079
9080 return 1;
9081 }
9082
9083 /**
9084 * smb3_set_sign_rsp() - handler for rsp packet sign processing
9085 * @work: smb work containing notify command buffer
9086 *
9087 */
9088 void smb3_set_sign_rsp(struct ksmbd_work *work)
9089 {
9090 struct ksmbd_conn *conn = work->conn;
9091 struct smb2_hdr *hdr;
9092 struct channel *chann;
9093 char signature[SMB2_CMACAES_SIZE];
9094 struct kvec *iov;
9095 int n_vec = 1;
9096 char *signing_key;
9097
9098 hdr = ksmbd_resp_buf_curr(work);
9099
9100 if (conn->binding == false &&
9101 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9102 signing_key = work->sess->smb3signingkey;
9103 } else {
9104 chann = lookup_chann_list(work->sess, work->conn);
9105 if (!chann) {
9106 return;
9107 }
9108 signing_key = chann->smb3signingkey;
9109 }
9110
9111 if (!signing_key)
9112 return;
9113
9114 hdr->Flags |= SMB2_FLAGS_SIGNED;
9115 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9116
9117 if (hdr->Command == SMB2_READ) {
9118 iov = &work->iov[work->iov_idx - 1];
9119 n_vec++;
9120 } else {
9121 iov = &work->iov[work->iov_idx];
9122 }
9123
9124 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
9125 signature))
9126 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9127 }
9128
9129 /**
9130 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
9131 * @work: smb work containing response buffer
9132 *
9133 */
9134 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
9135 {
9136 struct ksmbd_conn *conn = work->conn;
9137 struct ksmbd_session *sess = work->sess;
9138 struct smb2_hdr *req, *rsp;
9139
9140 if (conn->dialect != SMB311_PROT_ID)
9141 return;
9142
9143 WORK_BUFFERS(work, req, rsp);
9144
9145 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
9146 conn->preauth_info)
9147 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9148 conn->preauth_info->Preauth_HashValue);
9149
9150 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9151 __u8 *hash_value;
9152
9153 if (conn->binding) {
9154 struct preauth_session *preauth_sess;
9155
9156 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9157 if (!preauth_sess)
9158 return;
9159 hash_value = preauth_sess->Preauth_HashValue;
9160 } else {
9161 hash_value = sess->Preauth_HashValue;
9162 if (!hash_value)
9163 return;
9164 }
9165 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9166 hash_value);
9167 }
9168 }
9169
9170 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9171 {
9172 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9173 struct smb2_hdr *hdr = smb_get_msg(old_buf);
9174 unsigned int orig_len = get_rfc1002_len(old_buf);
9175
9176 /* tr_buf must be cleared by the caller */
9177 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9178 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9179 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9180 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9181 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9182 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9183 else
9184 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9185 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9186 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9187 inc_rfc1001_len(tr_buf, orig_len);
9188 }
9189
9190 int smb3_encrypt_resp(struct ksmbd_work *work)
9191 {
9192 struct kvec *iov = work->iov;
9193 int rc = -ENOMEM;
9194 void *tr_buf;
9195
9196 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9197 if (!tr_buf)
9198 return rc;
9199
9200 /* fill transform header */
9201 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9202
9203 iov[0].iov_base = tr_buf;
9204 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9205 work->tr_buf = tr_buf;
9206
9207 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9208 }
9209
9210 bool smb3_is_transform_hdr(void *buf)
9211 {
9212 struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
9213
9214 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9215 }
9216
9217 int smb3_decrypt_req(struct ksmbd_work *work)
9218 {
9219 struct ksmbd_session *sess;
9220 char *buf = work->request_buf;
9221 unsigned int pdu_length = get_rfc1002_len(buf);
9222 struct kvec iov[2];
9223 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9224 struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
9225 int rc = 0;
9226
9227 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9228 buf_data_size < sizeof(struct smb2_hdr)) {
9229 pr_err("Transform message is too small (%u)\n",
9230 pdu_length);
9231 return -ECONNABORTED;
9232 }
9233
9234 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9235 pr_err("Transform message is broken\n");
9236 return -ECONNABORTED;
9237 }
9238
9239 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9240 if (!sess) {
9241 pr_err("invalid session id(%llx) in transform header\n",
9242 le64_to_cpu(tr_hdr->SessionId));
9243 return -ECONNABORTED;
9244 }
9245 ksmbd_user_session_put(sess);
9246
9247 iov[0].iov_base = buf;
9248 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9249 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9250 iov[1].iov_len = buf_data_size;
9251 rc = ksmbd_crypt_message(work, iov, 2, 0);
9252 if (rc)
9253 return rc;
9254
9255 memmove(buf + 4, iov[1].iov_base, buf_data_size);
9256 *(__be32 *)buf = cpu_to_be32(buf_data_size);
9257
9258 return rc;
9259 }
9260
9261 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9262 {
9263 struct ksmbd_conn *conn = work->conn;
9264 struct ksmbd_session *sess = work->sess;
9265 struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
9266
9267 if (conn->dialect < SMB30_PROT_ID)
9268 return false;
9269
9270 if (work->next_smb2_rcv_hdr_off)
9271 rsp = ksmbd_resp_buf_next(work);
9272
9273 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9274 sess->user && !user_guest(sess->user) &&
9275 rsp->Status == STATUS_SUCCESS)
9276 return true;
9277 return false;
9278 }