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