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