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