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