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