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