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