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