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