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