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