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