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