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