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