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