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