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