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