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