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