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
2955 if (posix_ctxt == false) {
2956 if (strchr(name, ':')) {
2957 if (!test_share_config_flag(work->tcon->share_conf,
2958 KSMBD_SHARE_FLAG_STREAMS)) {
2959 rc = -EBADF;
2960 goto err_out2;
2961 }
2962 rc = parse_stream_name(name, &stream_name, &s_type);
2963 if (rc < 0)
2964 goto err_out2;
2965 }
2966
2967 rc = ksmbd_validate_filename(name);
2968 if (rc < 0)
2969 goto err_out2;
2970 }
2971
2972 if (ksmbd_share_veto_filename(share, name)) {
2973 rc = -ENOENT;
2974 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2975 name);
2976 goto err_out2;
2977 }
2978 } else {
2979 name = kstrdup("", KSMBD_DEFAULT_GFP);
2980 if (!name) {
2981 rc = -ENOMEM;
2982 goto err_out2;
2983 }
2984 }
2985
2986 req_op_level = req->RequestedOplockLevel;
2987
2988 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
2989 req->CreateContextsOffset) {
2990 lc = parse_lease_state(req);
2991 rc = parse_durable_handle_context(work, req, lc, &dh_info);
2992 if (rc) {
2993 ksmbd_debug(SMB, "error parsing durable handle context\n");
2994 goto err_out2;
2995 }
2996
2997 if (dh_info.reconnected == true) {
2998 rc = smb2_check_durable_oplock(conn, share, dh_info.fp, lc, name);
2999 if (rc) {
3000 ksmbd_put_durable_fd(dh_info.fp);
3001 goto err_out2;
3002 }
3003
3004 rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
3005 if (rc) {
3006 ksmbd_put_durable_fd(dh_info.fp);
3007 goto err_out2;
3008 }
3009
3010 if (ksmbd_override_fsids(work)) {
3011 rc = -ENOMEM;
3012 ksmbd_put_durable_fd(dh_info.fp);
3013 goto err_out2;
3014 }
3015
3016 fp = dh_info.fp;
3017 file_info = FILE_OPENED;
3018
3019 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3020 if (rc)
3021 goto err_out2;
3022
3023 ksmbd_put_durable_fd(fp);
3024 goto reconnected_fp;
3025 }
3026 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3027 lc = parse_lease_state(req);
3028
3029 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3030 pr_err("Invalid impersonationlevel : 0x%x\n",
3031 le32_to_cpu(req->ImpersonationLevel));
3032 rc = -EIO;
3033 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3034 goto err_out2;
3035 }
3036
3037 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3038 pr_err("Invalid create options : 0x%x\n",
3039 le32_to_cpu(req->CreateOptions));
3040 rc = -EINVAL;
3041 goto err_out2;
3042 } else {
3043 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3044 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3045 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
3046
3047 if (req->CreateOptions &
3048 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3049 FILE_RESERVE_OPFILTER_LE)) {
3050 rc = -EOPNOTSUPP;
3051 goto err_out2;
3052 }
3053
3054 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3055 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3056 rc = -EINVAL;
3057 goto err_out2;
3058 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3059 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
3060 }
3061 }
3062 }
3063
3064 if (le32_to_cpu(req->CreateDisposition) >
3065 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3066 pr_err("Invalid create disposition : 0x%x\n",
3067 le32_to_cpu(req->CreateDisposition));
3068 rc = -EINVAL;
3069 goto err_out2;
3070 }
3071
3072 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3073 pr_err("Invalid desired access : 0x%x\n",
3074 le32_to_cpu(req->DesiredAccess));
3075 rc = -EACCES;
3076 goto err_out2;
3077 }
3078
3079 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
3080 pr_err("Invalid file attribute : 0x%x\n",
3081 le32_to_cpu(req->FileAttributes));
3082 rc = -EINVAL;
3083 goto err_out2;
3084 }
3085
3086 if (req->CreateContextsOffset) {
3087 /* Parse non-durable handle create contexts */
3088 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3089 if (IS_ERR(context)) {
3090 rc = PTR_ERR(context);
3091 goto err_out2;
3092 } else if (context) {
3093 ea_buf = (struct create_ea_buf_req *)context;
3094 if (le16_to_cpu(context->DataOffset) +
3095 le32_to_cpu(context->DataLength) <
3096 sizeof(struct create_ea_buf_req)) {
3097 rc = -EINVAL;
3098 goto err_out2;
3099 }
3100 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3101 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3102 rc = -EACCES;
3103 goto err_out2;
3104 }
3105 }
3106
3107 context = smb2_find_context_vals(req,
3108 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3109 if (IS_ERR(context)) {
3110 rc = PTR_ERR(context);
3111 goto err_out2;
3112 } else if (context) {
3113 ksmbd_debug(SMB,
3114 "get query maximal access context\n");
3115 maximal_access_ctxt = 1;
3116 }
3117
3118 context = smb2_find_context_vals(req,
3119 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3120 if (IS_ERR(context)) {
3121 rc = PTR_ERR(context);
3122 goto err_out2;
3123 } else if (context) {
3124 ksmbd_debug(SMB, "get timewarp context\n");
3125 rc = -EBADF;
3126 goto err_out2;
3127 }
3128 }
3129
3130 if (ksmbd_override_fsids(work)) {
3131 rc = -ENOMEM;
3132 goto err_out2;
3133 }
3134
3135 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3136 &path, 1);
3137 if (!rc) {
3138 file_present = true;
3139
3140 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3141 /*
3142 * If file exists with under flags, return access
3143 * denied error.
3144 */
3145 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3146 req->CreateDisposition == FILE_OPEN_IF_LE) {
3147 rc = -EACCES;
3148 goto err_out;
3149 }
3150
3151 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3152 ksmbd_debug(SMB,
3153 "User does not have write permission\n");
3154 rc = -EACCES;
3155 goto err_out;
3156 }
3157 } else if (d_is_symlink(path.dentry)) {
3158 rc = -EACCES;
3159 goto err_out;
3160 }
3161
3162 idmap = mnt_idmap(path.mnt);
3163 } else {
3164 if (rc != -ENOENT)
3165 goto err_out;
3166 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3167 name, rc);
3168 rc = 0;
3169 }
3170
3171 if (stream_name) {
3172 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3173 if (s_type == DATA_STREAM) {
3174 rc = -EIO;
3175 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3176 }
3177 } else {
3178 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3179 s_type == DATA_STREAM) {
3180 rc = -EIO;
3181 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3182 }
3183 }
3184
3185 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3186 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3187 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3188 rc = -EIO;
3189 }
3190
3191 if (rc < 0)
3192 goto err_out;
3193 }
3194
3195 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3196 S_ISDIR(d_inode(path.dentry)->i_mode) &&
3197 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3198 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3199 name, req->CreateOptions);
3200 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3201 rc = -EIO;
3202 goto err_out;
3203 }
3204
3205 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3206 !(req->CreateDisposition == FILE_CREATE_LE) &&
3207 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3208 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3209 rc = -EIO;
3210 goto err_out;
3211 }
3212
3213 if (!stream_name && file_present &&
3214 req->CreateDisposition == FILE_CREATE_LE) {
3215 rc = -EEXIST;
3216 goto err_out;
3217 }
3218
3219 daccess = smb_map_generic_desired_access(req->DesiredAccess);
3220
3221 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3222 rc = smb_check_perm_dacl(conn, &path, &daccess,
3223 sess->user->uid);
3224 if (rc)
3225 goto err_out;
3226 }
3227
3228 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3229 if (!file_present) {
3230 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3231 } else {
3232 ksmbd_vfs_query_maximal_access(idmap,
3233 path.dentry,
3234 &daccess);
3235 already_permitted = true;
3236 }
3237 maximal_access = daccess;
3238 }
3239
3240 open_flags = smb2_create_open_flags(file_present, daccess,
3241 req->CreateDisposition,
3242 &may_flags,
3243 req->CreateOptions,
3244 file_present ? d_inode(path.dentry)->i_mode : 0);
3245
3246 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3247 if (open_flags & (O_CREAT | O_TRUNC)) {
3248 ksmbd_debug(SMB,
3249 "User does not have write permission\n");
3250 rc = -EACCES;
3251 goto err_out;
3252 }
3253 }
3254
3255 /*create file if not present */
3256 if (!file_present) {
3257 rc = smb2_creat(work, &path, name, open_flags,
3258 posix_mode,
3259 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3260 if (rc) {
3261 if (rc == -ENOENT) {
3262 rc = -EIO;
3263 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3264 }
3265 goto err_out;
3266 }
3267
3268 created = true;
3269 idmap = mnt_idmap(path.mnt);
3270 if (ea_buf) {
3271 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3272 sizeof(struct smb2_ea_info)) {
3273 rc = -EINVAL;
3274 goto err_out;
3275 }
3276
3277 rc = smb2_set_ea(&ea_buf->ea,
3278 le32_to_cpu(ea_buf->ccontext.DataLength),
3279 &path, false);
3280 if (rc == -EOPNOTSUPP)
3281 rc = 0;
3282 else if (rc)
3283 goto err_out;
3284 }
3285 } else if (!already_permitted) {
3286 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3287 * because execute(search) permission on a parent directory,
3288 * is already granted.
3289 */
3290 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3291 rc = inode_permission(idmap,
3292 d_inode(path.dentry),
3293 may_flags);
3294 if (rc)
3295 goto err_out;
3296
3297 if ((daccess & FILE_DELETE_LE) ||
3298 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3299 rc = inode_permission(idmap,
3300 d_inode(path.dentry->d_parent),
3301 MAY_EXEC | MAY_WRITE);
3302 if (rc)
3303 goto err_out;
3304 }
3305 }
3306 }
3307
3308 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3309 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3310 rc = -EBUSY;
3311 goto err_out;
3312 }
3313
3314 rc = 0;
3315 filp = dentry_open(&path, open_flags, current_cred());
3316 if (IS_ERR(filp)) {
3317 rc = PTR_ERR(filp);
3318 pr_err("dentry open for dir failed, rc %d\n", rc);
3319 goto err_out;
3320 }
3321
3322 if (file_present) {
3323 if (!(open_flags & O_TRUNC))
3324 file_info = FILE_OPENED;
3325 else
3326 file_info = FILE_OVERWRITTEN;
3327
3328 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3329 FILE_SUPERSEDE_LE)
3330 file_info = FILE_SUPERSEDED;
3331 } else if (open_flags & O_CREAT) {
3332 file_info = FILE_CREATED;
3333 }
3334
3335 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3336
3337 /* Obtain Volatile-ID */
3338 fp = ksmbd_open_fd(work, filp);
3339 if (IS_ERR(fp)) {
3340 fput(filp);
3341 rc = PTR_ERR(fp);
3342 fp = NULL;
3343 goto err_out;
3344 }
3345
3346 /* Get Persistent-ID */
3347 ksmbd_open_durable_fd(fp);
3348 if (!has_file_id(fp->persistent_id)) {
3349 rc = -ENOMEM;
3350 goto err_out;
3351 }
3352
3353 fp->cdoption = req->CreateDisposition;
3354 fp->daccess = daccess;
3355 fp->saccess = req->ShareAccess;
3356 fp->coption = req->CreateOptions;
3357
3358 /* Set default windows and posix acls if creating new file */
3359 if (created) {
3360 int posix_acl_rc;
3361 struct inode *inode = d_inode(path.dentry);
3362
3363 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3364 &path,
3365 d_inode(path.dentry->d_parent));
3366 if (posix_acl_rc)
3367 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3368
3369 if (test_share_config_flag(work->tcon->share_conf,
3370 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3371 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3372 sess->user->gid);
3373 }
3374
3375 if (rc) {
3376 rc = smb2_create_sd_buffer(work, req, &path);
3377 if (rc) {
3378 if (posix_acl_rc)
3379 ksmbd_vfs_set_init_posix_acl(idmap,
3380 &path);
3381
3382 if (test_share_config_flag(work->tcon->share_conf,
3383 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3384 struct smb_fattr fattr;
3385 struct smb_ntsd *pntsd;
3386 int pntsd_size, ace_num = 0;
3387
3388 ksmbd_acls_fattr(&fattr, idmap, inode);
3389 if (fattr.cf_acls)
3390 ace_num = fattr.cf_acls->a_count;
3391 if (fattr.cf_dacls)
3392 ace_num += fattr.cf_dacls->a_count;
3393
3394 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3395 sizeof(struct smb_sid) * 3 +
3396 sizeof(struct smb_acl) +
3397 sizeof(struct smb_ace) * ace_num * 2,
3398 KSMBD_DEFAULT_GFP);
3399 if (!pntsd) {
3400 posix_acl_release(fattr.cf_acls);
3401 posix_acl_release(fattr.cf_dacls);
3402 goto err_out;
3403 }
3404
3405 rc = build_sec_desc(idmap,
3406 pntsd, NULL, 0,
3407 OWNER_SECINFO |
3408 GROUP_SECINFO |
3409 DACL_SECINFO,
3410 &pntsd_size, &fattr);
3411 posix_acl_release(fattr.cf_acls);
3412 posix_acl_release(fattr.cf_dacls);
3413 if (rc) {
3414 kfree(pntsd);
3415 goto err_out;
3416 }
3417
3418 rc = ksmbd_vfs_set_sd_xattr(conn,
3419 idmap,
3420 &path,
3421 pntsd,
3422 pntsd_size,
3423 false);
3424 kfree(pntsd);
3425 if (rc)
3426 pr_err("failed to store ntacl in xattr : %d\n",
3427 rc);
3428 }
3429 }
3430 }
3431 rc = 0;
3432 }
3433
3434 if (stream_name) {
3435 rc = smb2_set_stream_name_xattr(&path,
3436 fp,
3437 stream_name,
3438 s_type);
3439 if (rc)
3440 goto err_out;
3441 file_info = FILE_CREATED;
3442 }
3443
3444 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3445 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3446
3447 fp->is_posix_ctxt = posix_ctxt;
3448
3449 /* fp should be searchable through ksmbd_inode.m_fp_list
3450 * after daccess, saccess, attrib_only, and stream are
3451 * initialized.
3452 */
3453 down_write(&fp->f_ci->m_lock);
3454 list_add(&fp->node, &fp->f_ci->m_fp_list);
3455 up_write(&fp->f_ci->m_lock);
3456
3457 /* Check delete pending among previous fp before oplock break */
3458 if (ksmbd_inode_pending_delete(fp)) {
3459 rc = -EBUSY;
3460 goto err_out;
3461 }
3462
3463 if (file_present || created)
3464 path_put(&path);
3465
3466 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3467 !fp->attrib_only && !stream_name) {
3468 smb_break_all_oplock(work, fp);
3469 need_truncate = 1;
3470 }
3471
3472 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3473 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3474 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3475 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3476 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3477 rc = share_ret;
3478 goto err_out1;
3479 }
3480 } else {
3481 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3482 if (S_ISDIR(file_inode(filp)->i_mode)) {
3483 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3484 lc->is_dir = true;
3485 }
3486
3487 /*
3488 * Compare parent lease using parent key. If there is no
3489 * a lease that has same parent key, Send lease break
3490 * notification.
3491 */
3492 smb_send_parent_lease_break_noti(fp, lc);
3493
3494 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3495 ksmbd_debug(SMB,
3496 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3497 name, req_op_level, lc->req_state);
3498 rc = find_same_lease_key(sess, fp->f_ci, lc);
3499 if (rc)
3500 goto err_out1;
3501 } else if (open_flags == O_RDONLY &&
3502 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3503 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3504 req_op_level = SMB2_OPLOCK_LEVEL_II;
3505
3506 rc = smb_grant_oplock(work, req_op_level,
3507 fp->persistent_id, fp,
3508 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3509 lc, share_ret);
3510 if (rc < 0)
3511 goto err_out1;
3512 }
3513
3514 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3515 ksmbd_fd_set_delete_on_close(fp, file_info);
3516
3517 if (need_truncate) {
3518 rc = smb2_create_truncate(&fp->filp->f_path);
3519 if (rc)
3520 goto err_out1;
3521 }
3522
3523 if (req->CreateContextsOffset) {
3524 struct create_alloc_size_req *az_req;
3525
3526 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3527 SMB2_CREATE_ALLOCATION_SIZE, 4);
3528 if (IS_ERR(az_req)) {
3529 rc = PTR_ERR(az_req);
3530 goto err_out1;
3531 } else if (az_req) {
3532 loff_t alloc_size;
3533 int err;
3534
3535 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3536 le32_to_cpu(az_req->ccontext.DataLength) <
3537 sizeof(struct create_alloc_size_req)) {
3538 rc = -EINVAL;
3539 goto err_out1;
3540 }
3541 alloc_size = le64_to_cpu(az_req->AllocationSize);
3542 ksmbd_debug(SMB,
3543 "request smb2 create allocate size : %llu\n",
3544 alloc_size);
3545 smb_break_all_levII_oplock(work, fp, 1);
3546 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3547 alloc_size);
3548 if (err < 0)
3549 ksmbd_debug(SMB,
3550 "vfs_fallocate is failed : %d\n",
3551 err);
3552 }
3553
3554 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3555 if (IS_ERR(context)) {
3556 rc = PTR_ERR(context);
3557 goto err_out1;
3558 } else if (context) {
3559 ksmbd_debug(SMB, "get query on disk id context\n");
3560 query_disk_id = 1;
3561 }
3562
3563 if (conn->is_aapl == false) {
3564 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3565 if (IS_ERR(context)) {
3566 rc = PTR_ERR(context);
3567 goto err_out1;
3568 } else if (context)
3569 conn->is_aapl = true;
3570 }
3571 }
3572
3573 rc = ksmbd_vfs_getattr(&path, &stat);
3574 if (rc)
3575 goto err_out1;
3576
3577 if (stat.result_mask & STATX_BTIME)
3578 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3579 else
3580 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3581 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3582 fp->f_ci->m_fattr =
3583 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3584
3585 if (!created)
3586 smb2_update_xattrs(tcon, &path, fp);
3587 else
3588 smb2_new_xattrs(tcon, &path, fp);
3589
3590 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3591
3592 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3593 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3594 test_share_config_flag(work->tcon->share_conf,
3595 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3596 fp->is_persistent = true;
3597 else
3598 fp->is_durable = true;
3599
3600 if (dh_info.type == DURABLE_REQ_V2) {
3601 memcpy(fp->create_guid, dh_info.CreateGuid,
3602 SMB2_CREATE_GUID_SIZE);
3603 if (dh_info.timeout)
3604 fp->durable_timeout =
3605 min_t(unsigned int, dh_info.timeout,
3606 DURABLE_HANDLE_MAX_TIMEOUT);
3607 else
3608 fp->durable_timeout = 60;
3609 }
3610 }
3611
3612 reconnected_fp:
3613 rsp->StructureSize = cpu_to_le16(89);
3614 rcu_read_lock();
3615 opinfo = rcu_dereference(fp->f_opinfo);
3616 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3617 rcu_read_unlock();
3618 rsp->Flags = 0;
3619 rsp->CreateAction = cpu_to_le32(file_info);
3620 rsp->CreationTime = cpu_to_le64(fp->create_time);
3621 time = ksmbd_UnixTimeToNT(stat.atime);
3622 rsp->LastAccessTime = cpu_to_le64(time);
3623 time = ksmbd_UnixTimeToNT(stat.mtime);
3624 rsp->LastWriteTime = cpu_to_le64(time);
3625 time = ksmbd_UnixTimeToNT(stat.ctime);
3626 rsp->ChangeTime = cpu_to_le64(time);
3627 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3628 cpu_to_le64(stat.blocks << 9);
3629 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3630 rsp->FileAttributes = fp->f_ci->m_fattr;
3631
3632 rsp->Reserved2 = 0;
3633
3634 rsp->PersistentFileId = fp->persistent_id;
3635 rsp->VolatileFileId = fp->volatile_id;
3636
3637 rsp->CreateContextsOffset = 0;
3638 rsp->CreateContextsLength = 0;
3639 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3640
3641 /* If lease is request send lease context response */
3642 if (opinfo && opinfo->is_lease) {
3643 struct create_context *lease_ccontext;
3644
3645 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3646 name, opinfo->o_lease->state);
3647 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3648
3649 lease_ccontext = (struct create_context *)rsp->Buffer;
3650 contxt_cnt++;
3651 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3652 le32_add_cpu(&rsp->CreateContextsLength,
3653 conn->vals->create_lease_size);
3654 iov_len += conn->vals->create_lease_size;
3655 next_ptr = &lease_ccontext->Next;
3656 next_off = conn->vals->create_lease_size;
3657 }
3658
3659 if (maximal_access_ctxt) {
3660 struct create_context *mxac_ccontext;
3661
3662 if (maximal_access == 0)
3663 ksmbd_vfs_query_maximal_access(idmap,
3664 path.dentry,
3665 &maximal_access);
3666 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3667 le32_to_cpu(rsp->CreateContextsLength));
3668 contxt_cnt++;
3669 create_mxac_rsp_buf(rsp->Buffer +
3670 le32_to_cpu(rsp->CreateContextsLength),
3671 le32_to_cpu(maximal_access));
3672 le32_add_cpu(&rsp->CreateContextsLength,
3673 conn->vals->create_mxac_size);
3674 iov_len += conn->vals->create_mxac_size;
3675 if (next_ptr)
3676 *next_ptr = cpu_to_le32(next_off);
3677 next_ptr = &mxac_ccontext->Next;
3678 next_off = conn->vals->create_mxac_size;
3679 }
3680
3681 if (query_disk_id) {
3682 struct create_context *disk_id_ccontext;
3683
3684 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3685 le32_to_cpu(rsp->CreateContextsLength));
3686 contxt_cnt++;
3687 create_disk_id_rsp_buf(rsp->Buffer +
3688 le32_to_cpu(rsp->CreateContextsLength),
3689 stat.ino, tcon->id);
3690 le32_add_cpu(&rsp->CreateContextsLength,
3691 conn->vals->create_disk_id_size);
3692 iov_len += conn->vals->create_disk_id_size;
3693 if (next_ptr)
3694 *next_ptr = cpu_to_le32(next_off);
3695 next_ptr = &disk_id_ccontext->Next;
3696 next_off = conn->vals->create_disk_id_size;
3697 }
3698
3699 if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3700 struct create_context *durable_ccontext;
3701
3702 durable_ccontext = (struct create_context *)(rsp->Buffer +
3703 le32_to_cpu(rsp->CreateContextsLength));
3704 contxt_cnt++;
3705 if (dh_info.type == DURABLE_REQ) {
3706 create_durable_rsp_buf(rsp->Buffer +
3707 le32_to_cpu(rsp->CreateContextsLength));
3708 le32_add_cpu(&rsp->CreateContextsLength,
3709 conn->vals->create_durable_size);
3710 iov_len += conn->vals->create_durable_size;
3711 } else {
3712 create_durable_v2_rsp_buf(rsp->Buffer +
3713 le32_to_cpu(rsp->CreateContextsLength),
3714 fp);
3715 le32_add_cpu(&rsp->CreateContextsLength,
3716 conn->vals->create_durable_v2_size);
3717 iov_len += conn->vals->create_durable_v2_size;
3718 }
3719
3720 if (next_ptr)
3721 *next_ptr = cpu_to_le32(next_off);
3722 next_ptr = &durable_ccontext->Next;
3723 next_off = conn->vals->create_durable_size;
3724 }
3725
3726 if (posix_ctxt) {
3727 contxt_cnt++;
3728 create_posix_rsp_buf(rsp->Buffer +
3729 le32_to_cpu(rsp->CreateContextsLength),
3730 fp);
3731 le32_add_cpu(&rsp->CreateContextsLength,
3732 conn->vals->create_posix_size);
3733 iov_len += conn->vals->create_posix_size;
3734 if (next_ptr)
3735 *next_ptr = cpu_to_le32(next_off);
3736 }
3737
3738 if (contxt_cnt > 0) {
3739 rsp->CreateContextsOffset =
3740 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3741 }
3742
3743 err_out:
3744 if (rc && (file_present || created))
3745 path_put(&path);
3746
3747 err_out1:
3748 ksmbd_revert_fsids(work);
3749
3750 err_out2:
3751 if (!rc) {
3752 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3753 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3754 }
3755 if (rc) {
3756 if (rc == -EINVAL)
3757 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3758 else if (rc == -EOPNOTSUPP)
3759 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3760 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3761 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3762 else if (rc == -ENOENT)
3763 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3764 else if (rc == -EPERM)
3765 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3766 else if (rc == -EBUSY)
3767 rsp->hdr.Status = STATUS_DELETE_PENDING;
3768 else if (rc == -EBADF)
3769 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3770 else if (rc == -ENOEXEC)
3771 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3772 else if (rc == -ENXIO)
3773 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3774 else if (rc == -EEXIST)
3775 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3776 else if (rc == -EMFILE)
3777 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3778 if (!rsp->hdr.Status)
3779 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3780
3781 if (fp)
3782 ksmbd_fd_put(work, fp);
3783 smb2_set_err_rsp(work);
3784 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3785 }
3786
3787 kfree(name);
3788 kfree(lc);
3789
3790 return rc;
3791 }
3792
readdir_info_level_struct_sz(int info_level)3793 static int readdir_info_level_struct_sz(int info_level)
3794 {
3795 switch (info_level) {
3796 case FILE_FULL_DIRECTORY_INFORMATION:
3797 return sizeof(struct file_full_directory_info);
3798 case FILE_BOTH_DIRECTORY_INFORMATION:
3799 return sizeof(struct file_both_directory_info);
3800 case FILE_DIRECTORY_INFORMATION:
3801 return sizeof(struct file_directory_info);
3802 case FILE_NAMES_INFORMATION:
3803 return sizeof(struct file_names_info);
3804 case FILEID_FULL_DIRECTORY_INFORMATION:
3805 return sizeof(struct file_id_full_dir_info);
3806 case FILEID_BOTH_DIRECTORY_INFORMATION:
3807 return sizeof(struct file_id_both_directory_info);
3808 case SMB_FIND_FILE_POSIX_INFO:
3809 return sizeof(struct smb2_posix_info);
3810 default:
3811 return -EOPNOTSUPP;
3812 }
3813 }
3814
dentry_name(struct ksmbd_dir_info * d_info,int info_level)3815 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3816 {
3817 switch (info_level) {
3818 case FILE_FULL_DIRECTORY_INFORMATION:
3819 {
3820 struct file_full_directory_info *ffdinfo;
3821
3822 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3823 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3824 d_info->name = ffdinfo->FileName;
3825 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3826 return 0;
3827 }
3828 case FILE_BOTH_DIRECTORY_INFORMATION:
3829 {
3830 struct file_both_directory_info *fbdinfo;
3831
3832 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3833 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3834 d_info->name = fbdinfo->FileName;
3835 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3836 return 0;
3837 }
3838 case FILE_DIRECTORY_INFORMATION:
3839 {
3840 struct file_directory_info *fdinfo;
3841
3842 fdinfo = (struct file_directory_info *)d_info->rptr;
3843 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3844 d_info->name = fdinfo->FileName;
3845 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3846 return 0;
3847 }
3848 case FILE_NAMES_INFORMATION:
3849 {
3850 struct file_names_info *fninfo;
3851
3852 fninfo = (struct file_names_info *)d_info->rptr;
3853 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3854 d_info->name = fninfo->FileName;
3855 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3856 return 0;
3857 }
3858 case FILEID_FULL_DIRECTORY_INFORMATION:
3859 {
3860 struct file_id_full_dir_info *dinfo;
3861
3862 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3863 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3864 d_info->name = dinfo->FileName;
3865 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3866 return 0;
3867 }
3868 case FILEID_BOTH_DIRECTORY_INFORMATION:
3869 {
3870 struct file_id_both_directory_info *fibdinfo;
3871
3872 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3873 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3874 d_info->name = fibdinfo->FileName;
3875 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3876 return 0;
3877 }
3878 case SMB_FIND_FILE_POSIX_INFO:
3879 {
3880 struct smb2_posix_info *posix_info;
3881
3882 posix_info = (struct smb2_posix_info *)d_info->rptr;
3883 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3884 d_info->name = posix_info->name;
3885 d_info->name_len = le32_to_cpu(posix_info->name_len);
3886 return 0;
3887 }
3888 default:
3889 return -EINVAL;
3890 }
3891 }
3892
3893 /**
3894 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3895 * buffer
3896 * @conn: connection instance
3897 * @info_level: smb information level
3898 * @d_info: structure included variables for query dir
3899 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3900 *
3901 * if directory has many entries, find first can't read it fully.
3902 * find next might be called multiple times to read remaining dir entries
3903 *
3904 * Return: 0 on success, otherwise error
3905 */
smb2_populate_readdir_entry(struct ksmbd_conn * conn,int info_level,struct ksmbd_dir_info * d_info,struct ksmbd_kstat * ksmbd_kstat)3906 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3907 struct ksmbd_dir_info *d_info,
3908 struct ksmbd_kstat *ksmbd_kstat)
3909 {
3910 int next_entry_offset = 0;
3911 char *conv_name;
3912 int conv_len;
3913 void *kstat;
3914 int struct_sz, rc = 0;
3915
3916 conv_name = ksmbd_convert_dir_info_name(d_info,
3917 conn->local_nls,
3918 &conv_len);
3919 if (!conv_name)
3920 return -ENOMEM;
3921
3922 /* Somehow the name has only terminating NULL bytes */
3923 if (conv_len < 0) {
3924 rc = -EINVAL;
3925 goto free_conv_name;
3926 }
3927
3928 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3929 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3930 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3931
3932 if (next_entry_offset > d_info->out_buf_len) {
3933 d_info->out_buf_len = 0;
3934 rc = -ENOSPC;
3935 goto free_conv_name;
3936 }
3937
3938 kstat = d_info->wptr;
3939 if (info_level != FILE_NAMES_INFORMATION)
3940 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3941
3942 switch (info_level) {
3943 case FILE_FULL_DIRECTORY_INFORMATION:
3944 {
3945 struct file_full_directory_info *ffdinfo;
3946
3947 ffdinfo = (struct file_full_directory_info *)kstat;
3948 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3949 ffdinfo->EaSize =
3950 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3951 if (ffdinfo->EaSize)
3952 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3953 if (d_info->hide_dot_file && d_info->name[0] == '.')
3954 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3955 memcpy(ffdinfo->FileName, conv_name, conv_len);
3956 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3957 break;
3958 }
3959 case FILE_BOTH_DIRECTORY_INFORMATION:
3960 {
3961 struct file_both_directory_info *fbdinfo;
3962
3963 fbdinfo = (struct file_both_directory_info *)kstat;
3964 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3965 fbdinfo->EaSize =
3966 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3967 if (fbdinfo->EaSize)
3968 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3969 fbdinfo->ShortNameLength = 0;
3970 fbdinfo->Reserved = 0;
3971 if (d_info->hide_dot_file && d_info->name[0] == '.')
3972 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3973 memcpy(fbdinfo->FileName, conv_name, conv_len);
3974 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3975 break;
3976 }
3977 case FILE_DIRECTORY_INFORMATION:
3978 {
3979 struct file_directory_info *fdinfo;
3980
3981 fdinfo = (struct file_directory_info *)kstat;
3982 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3983 if (d_info->hide_dot_file && d_info->name[0] == '.')
3984 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3985 memcpy(fdinfo->FileName, conv_name, conv_len);
3986 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3987 break;
3988 }
3989 case FILE_NAMES_INFORMATION:
3990 {
3991 struct file_names_info *fninfo;
3992
3993 fninfo = (struct file_names_info *)kstat;
3994 fninfo->FileNameLength = cpu_to_le32(conv_len);
3995 memcpy(fninfo->FileName, conv_name, conv_len);
3996 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3997 break;
3998 }
3999 case FILEID_FULL_DIRECTORY_INFORMATION:
4000 {
4001 struct file_id_full_dir_info *dinfo;
4002
4003 dinfo = (struct file_id_full_dir_info *)kstat;
4004 dinfo->FileNameLength = cpu_to_le32(conv_len);
4005 dinfo->EaSize =
4006 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4007 if (dinfo->EaSize)
4008 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4009 dinfo->Reserved = 0;
4010 if (conn->is_aapl)
4011 dinfo->UniqueId = 0;
4012 else
4013 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4014 if (d_info->hide_dot_file && d_info->name[0] == '.')
4015 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4016 memcpy(dinfo->FileName, conv_name, conv_len);
4017 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4018 break;
4019 }
4020 case FILEID_BOTH_DIRECTORY_INFORMATION:
4021 {
4022 struct file_id_both_directory_info *fibdinfo;
4023
4024 fibdinfo = (struct file_id_both_directory_info *)kstat;
4025 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4026 fibdinfo->EaSize =
4027 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4028 if (fibdinfo->EaSize)
4029 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4030 if (conn->is_aapl)
4031 fibdinfo->UniqueId = 0;
4032 else
4033 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4034 fibdinfo->ShortNameLength = 0;
4035 fibdinfo->Reserved = 0;
4036 fibdinfo->Reserved2 = cpu_to_le16(0);
4037 if (d_info->hide_dot_file && d_info->name[0] == '.')
4038 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4039 memcpy(fibdinfo->FileName, conv_name, conv_len);
4040 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4041 break;
4042 }
4043 case SMB_FIND_FILE_POSIX_INFO:
4044 {
4045 struct smb2_posix_info *posix_info;
4046 u64 time;
4047
4048 posix_info = (struct smb2_posix_info *)kstat;
4049 posix_info->Ignored = 0;
4050 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4051 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4052 posix_info->ChangeTime = cpu_to_le64(time);
4053 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4054 posix_info->LastAccessTime = cpu_to_le64(time);
4055 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4056 posix_info->LastWriteTime = cpu_to_le64(time);
4057 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4058 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4059 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4060 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4061 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4062 switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4063 case S_IFDIR:
4064 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4065 break;
4066 case S_IFLNK:
4067 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4068 break;
4069 case S_IFCHR:
4070 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4071 break;
4072 case S_IFBLK:
4073 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4074 break;
4075 case S_IFIFO:
4076 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4077 break;
4078 case S_IFSOCK:
4079 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4080 }
4081
4082 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4083 posix_info->DosAttributes =
4084 S_ISDIR(ksmbd_kstat->kstat->mode) ?
4085 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4086 if (d_info->hide_dot_file && d_info->name[0] == '.')
4087 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4088 /*
4089 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4090 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4091 * sub_auth(4 * 1(num_subauth)) + RID(4).
4092 */
4093 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4094 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4095 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4096 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4097 memcpy(posix_info->name, conv_name, conv_len);
4098 posix_info->name_len = cpu_to_le32(conv_len);
4099 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4100 break;
4101 }
4102
4103 } /* switch (info_level) */
4104
4105 d_info->last_entry_offset = d_info->data_count;
4106 d_info->data_count += next_entry_offset;
4107 d_info->out_buf_len -= next_entry_offset;
4108 d_info->wptr += next_entry_offset;
4109
4110 ksmbd_debug(SMB,
4111 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4112 info_level, d_info->out_buf_len,
4113 next_entry_offset, d_info->data_count);
4114
4115 free_conv_name:
4116 kfree(conv_name);
4117 return rc;
4118 }
4119
4120 struct smb2_query_dir_private {
4121 struct ksmbd_work *work;
4122 char *search_pattern;
4123 struct ksmbd_file *dir_fp;
4124
4125 struct ksmbd_dir_info *d_info;
4126 int info_level;
4127 };
4128
process_query_dir_entries(struct smb2_query_dir_private * priv)4129 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4130 {
4131 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
4132 struct kstat kstat;
4133 struct ksmbd_kstat ksmbd_kstat;
4134 int rc;
4135 int i;
4136
4137 for (i = 0; i < priv->d_info->num_entry; i++) {
4138 struct dentry *dent;
4139
4140 if (dentry_name(priv->d_info, priv->info_level))
4141 return -EINVAL;
4142
4143 dent = lookup_one_unlocked(idmap,
4144 &QSTR_LEN(priv->d_info->name,
4145 priv->d_info->name_len),
4146 priv->dir_fp->filp->f_path.dentry);
4147
4148 if (IS_ERR(dent)) {
4149 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4150 priv->d_info->name,
4151 PTR_ERR(dent));
4152 continue;
4153 }
4154 if (unlikely(d_is_negative(dent))) {
4155 dput(dent);
4156 ksmbd_debug(SMB, "Negative dentry `%s'\n",
4157 priv->d_info->name);
4158 continue;
4159 }
4160
4161 ksmbd_kstat.kstat = &kstat;
4162 if (priv->info_level != FILE_NAMES_INFORMATION) {
4163 rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4164 idmap,
4165 dent,
4166 &ksmbd_kstat);
4167 if (rc) {
4168 dput(dent);
4169 continue;
4170 }
4171 }
4172
4173 rc = smb2_populate_readdir_entry(priv->work->conn,
4174 priv->info_level,
4175 priv->d_info,
4176 &ksmbd_kstat);
4177 dput(dent);
4178 if (rc)
4179 return rc;
4180 }
4181 return 0;
4182 }
4183
reserve_populate_dentry(struct ksmbd_dir_info * d_info,int info_level)4184 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4185 int info_level)
4186 {
4187 int struct_sz;
4188 int conv_len;
4189 int next_entry_offset;
4190
4191 struct_sz = readdir_info_level_struct_sz(info_level);
4192 if (struct_sz == -EOPNOTSUPP)
4193 return -EOPNOTSUPP;
4194
4195 conv_len = (d_info->name_len + 1) * 2;
4196 next_entry_offset = ALIGN(struct_sz + conv_len,
4197 KSMBD_DIR_INFO_ALIGNMENT);
4198
4199 if (next_entry_offset > d_info->out_buf_len) {
4200 d_info->out_buf_len = 0;
4201 return -ENOSPC;
4202 }
4203
4204 switch (info_level) {
4205 case FILE_FULL_DIRECTORY_INFORMATION:
4206 {
4207 struct file_full_directory_info *ffdinfo;
4208
4209 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
4210 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4211 ffdinfo->FileName[d_info->name_len] = 0x00;
4212 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4213 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4214 break;
4215 }
4216 case FILE_BOTH_DIRECTORY_INFORMATION:
4217 {
4218 struct file_both_directory_info *fbdinfo;
4219
4220 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
4221 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4222 fbdinfo->FileName[d_info->name_len] = 0x00;
4223 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4224 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4225 break;
4226 }
4227 case FILE_DIRECTORY_INFORMATION:
4228 {
4229 struct file_directory_info *fdinfo;
4230
4231 fdinfo = (struct file_directory_info *)d_info->wptr;
4232 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4233 fdinfo->FileName[d_info->name_len] = 0x00;
4234 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4235 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4236 break;
4237 }
4238 case FILE_NAMES_INFORMATION:
4239 {
4240 struct file_names_info *fninfo;
4241
4242 fninfo = (struct file_names_info *)d_info->wptr;
4243 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4244 fninfo->FileName[d_info->name_len] = 0x00;
4245 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4246 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4247 break;
4248 }
4249 case FILEID_FULL_DIRECTORY_INFORMATION:
4250 {
4251 struct file_id_full_dir_info *dinfo;
4252
4253 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
4254 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4255 dinfo->FileName[d_info->name_len] = 0x00;
4256 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4257 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4258 break;
4259 }
4260 case FILEID_BOTH_DIRECTORY_INFORMATION:
4261 {
4262 struct file_id_both_directory_info *fibdinfo;
4263
4264 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4265 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4266 fibdinfo->FileName[d_info->name_len] = 0x00;
4267 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4268 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4269 break;
4270 }
4271 case SMB_FIND_FILE_POSIX_INFO:
4272 {
4273 struct smb2_posix_info *posix_info;
4274
4275 posix_info = (struct smb2_posix_info *)d_info->wptr;
4276 memcpy(posix_info->name, d_info->name, d_info->name_len);
4277 posix_info->name[d_info->name_len] = 0x00;
4278 posix_info->name_len = cpu_to_le32(d_info->name_len);
4279 posix_info->NextEntryOffset =
4280 cpu_to_le32(next_entry_offset);
4281 break;
4282 }
4283 } /* switch (info_level) */
4284
4285 d_info->num_entry++;
4286 d_info->out_buf_len -= next_entry_offset;
4287 d_info->wptr += next_entry_offset;
4288 return 0;
4289 }
4290
__query_dir(struct dir_context * ctx,const char * name,int namlen,loff_t offset,u64 ino,unsigned int d_type)4291 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4292 loff_t offset, u64 ino, unsigned int d_type)
4293 {
4294 struct ksmbd_readdir_data *buf;
4295 struct smb2_query_dir_private *priv;
4296 struct ksmbd_dir_info *d_info;
4297 int rc;
4298
4299 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
4300 priv = buf->private;
4301 d_info = priv->d_info;
4302
4303 /* dot and dotdot entries are already reserved */
4304 if (!strcmp(".", name) || !strcmp("..", name))
4305 return true;
4306 d_info->num_scan++;
4307 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4308 return true;
4309 if (!match_pattern(name, namlen, priv->search_pattern))
4310 return true;
4311
4312 d_info->name = name;
4313 d_info->name_len = namlen;
4314 rc = reserve_populate_dentry(d_info, priv->info_level);
4315 if (rc)
4316 return false;
4317 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4318 d_info->out_buf_len = 0;
4319 return true;
4320 }
4321
verify_info_level(int info_level)4322 static int verify_info_level(int info_level)
4323 {
4324 switch (info_level) {
4325 case FILE_FULL_DIRECTORY_INFORMATION:
4326 case FILE_BOTH_DIRECTORY_INFORMATION:
4327 case FILE_DIRECTORY_INFORMATION:
4328 case FILE_NAMES_INFORMATION:
4329 case FILEID_FULL_DIRECTORY_INFORMATION:
4330 case FILEID_BOTH_DIRECTORY_INFORMATION:
4331 case SMB_FIND_FILE_POSIX_INFO:
4332 break;
4333 default:
4334 return -EOPNOTSUPP;
4335 }
4336
4337 return 0;
4338 }
4339
smb2_resp_buf_len(struct ksmbd_work * work,unsigned short hdr2_len)4340 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4341 {
4342 int free_len;
4343
4344 free_len = (int)(work->response_sz -
4345 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4346 return free_len;
4347 }
4348
smb2_calc_max_out_buf_len(struct ksmbd_work * work,unsigned short hdr2_len,unsigned int out_buf_len)4349 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4350 unsigned short hdr2_len,
4351 unsigned int out_buf_len)
4352 {
4353 int free_len;
4354
4355 if (out_buf_len > work->conn->vals->max_trans_size)
4356 return -EINVAL;
4357
4358 free_len = smb2_resp_buf_len(work, hdr2_len);
4359 if (free_len < 0)
4360 return -EINVAL;
4361
4362 return min_t(int, out_buf_len, free_len);
4363 }
4364
smb2_query_dir(struct ksmbd_work * work)4365 int smb2_query_dir(struct ksmbd_work *work)
4366 {
4367 struct ksmbd_conn *conn = work->conn;
4368 struct smb2_query_directory_req *req;
4369 struct smb2_query_directory_rsp *rsp;
4370 struct ksmbd_share_config *share = work->tcon->share_conf;
4371 struct ksmbd_file *dir_fp = NULL;
4372 struct ksmbd_dir_info d_info;
4373 int rc = 0;
4374 char *srch_ptr = NULL;
4375 unsigned char srch_flag;
4376 int buffer_sz;
4377 struct smb2_query_dir_private query_dir_private = {NULL, };
4378
4379 ksmbd_debug(SMB, "Received smb2 query directory request\n");
4380
4381 WORK_BUFFERS(work, req, rsp);
4382
4383 if (ksmbd_override_fsids(work)) {
4384 rsp->hdr.Status = STATUS_NO_MEMORY;
4385 smb2_set_err_rsp(work);
4386 return -ENOMEM;
4387 }
4388
4389 rc = verify_info_level(req->FileInformationClass);
4390 if (rc) {
4391 rc = -EFAULT;
4392 goto err_out2;
4393 }
4394
4395 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4396 if (!dir_fp) {
4397 rc = -EBADF;
4398 goto err_out2;
4399 }
4400
4401 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4402 inode_permission(file_mnt_idmap(dir_fp->filp),
4403 file_inode(dir_fp->filp),
4404 MAY_READ | MAY_EXEC)) {
4405 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4406 rc = -EACCES;
4407 goto err_out2;
4408 }
4409
4410 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4411 pr_err("can't do query dir for a file\n");
4412 rc = -EINVAL;
4413 goto err_out2;
4414 }
4415
4416 srch_flag = req->Flags;
4417 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4418 le16_to_cpu(req->FileNameLength), 1,
4419 conn->local_nls);
4420 if (IS_ERR(srch_ptr)) {
4421 ksmbd_debug(SMB, "Search Pattern not found\n");
4422 rc = -EINVAL;
4423 goto err_out2;
4424 } else {
4425 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4426 }
4427
4428 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4429 ksmbd_debug(SMB, "Restart directory scan\n");
4430 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4431 }
4432
4433 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4434 d_info.wptr = (char *)rsp->Buffer;
4435 d_info.rptr = (char *)rsp->Buffer;
4436 d_info.out_buf_len =
4437 smb2_calc_max_out_buf_len(work, 8,
4438 le32_to_cpu(req->OutputBufferLength));
4439 if (d_info.out_buf_len < 0) {
4440 rc = -EINVAL;
4441 goto err_out;
4442 }
4443 d_info.flags = srch_flag;
4444
4445 /*
4446 * reserve dot and dotdot entries in head of buffer
4447 * in first response
4448 */
4449 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4450 dir_fp, &d_info, srch_ptr,
4451 smb2_populate_readdir_entry);
4452 if (rc == -ENOSPC)
4453 rc = 0;
4454 else if (rc)
4455 goto err_out;
4456
4457 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4458 d_info.hide_dot_file = true;
4459
4460 buffer_sz = d_info.out_buf_len;
4461 d_info.rptr = d_info.wptr;
4462 query_dir_private.work = work;
4463 query_dir_private.search_pattern = srch_ptr;
4464 query_dir_private.dir_fp = dir_fp;
4465 query_dir_private.d_info = &d_info;
4466 query_dir_private.info_level = req->FileInformationClass;
4467 dir_fp->readdir_data.private = &query_dir_private;
4468 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4469 again:
4470 d_info.num_scan = 0;
4471 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4472 /*
4473 * num_entry can be 0 if the directory iteration stops before reaching
4474 * the end of the directory and no file is matched with the search
4475 * pattern.
4476 */
4477 if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4478 d_info.out_buf_len > 0)
4479 goto again;
4480 /*
4481 * req->OutputBufferLength is too small to contain even one entry.
4482 * In this case, it immediately returns OutputBufferLength 0 to client.
4483 */
4484 if (!d_info.out_buf_len && !d_info.num_entry)
4485 goto no_buf_len;
4486 if (rc > 0 || rc == -ENOSPC)
4487 rc = 0;
4488 else if (rc)
4489 goto err_out;
4490
4491 d_info.wptr = d_info.rptr;
4492 d_info.out_buf_len = buffer_sz;
4493 rc = process_query_dir_entries(&query_dir_private);
4494 if (rc)
4495 goto err_out;
4496
4497 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4498 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4499 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4500 } else {
4501 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4502 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4503 }
4504 rsp->StructureSize = cpu_to_le16(9);
4505 rsp->OutputBufferOffset = cpu_to_le16(0);
4506 rsp->OutputBufferLength = cpu_to_le32(0);
4507 rsp->Buffer[0] = 0;
4508 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4509 offsetof(struct smb2_query_directory_rsp, Buffer)
4510 + 1);
4511 if (rc)
4512 goto err_out;
4513 } else {
4514 no_buf_len:
4515 ((struct file_directory_info *)
4516 ((char *)rsp->Buffer + d_info.last_entry_offset))
4517 ->NextEntryOffset = 0;
4518 if (d_info.data_count >= d_info.last_entry_off_align)
4519 d_info.data_count -= d_info.last_entry_off_align;
4520
4521 rsp->StructureSize = cpu_to_le16(9);
4522 rsp->OutputBufferOffset = cpu_to_le16(72);
4523 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4524 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4525 offsetof(struct smb2_query_directory_rsp, Buffer) +
4526 d_info.data_count);
4527 if (rc)
4528 goto err_out;
4529 }
4530
4531 kfree(srch_ptr);
4532 ksmbd_fd_put(work, dir_fp);
4533 ksmbd_revert_fsids(work);
4534 return 0;
4535
4536 err_out:
4537 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4538 kfree(srch_ptr);
4539
4540 err_out2:
4541 if (rc == -EINVAL)
4542 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4543 else if (rc == -EACCES)
4544 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4545 else if (rc == -ENOENT)
4546 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4547 else if (rc == -EBADF)
4548 rsp->hdr.Status = STATUS_FILE_CLOSED;
4549 else if (rc == -ENOMEM)
4550 rsp->hdr.Status = STATUS_NO_MEMORY;
4551 else if (rc == -EFAULT)
4552 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4553 else if (rc == -EIO)
4554 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4555 if (!rsp->hdr.Status)
4556 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4557
4558 smb2_set_err_rsp(work);
4559 ksmbd_fd_put(work, dir_fp);
4560 ksmbd_revert_fsids(work);
4561 return 0;
4562 }
4563
4564 /**
4565 * buffer_check_err() - helper function to check buffer errors
4566 * @reqOutputBufferLength: max buffer length expected in command response
4567 * @rsp: query info response buffer contains output buffer length
4568 * @rsp_org: base response buffer pointer in case of chained response
4569 *
4570 * Return: 0 on success, otherwise error
4571 */
buffer_check_err(int reqOutputBufferLength,struct smb2_query_info_rsp * rsp,void * rsp_org)4572 static int buffer_check_err(int reqOutputBufferLength,
4573 struct smb2_query_info_rsp *rsp,
4574 void *rsp_org)
4575 {
4576 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4577 pr_err("Invalid Buffer Size Requested\n");
4578 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4579 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4580 return -EINVAL;
4581 }
4582 return 0;
4583 }
4584
get_standard_info_pipe(struct smb2_query_info_rsp * rsp,void * rsp_org)4585 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4586 void *rsp_org)
4587 {
4588 struct smb2_file_standard_info *sinfo;
4589
4590 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4591
4592 sinfo->AllocationSize = cpu_to_le64(4096);
4593 sinfo->EndOfFile = cpu_to_le64(0);
4594 sinfo->NumberOfLinks = cpu_to_le32(1);
4595 sinfo->DeletePending = 1;
4596 sinfo->Directory = 0;
4597 rsp->OutputBufferLength =
4598 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4599 }
4600
get_internal_info_pipe(struct smb2_query_info_rsp * rsp,u64 num,void * rsp_org)4601 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4602 void *rsp_org)
4603 {
4604 struct smb2_file_internal_info *file_info;
4605
4606 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4607
4608 /* any unique number */
4609 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4610 rsp->OutputBufferLength =
4611 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4612 }
4613
smb2_get_info_file_pipe(struct ksmbd_session * sess,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp,void * rsp_org)4614 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4615 struct smb2_query_info_req *req,
4616 struct smb2_query_info_rsp *rsp,
4617 void *rsp_org)
4618 {
4619 u64 id;
4620 int rc;
4621
4622 /*
4623 * Windows can sometime send query file info request on
4624 * pipe without opening it, checking error condition here
4625 */
4626 id = req->VolatileFileId;
4627 if (!ksmbd_session_rpc_method(sess, id))
4628 return -ENOENT;
4629
4630 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4631 req->FileInfoClass, req->VolatileFileId);
4632
4633 switch (req->FileInfoClass) {
4634 case FILE_STANDARD_INFORMATION:
4635 get_standard_info_pipe(rsp, rsp_org);
4636 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4637 rsp, rsp_org);
4638 break;
4639 case FILE_INTERNAL_INFORMATION:
4640 get_internal_info_pipe(rsp, id, rsp_org);
4641 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4642 rsp, rsp_org);
4643 break;
4644 default:
4645 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4646 req->FileInfoClass);
4647 rc = -EOPNOTSUPP;
4648 }
4649 return rc;
4650 }
4651
4652 /**
4653 * smb2_get_ea() - handler for smb2 get extended attribute command
4654 * @work: smb work containing query info command buffer
4655 * @fp: ksmbd_file pointer
4656 * @req: get extended attribute request
4657 * @rsp: response buffer pointer
4658 * @rsp_org: base response buffer pointer in case of chained response
4659 *
4660 * Return: 0 on success, otherwise error
4661 */
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)4662 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4663 struct smb2_query_info_req *req,
4664 struct smb2_query_info_rsp *rsp, void *rsp_org)
4665 {
4666 struct smb2_ea_info *eainfo, *prev_eainfo;
4667 char *name, *ptr, *xattr_list = NULL, *buf;
4668 int rc, name_len, value_len, xattr_list_len, idx;
4669 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4670 struct smb2_ea_info_req *ea_req = NULL;
4671 const struct path *path;
4672 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4673
4674 if (!(fp->daccess & FILE_READ_EA_LE)) {
4675 pr_err("Not permitted to read ext attr : 0x%x\n",
4676 fp->daccess);
4677 return -EACCES;
4678 }
4679
4680 path = &fp->filp->f_path;
4681 /* single EA entry is requested with given user.* name */
4682 if (req->InputBufferLength) {
4683 if (le32_to_cpu(req->InputBufferLength) <=
4684 sizeof(struct smb2_ea_info_req))
4685 return -EINVAL;
4686
4687 ea_req = (struct smb2_ea_info_req *)((char *)req +
4688 le16_to_cpu(req->InputBufferOffset));
4689 } else {
4690 /* need to send all EAs, if no specific EA is requested*/
4691 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4692 ksmbd_debug(SMB,
4693 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4694 le32_to_cpu(req->Flags));
4695 }
4696
4697 buf_free_len =
4698 smb2_calc_max_out_buf_len(work, 8,
4699 le32_to_cpu(req->OutputBufferLength));
4700 if (buf_free_len < 0)
4701 return -EINVAL;
4702
4703 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4704 if (rc < 0) {
4705 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4706 goto out;
4707 } else if (!rc) { /* there is no EA in the file */
4708 ksmbd_debug(SMB, "no ea data in the file\n");
4709 goto done;
4710 }
4711 xattr_list_len = rc;
4712
4713 ptr = (char *)rsp->Buffer;
4714 eainfo = (struct smb2_ea_info *)ptr;
4715 prev_eainfo = eainfo;
4716 idx = 0;
4717
4718 while (idx < xattr_list_len) {
4719 name = xattr_list + idx;
4720 name_len = strlen(name);
4721
4722 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4723 idx += name_len + 1;
4724
4725 /*
4726 * CIFS does not support EA other than user.* namespace,
4727 * still keep the framework generic, to list other attrs
4728 * in future.
4729 */
4730 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4731 continue;
4732
4733 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4734 STREAM_PREFIX_LEN))
4735 continue;
4736
4737 if (req->InputBufferLength &&
4738 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4739 ea_req->EaNameLength))
4740 continue;
4741
4742 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4743 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4744 continue;
4745
4746 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4747 name_len -= XATTR_USER_PREFIX_LEN;
4748
4749 ptr = eainfo->name + name_len + 1;
4750 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4751 name_len + 1);
4752 /* bailout if xattr can't fit in buf_free_len */
4753 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4754 name, &buf);
4755 if (value_len <= 0) {
4756 rc = -ENOENT;
4757 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4758 goto out;
4759 }
4760
4761 buf_free_len -= value_len;
4762 if (buf_free_len < 0) {
4763 kfree(buf);
4764 break;
4765 }
4766
4767 memcpy(ptr, buf, value_len);
4768 kfree(buf);
4769
4770 ptr += value_len;
4771 eainfo->Flags = 0;
4772 eainfo->EaNameLength = name_len;
4773
4774 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4775 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4776 name_len);
4777 else
4778 memcpy(eainfo->name, name, name_len);
4779
4780 eainfo->name[name_len] = '\0';
4781 eainfo->EaValueLength = cpu_to_le16(value_len);
4782 next_offset = offsetof(struct smb2_ea_info, name) +
4783 name_len + 1 + value_len;
4784
4785 /* align next xattr entry at 4 byte bundary */
4786 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4787 if (alignment_bytes) {
4788 memset(ptr, '\0', alignment_bytes);
4789 ptr += alignment_bytes;
4790 next_offset += alignment_bytes;
4791 buf_free_len -= alignment_bytes;
4792 }
4793 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4794 prev_eainfo = eainfo;
4795 eainfo = (struct smb2_ea_info *)ptr;
4796 rsp_data_cnt += next_offset;
4797
4798 if (req->InputBufferLength) {
4799 ksmbd_debug(SMB, "single entry requested\n");
4800 break;
4801 }
4802 }
4803
4804 /* no more ea entries */
4805 prev_eainfo->NextEntryOffset = 0;
4806 done:
4807 rc = 0;
4808 if (rsp_data_cnt == 0)
4809 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4810 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4811 out:
4812 kvfree(xattr_list);
4813 return rc;
4814 }
4815
get_file_access_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4816 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4817 struct ksmbd_file *fp, void *rsp_org)
4818 {
4819 struct smb2_file_access_info *file_info;
4820
4821 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4822 file_info->AccessFlags = fp->daccess;
4823 rsp->OutputBufferLength =
4824 cpu_to_le32(sizeof(struct smb2_file_access_info));
4825 }
4826
get_file_basic_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4827 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4828 struct ksmbd_file *fp, void *rsp_org)
4829 {
4830 struct smb2_file_basic_info *basic_info;
4831 struct kstat stat;
4832 u64 time;
4833 int ret;
4834
4835 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4836 pr_err("no right to read the attributes : 0x%x\n",
4837 fp->daccess);
4838 return -EACCES;
4839 }
4840
4841 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4842 AT_STATX_SYNC_AS_STAT);
4843 if (ret)
4844 return ret;
4845
4846 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4847 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4848 time = ksmbd_UnixTimeToNT(stat.atime);
4849 basic_info->LastAccessTime = cpu_to_le64(time);
4850 time = ksmbd_UnixTimeToNT(stat.mtime);
4851 basic_info->LastWriteTime = cpu_to_le64(time);
4852 time = ksmbd_UnixTimeToNT(stat.ctime);
4853 basic_info->ChangeTime = cpu_to_le64(time);
4854 basic_info->Attributes = fp->f_ci->m_fattr;
4855 basic_info->Pad1 = 0;
4856 rsp->OutputBufferLength =
4857 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4858 return 0;
4859 }
4860
get_file_standard_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4861 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4862 struct ksmbd_file *fp, void *rsp_org)
4863 {
4864 struct smb2_file_standard_info *sinfo;
4865 unsigned int delete_pending;
4866 struct kstat stat;
4867 int ret;
4868
4869 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4870 AT_STATX_SYNC_AS_STAT);
4871 if (ret)
4872 return ret;
4873
4874 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4875 delete_pending = ksmbd_inode_pending_delete(fp);
4876
4877 if (ksmbd_stream_fd(fp) == false) {
4878 sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4879 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4880 } else {
4881 sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
4882 sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
4883 }
4884 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4885 sinfo->DeletePending = delete_pending;
4886 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4887 rsp->OutputBufferLength =
4888 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4889
4890 return 0;
4891 }
4892
get_file_alignment_info(struct smb2_query_info_rsp * rsp,void * rsp_org)4893 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4894 void *rsp_org)
4895 {
4896 struct smb2_file_alignment_info *file_info;
4897
4898 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4899 file_info->AlignmentRequirement = 0;
4900 rsp->OutputBufferLength =
4901 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4902 }
4903
get_file_all_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4904 static int get_file_all_info(struct ksmbd_work *work,
4905 struct smb2_query_info_rsp *rsp,
4906 struct ksmbd_file *fp,
4907 void *rsp_org)
4908 {
4909 struct ksmbd_conn *conn = work->conn;
4910 struct smb2_file_all_info *file_info;
4911 unsigned int delete_pending;
4912 struct kstat stat;
4913 int conv_len;
4914 char *filename;
4915 u64 time;
4916 int ret;
4917
4918 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4919 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4920 fp->daccess);
4921 return -EACCES;
4922 }
4923
4924 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4925 if (IS_ERR(filename))
4926 return PTR_ERR(filename);
4927
4928 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4929 AT_STATX_SYNC_AS_STAT);
4930 if (ret)
4931 return ret;
4932
4933 ksmbd_debug(SMB, "filename = %s\n", filename);
4934 delete_pending = ksmbd_inode_pending_delete(fp);
4935 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4936
4937 file_info->CreationTime = cpu_to_le64(fp->create_time);
4938 time = ksmbd_UnixTimeToNT(stat.atime);
4939 file_info->LastAccessTime = cpu_to_le64(time);
4940 time = ksmbd_UnixTimeToNT(stat.mtime);
4941 file_info->LastWriteTime = cpu_to_le64(time);
4942 time = ksmbd_UnixTimeToNT(stat.ctime);
4943 file_info->ChangeTime = cpu_to_le64(time);
4944 file_info->Attributes = fp->f_ci->m_fattr;
4945 file_info->Pad1 = 0;
4946 if (ksmbd_stream_fd(fp) == false) {
4947 file_info->AllocationSize =
4948 cpu_to_le64(stat.blocks << 9);
4949 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4950 } else {
4951 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
4952 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
4953 }
4954 file_info->NumberOfLinks =
4955 cpu_to_le32(get_nlink(&stat) - delete_pending);
4956 file_info->DeletePending = delete_pending;
4957 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4958 file_info->Pad2 = 0;
4959 file_info->IndexNumber = cpu_to_le64(stat.ino);
4960 file_info->EASize = 0;
4961 file_info->AccessFlags = fp->daccess;
4962 if (ksmbd_stream_fd(fp) == false)
4963 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4964 else
4965 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
4966 file_info->Mode = fp->coption;
4967 file_info->AlignmentRequirement = 0;
4968 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4969 PATH_MAX, conn->local_nls, 0);
4970 conv_len *= 2;
4971 file_info->FileNameLength = cpu_to_le32(conv_len);
4972 rsp->OutputBufferLength =
4973 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4974 kfree(filename);
4975 return 0;
4976 }
4977
get_file_alternate_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4978 static void get_file_alternate_info(struct ksmbd_work *work,
4979 struct smb2_query_info_rsp *rsp,
4980 struct ksmbd_file *fp,
4981 void *rsp_org)
4982 {
4983 struct ksmbd_conn *conn = work->conn;
4984 struct smb2_file_alt_name_info *file_info;
4985 struct dentry *dentry = fp->filp->f_path.dentry;
4986 int conv_len;
4987
4988 spin_lock(&dentry->d_lock);
4989 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4990 conv_len = ksmbd_extract_shortname(conn,
4991 dentry->d_name.name,
4992 file_info->FileName);
4993 spin_unlock(&dentry->d_lock);
4994 file_info->FileNameLength = cpu_to_le32(conv_len);
4995 rsp->OutputBufferLength =
4996 cpu_to_le32(struct_size(file_info, FileName, conv_len));
4997 }
4998
get_file_stream_info(struct ksmbd_work * work,struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)4999 static int get_file_stream_info(struct ksmbd_work *work,
5000 struct smb2_query_info_rsp *rsp,
5001 struct ksmbd_file *fp,
5002 void *rsp_org)
5003 {
5004 struct ksmbd_conn *conn = work->conn;
5005 struct smb2_file_stream_info *file_info;
5006 char *stream_name, *xattr_list = NULL, *stream_buf;
5007 struct kstat stat;
5008 const struct path *path = &fp->filp->f_path;
5009 ssize_t xattr_list_len;
5010 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5011 int buf_free_len;
5012 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5013 int ret;
5014
5015 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5016 AT_STATX_SYNC_AS_STAT);
5017 if (ret)
5018 return ret;
5019
5020 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5021
5022 buf_free_len =
5023 smb2_calc_max_out_buf_len(work, 8,
5024 le32_to_cpu(req->OutputBufferLength));
5025 if (buf_free_len < 0)
5026 goto out;
5027
5028 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5029 if (xattr_list_len < 0) {
5030 goto out;
5031 } else if (!xattr_list_len) {
5032 ksmbd_debug(SMB, "empty xattr in the file\n");
5033 goto out;
5034 }
5035
5036 while (idx < xattr_list_len) {
5037 stream_name = xattr_list + idx;
5038 streamlen = strlen(stream_name);
5039 idx += streamlen + 1;
5040
5041 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5042
5043 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5044 STREAM_PREFIX, STREAM_PREFIX_LEN))
5045 continue;
5046
5047 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5048 STREAM_PREFIX_LEN);
5049 streamlen = stream_name_len;
5050
5051 /* plus : size */
5052 streamlen += 1;
5053 stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5054 if (!stream_buf)
5055 break;
5056
5057 streamlen = snprintf(stream_buf, streamlen + 1,
5058 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5059
5060 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5061 if (next > buf_free_len) {
5062 kfree(stream_buf);
5063 break;
5064 }
5065
5066 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5067 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5068 stream_buf, streamlen,
5069 conn->local_nls, 0);
5070 streamlen *= 2;
5071 kfree(stream_buf);
5072 file_info->StreamNameLength = cpu_to_le32(streamlen);
5073 file_info->StreamSize = cpu_to_le64(stream_name_len);
5074 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5075
5076 nbytes += next;
5077 buf_free_len -= next;
5078 file_info->NextEntryOffset = cpu_to_le32(next);
5079 }
5080
5081 out:
5082 if (!S_ISDIR(stat.mode) &&
5083 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5084 file_info = (struct smb2_file_stream_info *)
5085 &rsp->Buffer[nbytes];
5086 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5087 "::$DATA", 7, conn->local_nls, 0);
5088 streamlen *= 2;
5089 file_info->StreamNameLength = cpu_to_le32(streamlen);
5090 file_info->StreamSize = cpu_to_le64(stat.size);
5091 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5092 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5093 }
5094
5095 /* last entry offset should be 0 */
5096 file_info->NextEntryOffset = 0;
5097 kvfree(xattr_list);
5098
5099 rsp->OutputBufferLength = cpu_to_le32(nbytes);
5100
5101 return 0;
5102 }
5103
get_file_internal_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5104 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5105 struct ksmbd_file *fp, void *rsp_org)
5106 {
5107 struct smb2_file_internal_info *file_info;
5108 struct kstat stat;
5109 int ret;
5110
5111 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5112 AT_STATX_SYNC_AS_STAT);
5113 if (ret)
5114 return ret;
5115
5116 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5117 file_info->IndexNumber = cpu_to_le64(stat.ino);
5118 rsp->OutputBufferLength =
5119 cpu_to_le32(sizeof(struct smb2_file_internal_info));
5120
5121 return 0;
5122 }
5123
get_file_network_open_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5124 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5125 struct ksmbd_file *fp, void *rsp_org)
5126 {
5127 struct smb2_file_ntwrk_info *file_info;
5128 struct kstat stat;
5129 u64 time;
5130 int ret;
5131
5132 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5133 pr_err("no right to read the attributes : 0x%x\n",
5134 fp->daccess);
5135 return -EACCES;
5136 }
5137
5138 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5139 AT_STATX_SYNC_AS_STAT);
5140 if (ret)
5141 return ret;
5142
5143 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
5144
5145 file_info->CreationTime = cpu_to_le64(fp->create_time);
5146 time = ksmbd_UnixTimeToNT(stat.atime);
5147 file_info->LastAccessTime = cpu_to_le64(time);
5148 time = ksmbd_UnixTimeToNT(stat.mtime);
5149 file_info->LastWriteTime = cpu_to_le64(time);
5150 time = ksmbd_UnixTimeToNT(stat.ctime);
5151 file_info->ChangeTime = cpu_to_le64(time);
5152 file_info->Attributes = fp->f_ci->m_fattr;
5153 if (ksmbd_stream_fd(fp) == false) {
5154 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5155 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5156 } else {
5157 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5158 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5159 }
5160 file_info->Reserved = cpu_to_le32(0);
5161 rsp->OutputBufferLength =
5162 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
5163 return 0;
5164 }
5165
get_file_ea_info(struct smb2_query_info_rsp * rsp,void * rsp_org)5166 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5167 {
5168 struct smb2_file_ea_info *file_info;
5169
5170 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5171 file_info->EASize = 0;
5172 rsp->OutputBufferLength =
5173 cpu_to_le32(sizeof(struct smb2_file_ea_info));
5174 }
5175
get_file_position_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5176 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5177 struct ksmbd_file *fp, void *rsp_org)
5178 {
5179 struct smb2_file_pos_info *file_info;
5180
5181 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5182 if (ksmbd_stream_fd(fp) == false)
5183 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5184 else
5185 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5186
5187 rsp->OutputBufferLength =
5188 cpu_to_le32(sizeof(struct smb2_file_pos_info));
5189 }
5190
get_file_mode_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5191 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5192 struct ksmbd_file *fp, void *rsp_org)
5193 {
5194 struct smb2_file_mode_info *file_info;
5195
5196 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5197 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5198 rsp->OutputBufferLength =
5199 cpu_to_le32(sizeof(struct smb2_file_mode_info));
5200 }
5201
get_file_compression_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5202 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5203 struct ksmbd_file *fp, void *rsp_org)
5204 {
5205 struct smb2_file_comp_info *file_info;
5206 struct kstat stat;
5207 int ret;
5208
5209 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5210 AT_STATX_SYNC_AS_STAT);
5211 if (ret)
5212 return ret;
5213
5214 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5215 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5216 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5217 file_info->CompressionUnitShift = 0;
5218 file_info->ChunkShift = 0;
5219 file_info->ClusterShift = 0;
5220 memset(&file_info->Reserved[0], 0, 3);
5221
5222 rsp->OutputBufferLength =
5223 cpu_to_le32(sizeof(struct smb2_file_comp_info));
5224
5225 return 0;
5226 }
5227
get_file_attribute_tag_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5228 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5229 struct ksmbd_file *fp, void *rsp_org)
5230 {
5231 struct smb2_file_attr_tag_info *file_info;
5232
5233 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5234 pr_err("no right to read the attributes : 0x%x\n",
5235 fp->daccess);
5236 return -EACCES;
5237 }
5238
5239 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5240 file_info->FileAttributes = fp->f_ci->m_fattr;
5241 file_info->ReparseTag = 0;
5242 rsp->OutputBufferLength =
5243 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5244 return 0;
5245 }
5246
find_file_posix_info(struct smb2_query_info_rsp * rsp,struct ksmbd_file * fp,void * rsp_org)5247 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5248 struct ksmbd_file *fp, void *rsp_org)
5249 {
5250 struct smb311_posix_qinfo *file_info;
5251 struct inode *inode = file_inode(fp->filp);
5252 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5253 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5254 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5255 struct kstat stat;
5256 u64 time;
5257 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5258 int ret;
5259
5260 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5261 AT_STATX_SYNC_AS_STAT);
5262 if (ret)
5263 return ret;
5264
5265 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5266 file_info->CreationTime = cpu_to_le64(fp->create_time);
5267 time = ksmbd_UnixTimeToNT(stat.atime);
5268 file_info->LastAccessTime = cpu_to_le64(time);
5269 time = ksmbd_UnixTimeToNT(stat.mtime);
5270 file_info->LastWriteTime = cpu_to_le64(time);
5271 time = ksmbd_UnixTimeToNT(stat.ctime);
5272 file_info->ChangeTime = cpu_to_le64(time);
5273 file_info->DosAttributes = fp->f_ci->m_fattr;
5274 file_info->Inode = cpu_to_le64(stat.ino);
5275 if (ksmbd_stream_fd(fp) == false) {
5276 file_info->EndOfFile = cpu_to_le64(stat.size);
5277 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5278 } else {
5279 file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5280 file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5281 }
5282 file_info->HardLinks = cpu_to_le32(stat.nlink);
5283 file_info->Mode = cpu_to_le32(stat.mode & 0777);
5284 switch (stat.mode & S_IFMT) {
5285 case S_IFDIR:
5286 file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5287 break;
5288 case S_IFLNK:
5289 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5290 break;
5291 case S_IFCHR:
5292 file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5293 break;
5294 case S_IFBLK:
5295 file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5296 break;
5297 case S_IFIFO:
5298 file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5299 break;
5300 case S_IFSOCK:
5301 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5302 }
5303
5304 file_info->DeviceId = cpu_to_le32(stat.rdev);
5305
5306 /*
5307 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5308 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5309 * sub_auth(4 * 1(num_subauth)) + RID(4).
5310 */
5311 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5312 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5313 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5314 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5315
5316 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5317
5318 return 0;
5319 }
5320
smb2_get_info_file(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)5321 static int smb2_get_info_file(struct ksmbd_work *work,
5322 struct smb2_query_info_req *req,
5323 struct smb2_query_info_rsp *rsp)
5324 {
5325 struct ksmbd_file *fp;
5326 int fileinfoclass = 0;
5327 int rc = 0;
5328 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5329
5330 if (test_share_config_flag(work->tcon->share_conf,
5331 KSMBD_SHARE_FLAG_PIPE)) {
5332 /* smb2 info file called for pipe */
5333 return smb2_get_info_file_pipe(work->sess, req, rsp,
5334 work->response_buf);
5335 }
5336
5337 if (work->next_smb2_rcv_hdr_off) {
5338 if (!has_file_id(req->VolatileFileId)) {
5339 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5340 work->compound_fid);
5341 id = work->compound_fid;
5342 pid = work->compound_pfid;
5343 }
5344 }
5345
5346 if (!has_file_id(id)) {
5347 id = req->VolatileFileId;
5348 pid = req->PersistentFileId;
5349 }
5350
5351 fp = ksmbd_lookup_fd_slow(work, id, pid);
5352 if (!fp)
5353 return -ENOENT;
5354
5355 fileinfoclass = req->FileInfoClass;
5356
5357 switch (fileinfoclass) {
5358 case FILE_ACCESS_INFORMATION:
5359 get_file_access_info(rsp, fp, work->response_buf);
5360 break;
5361
5362 case FILE_BASIC_INFORMATION:
5363 rc = get_file_basic_info(rsp, fp, work->response_buf);
5364 break;
5365
5366 case FILE_STANDARD_INFORMATION:
5367 rc = get_file_standard_info(rsp, fp, work->response_buf);
5368 break;
5369
5370 case FILE_ALIGNMENT_INFORMATION:
5371 get_file_alignment_info(rsp, work->response_buf);
5372 break;
5373
5374 case FILE_ALL_INFORMATION:
5375 rc = get_file_all_info(work, rsp, fp, work->response_buf);
5376 break;
5377
5378 case FILE_ALTERNATE_NAME_INFORMATION:
5379 get_file_alternate_info(work, rsp, fp, work->response_buf);
5380 break;
5381
5382 case FILE_STREAM_INFORMATION:
5383 rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5384 break;
5385
5386 case FILE_INTERNAL_INFORMATION:
5387 rc = get_file_internal_info(rsp, fp, work->response_buf);
5388 break;
5389
5390 case FILE_NETWORK_OPEN_INFORMATION:
5391 rc = get_file_network_open_info(rsp, fp, work->response_buf);
5392 break;
5393
5394 case FILE_EA_INFORMATION:
5395 get_file_ea_info(rsp, work->response_buf);
5396 break;
5397
5398 case FILE_FULL_EA_INFORMATION:
5399 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5400 break;
5401
5402 case FILE_POSITION_INFORMATION:
5403 get_file_position_info(rsp, fp, work->response_buf);
5404 break;
5405
5406 case FILE_MODE_INFORMATION:
5407 get_file_mode_info(rsp, fp, work->response_buf);
5408 break;
5409
5410 case FILE_COMPRESSION_INFORMATION:
5411 rc = get_file_compression_info(rsp, fp, work->response_buf);
5412 break;
5413
5414 case FILE_ATTRIBUTE_TAG_INFORMATION:
5415 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5416 break;
5417 case SMB_FIND_FILE_POSIX_INFO:
5418 if (!work->tcon->posix_extensions) {
5419 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5420 rc = -EOPNOTSUPP;
5421 } else {
5422 rc = find_file_posix_info(rsp, fp, work->response_buf);
5423 }
5424 break;
5425 default:
5426 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5427 fileinfoclass);
5428 rc = -EOPNOTSUPP;
5429 }
5430 if (!rc)
5431 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5432 rsp, work->response_buf);
5433 ksmbd_fd_put(work, fp);
5434 return rc;
5435 }
5436
smb2_get_info_filesystem(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)5437 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5438 struct smb2_query_info_req *req,
5439 struct smb2_query_info_rsp *rsp)
5440 {
5441 struct ksmbd_session *sess = work->sess;
5442 struct ksmbd_conn *conn = work->conn;
5443 struct ksmbd_share_config *share = work->tcon->share_conf;
5444 int fsinfoclass = 0;
5445 struct kstatfs stfs;
5446 struct path path;
5447 int rc = 0, len;
5448
5449 if (!share->path)
5450 return -EIO;
5451
5452 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5453 if (rc) {
5454 pr_err("cannot create vfs path\n");
5455 return -EIO;
5456 }
5457
5458 rc = vfs_statfs(&path, &stfs);
5459 if (rc) {
5460 pr_err("cannot do stat of path %s\n", share->path);
5461 path_put(&path);
5462 return -EIO;
5463 }
5464
5465 fsinfoclass = req->FileInfoClass;
5466
5467 switch (fsinfoclass) {
5468 case FS_DEVICE_INFORMATION:
5469 {
5470 struct filesystem_device_info *info;
5471
5472 info = (struct filesystem_device_info *)rsp->Buffer;
5473
5474 info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5475 info->DeviceCharacteristics =
5476 cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5477 if (!test_tree_conn_flag(work->tcon,
5478 KSMBD_TREE_CONN_FLAG_WRITABLE))
5479 info->DeviceCharacteristics |=
5480 cpu_to_le32(FILE_READ_ONLY_DEVICE);
5481 rsp->OutputBufferLength = cpu_to_le32(8);
5482 break;
5483 }
5484 case FS_ATTRIBUTE_INFORMATION:
5485 {
5486 struct filesystem_attribute_info *info;
5487 size_t sz;
5488
5489 info = (struct filesystem_attribute_info *)rsp->Buffer;
5490 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5491 FILE_PERSISTENT_ACLS |
5492 FILE_UNICODE_ON_DISK |
5493 FILE_CASE_PRESERVED_NAMES |
5494 FILE_CASE_SENSITIVE_SEARCH |
5495 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5496
5497 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5498
5499 if (test_share_config_flag(work->tcon->share_conf,
5500 KSMBD_SHARE_FLAG_STREAMS))
5501 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5502
5503 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5504 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5505 "NTFS", PATH_MAX, conn->local_nls, 0);
5506 len = len * 2;
5507 info->FileSystemNameLen = cpu_to_le32(len);
5508 sz = sizeof(struct filesystem_attribute_info) + len;
5509 rsp->OutputBufferLength = cpu_to_le32(sz);
5510 break;
5511 }
5512 case FS_VOLUME_INFORMATION:
5513 {
5514 struct filesystem_vol_info *info;
5515 size_t sz;
5516 unsigned int serial_crc = 0;
5517
5518 info = (struct filesystem_vol_info *)(rsp->Buffer);
5519 info->VolumeCreationTime = 0;
5520 serial_crc = crc32_le(serial_crc, share->name,
5521 strlen(share->name));
5522 serial_crc = crc32_le(serial_crc, share->path,
5523 strlen(share->path));
5524 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5525 strlen(ksmbd_netbios_name()));
5526 /* Taking dummy value of serial number*/
5527 info->SerialNumber = cpu_to_le32(serial_crc);
5528 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5529 share->name, PATH_MAX,
5530 conn->local_nls, 0);
5531 len = len * 2;
5532 info->VolumeLabelSize = cpu_to_le32(len);
5533 info->Reserved = 0;
5534 sz = sizeof(struct filesystem_vol_info) + len;
5535 rsp->OutputBufferLength = cpu_to_le32(sz);
5536 break;
5537 }
5538 case FS_SIZE_INFORMATION:
5539 {
5540 struct filesystem_info *info;
5541
5542 info = (struct filesystem_info *)(rsp->Buffer);
5543 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5544 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5545 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5546 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5547 rsp->OutputBufferLength = cpu_to_le32(24);
5548 break;
5549 }
5550 case FS_FULL_SIZE_INFORMATION:
5551 {
5552 struct smb2_fs_full_size_info *info;
5553
5554 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5555 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5556 info->CallerAvailableAllocationUnits =
5557 cpu_to_le64(stfs.f_bavail);
5558 info->ActualAvailableAllocationUnits =
5559 cpu_to_le64(stfs.f_bfree);
5560 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5561 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5562 rsp->OutputBufferLength = cpu_to_le32(32);
5563 break;
5564 }
5565 case FS_OBJECT_ID_INFORMATION:
5566 {
5567 struct object_id_info *info;
5568
5569 info = (struct object_id_info *)(rsp->Buffer);
5570
5571 if (!user_guest(sess->user))
5572 memcpy(info->objid, user_passkey(sess->user), 16);
5573 else
5574 memset(info->objid, 0, 16);
5575
5576 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5577 info->extended_info.version = cpu_to_le32(1);
5578 info->extended_info.release = cpu_to_le32(1);
5579 info->extended_info.rel_date = 0;
5580 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5581 rsp->OutputBufferLength = cpu_to_le32(64);
5582 break;
5583 }
5584 case FS_SECTOR_SIZE_INFORMATION:
5585 {
5586 struct smb3_fs_ss_info *info;
5587 unsigned int sector_size =
5588 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5589
5590 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5591
5592 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5593 info->PhysicalBytesPerSectorForAtomicity =
5594 cpu_to_le32(sector_size);
5595 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5596 info->FSEffPhysicalBytesPerSectorForAtomicity =
5597 cpu_to_le32(sector_size);
5598 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5599 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5600 info->ByteOffsetForSectorAlignment = 0;
5601 info->ByteOffsetForPartitionAlignment = 0;
5602 rsp->OutputBufferLength = cpu_to_le32(28);
5603 break;
5604 }
5605 case FS_CONTROL_INFORMATION:
5606 {
5607 /*
5608 * TODO : The current implementation is based on
5609 * test result with win7(NTFS) server. It's need to
5610 * modify this to get valid Quota values
5611 * from Linux kernel
5612 */
5613 struct smb2_fs_control_info *info;
5614
5615 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5616 info->FreeSpaceStartFiltering = 0;
5617 info->FreeSpaceThreshold = 0;
5618 info->FreeSpaceStopFiltering = 0;
5619 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5620 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5621 info->Padding = 0;
5622 rsp->OutputBufferLength = cpu_to_le32(48);
5623 break;
5624 }
5625 case FS_POSIX_INFORMATION:
5626 {
5627 struct filesystem_posix_info *info;
5628
5629 if (!work->tcon->posix_extensions) {
5630 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5631 rc = -EOPNOTSUPP;
5632 } else {
5633 info = (struct filesystem_posix_info *)(rsp->Buffer);
5634 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5635 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5636 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5637 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5638 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5639 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5640 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5641 rsp->OutputBufferLength = cpu_to_le32(56);
5642 }
5643 break;
5644 }
5645 default:
5646 path_put(&path);
5647 return -EOPNOTSUPP;
5648 }
5649 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5650 rsp, work->response_buf);
5651 path_put(&path);
5652 return rc;
5653 }
5654
smb2_get_info_sec(struct ksmbd_work * work,struct smb2_query_info_req * req,struct smb2_query_info_rsp * rsp)5655 static int smb2_get_info_sec(struct ksmbd_work *work,
5656 struct smb2_query_info_req *req,
5657 struct smb2_query_info_rsp *rsp)
5658 {
5659 struct ksmbd_file *fp;
5660 struct mnt_idmap *idmap;
5661 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5662 struct smb_fattr fattr = {{0}};
5663 struct inode *inode;
5664 __u32 secdesclen = 0;
5665 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5666 int addition_info = le32_to_cpu(req->AdditionalInformation);
5667 int rc = 0, ppntsd_size = 0;
5668
5669 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5670 PROTECTED_DACL_SECINFO |
5671 UNPROTECTED_DACL_SECINFO)) {
5672 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5673 addition_info);
5674
5675 pntsd->revision = cpu_to_le16(1);
5676 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5677 pntsd->osidoffset = 0;
5678 pntsd->gsidoffset = 0;
5679 pntsd->sacloffset = 0;
5680 pntsd->dacloffset = 0;
5681
5682 secdesclen = sizeof(struct smb_ntsd);
5683 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5684
5685 return 0;
5686 }
5687
5688 if (work->next_smb2_rcv_hdr_off) {
5689 if (!has_file_id(req->VolatileFileId)) {
5690 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5691 work->compound_fid);
5692 id = work->compound_fid;
5693 pid = work->compound_pfid;
5694 }
5695 }
5696
5697 if (!has_file_id(id)) {
5698 id = req->VolatileFileId;
5699 pid = req->PersistentFileId;
5700 }
5701
5702 fp = ksmbd_lookup_fd_slow(work, id, pid);
5703 if (!fp)
5704 return -ENOENT;
5705
5706 idmap = file_mnt_idmap(fp->filp);
5707 inode = file_inode(fp->filp);
5708 ksmbd_acls_fattr(&fattr, idmap, inode);
5709
5710 if (test_share_config_flag(work->tcon->share_conf,
5711 KSMBD_SHARE_FLAG_ACL_XATTR))
5712 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5713 fp->filp->f_path.dentry,
5714 &ppntsd);
5715
5716 /* Check if sd buffer size exceeds response buffer size */
5717 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5718 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5719 addition_info, &secdesclen, &fattr);
5720 posix_acl_release(fattr.cf_acls);
5721 posix_acl_release(fattr.cf_dacls);
5722 kfree(ppntsd);
5723 ksmbd_fd_put(work, fp);
5724 if (rc)
5725 return rc;
5726
5727 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5728 return 0;
5729 }
5730
5731 /**
5732 * smb2_query_info() - handler for smb2 query info command
5733 * @work: smb work containing query info request buffer
5734 *
5735 * Return: 0 on success, otherwise error
5736 */
smb2_query_info(struct ksmbd_work * work)5737 int smb2_query_info(struct ksmbd_work *work)
5738 {
5739 struct smb2_query_info_req *req;
5740 struct smb2_query_info_rsp *rsp;
5741 int rc = 0;
5742
5743 ksmbd_debug(SMB, "Received request smb2 query info request\n");
5744
5745 WORK_BUFFERS(work, req, rsp);
5746
5747 if (ksmbd_override_fsids(work)) {
5748 rc = -ENOMEM;
5749 goto err_out;
5750 }
5751
5752 switch (req->InfoType) {
5753 case SMB2_O_INFO_FILE:
5754 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5755 rc = smb2_get_info_file(work, req, rsp);
5756 break;
5757 case SMB2_O_INFO_FILESYSTEM:
5758 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5759 rc = smb2_get_info_filesystem(work, req, rsp);
5760 break;
5761 case SMB2_O_INFO_SECURITY:
5762 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5763 rc = smb2_get_info_sec(work, req, rsp);
5764 break;
5765 default:
5766 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5767 req->InfoType);
5768 rc = -EOPNOTSUPP;
5769 }
5770 ksmbd_revert_fsids(work);
5771
5772 if (!rc) {
5773 rsp->StructureSize = cpu_to_le16(9);
5774 rsp->OutputBufferOffset = cpu_to_le16(72);
5775 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5776 offsetof(struct smb2_query_info_rsp, Buffer) +
5777 le32_to_cpu(rsp->OutputBufferLength));
5778 }
5779
5780 err_out:
5781 if (rc < 0) {
5782 if (rc == -EACCES)
5783 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5784 else if (rc == -ENOENT)
5785 rsp->hdr.Status = STATUS_FILE_CLOSED;
5786 else if (rc == -EIO)
5787 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5788 else if (rc == -ENOMEM)
5789 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5790 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5791 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5792 smb2_set_err_rsp(work);
5793
5794 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5795 rc);
5796 return rc;
5797 }
5798 return 0;
5799 }
5800
5801 /**
5802 * smb2_close_pipe() - handler for closing IPC pipe
5803 * @work: smb work containing close request buffer
5804 *
5805 * Return: 0
5806 */
smb2_close_pipe(struct ksmbd_work * work)5807 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5808 {
5809 u64 id;
5810 struct smb2_close_req *req;
5811 struct smb2_close_rsp *rsp;
5812
5813 WORK_BUFFERS(work, req, rsp);
5814
5815 id = req->VolatileFileId;
5816 ksmbd_session_rpc_close(work->sess, id);
5817
5818 rsp->StructureSize = cpu_to_le16(60);
5819 rsp->Flags = 0;
5820 rsp->Reserved = 0;
5821 rsp->CreationTime = 0;
5822 rsp->LastAccessTime = 0;
5823 rsp->LastWriteTime = 0;
5824 rsp->ChangeTime = 0;
5825 rsp->AllocationSize = 0;
5826 rsp->EndOfFile = 0;
5827 rsp->Attributes = 0;
5828
5829 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5830 sizeof(struct smb2_close_rsp));
5831 }
5832
5833 /**
5834 * smb2_close() - handler for smb2 close file command
5835 * @work: smb work containing close request buffer
5836 *
5837 * Return: 0
5838 */
smb2_close(struct ksmbd_work * work)5839 int smb2_close(struct ksmbd_work *work)
5840 {
5841 u64 volatile_id = KSMBD_NO_FID;
5842 u64 sess_id;
5843 struct smb2_close_req *req;
5844 struct smb2_close_rsp *rsp;
5845 struct ksmbd_conn *conn = work->conn;
5846 struct ksmbd_file *fp;
5847 u64 time;
5848 int err = 0;
5849
5850 ksmbd_debug(SMB, "Received smb2 close request\n");
5851
5852 WORK_BUFFERS(work, req, rsp);
5853
5854 if (test_share_config_flag(work->tcon->share_conf,
5855 KSMBD_SHARE_FLAG_PIPE)) {
5856 ksmbd_debug(SMB, "IPC pipe close request\n");
5857 return smb2_close_pipe(work);
5858 }
5859
5860 sess_id = le64_to_cpu(req->hdr.SessionId);
5861 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5862 sess_id = work->compound_sid;
5863
5864 work->compound_sid = 0;
5865 if (check_session_id(conn, sess_id)) {
5866 work->compound_sid = sess_id;
5867 } else {
5868 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5869 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5870 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5871 err = -EBADF;
5872 goto out;
5873 }
5874
5875 if (work->next_smb2_rcv_hdr_off &&
5876 !has_file_id(req->VolatileFileId)) {
5877 if (!has_file_id(work->compound_fid)) {
5878 /* file already closed, return FILE_CLOSED */
5879 ksmbd_debug(SMB, "file already closed\n");
5880 rsp->hdr.Status = STATUS_FILE_CLOSED;
5881 err = -EBADF;
5882 goto out;
5883 } else {
5884 ksmbd_debug(SMB,
5885 "Compound request set FID = %llu:%llu\n",
5886 work->compound_fid,
5887 work->compound_pfid);
5888 volatile_id = work->compound_fid;
5889
5890 /* file closed, stored id is not valid anymore */
5891 work->compound_fid = KSMBD_NO_FID;
5892 work->compound_pfid = KSMBD_NO_FID;
5893 }
5894 } else {
5895 volatile_id = req->VolatileFileId;
5896 }
5897 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5898
5899 rsp->StructureSize = cpu_to_le16(60);
5900 rsp->Reserved = 0;
5901
5902 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5903 struct kstat stat;
5904 int ret;
5905
5906 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5907 if (!fp) {
5908 err = -ENOENT;
5909 goto out;
5910 }
5911
5912 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5913 AT_STATX_SYNC_AS_STAT);
5914 if (ret) {
5915 ksmbd_fd_put(work, fp);
5916 goto out;
5917 }
5918
5919 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5920 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
5921 cpu_to_le64(stat.blocks << 9);
5922 rsp->EndOfFile = cpu_to_le64(stat.size);
5923 rsp->Attributes = fp->f_ci->m_fattr;
5924 rsp->CreationTime = cpu_to_le64(fp->create_time);
5925 time = ksmbd_UnixTimeToNT(stat.atime);
5926 rsp->LastAccessTime = cpu_to_le64(time);
5927 time = ksmbd_UnixTimeToNT(stat.mtime);
5928 rsp->LastWriteTime = cpu_to_le64(time);
5929 time = ksmbd_UnixTimeToNT(stat.ctime);
5930 rsp->ChangeTime = cpu_to_le64(time);
5931 ksmbd_fd_put(work, fp);
5932 } else {
5933 rsp->Flags = 0;
5934 rsp->AllocationSize = 0;
5935 rsp->EndOfFile = 0;
5936 rsp->Attributes = 0;
5937 rsp->CreationTime = 0;
5938 rsp->LastAccessTime = 0;
5939 rsp->LastWriteTime = 0;
5940 rsp->ChangeTime = 0;
5941 }
5942
5943 err = ksmbd_close_fd(work, volatile_id);
5944 out:
5945 if (!err)
5946 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5947 sizeof(struct smb2_close_rsp));
5948
5949 if (err) {
5950 if (rsp->hdr.Status == 0)
5951 rsp->hdr.Status = STATUS_FILE_CLOSED;
5952 smb2_set_err_rsp(work);
5953 }
5954
5955 return err;
5956 }
5957
5958 /**
5959 * smb2_echo() - handler for smb2 echo(ping) command
5960 * @work: smb work containing echo request buffer
5961 *
5962 * Return: 0
5963 */
smb2_echo(struct ksmbd_work * work)5964 int smb2_echo(struct ksmbd_work *work)
5965 {
5966 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5967
5968 ksmbd_debug(SMB, "Received smb2 echo request\n");
5969
5970 if (work->next_smb2_rcv_hdr_off)
5971 rsp = ksmbd_resp_buf_next(work);
5972
5973 rsp->StructureSize = cpu_to_le16(4);
5974 rsp->Reserved = 0;
5975 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5976 }
5977
smb2_rename(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_rename_info * file_info,struct nls_table * local_nls)5978 static int smb2_rename(struct ksmbd_work *work,
5979 struct ksmbd_file *fp,
5980 struct smb2_file_rename_info *file_info,
5981 struct nls_table *local_nls)
5982 {
5983 struct ksmbd_share_config *share = fp->tcon->share_conf;
5984 char *new_name = NULL;
5985 int rc, flags = 0;
5986
5987 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5988 new_name = smb2_get_name(file_info->FileName,
5989 le32_to_cpu(file_info->FileNameLength),
5990 local_nls);
5991 if (IS_ERR(new_name))
5992 return PTR_ERR(new_name);
5993
5994 if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
5995 int s_type;
5996 char *xattr_stream_name, *stream_name = NULL;
5997 size_t xattr_stream_size;
5998 int len;
5999
6000 rc = parse_stream_name(new_name, &stream_name, &s_type);
6001 if (rc < 0)
6002 goto out;
6003
6004 len = strlen(new_name);
6005 if (len > 0 && new_name[len - 1] != '/') {
6006 pr_err("not allow base filename in rename\n");
6007 rc = -ESHARE;
6008 goto out;
6009 }
6010
6011 rc = ksmbd_vfs_xattr_stream_name(stream_name,
6012 &xattr_stream_name,
6013 &xattr_stream_size,
6014 s_type);
6015 if (rc)
6016 goto out;
6017
6018 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6019 &fp->filp->f_path,
6020 xattr_stream_name,
6021 NULL, 0, 0, true);
6022 if (rc < 0) {
6023 pr_err("failed to store stream name in xattr: %d\n",
6024 rc);
6025 rc = -EINVAL;
6026 goto out;
6027 }
6028
6029 goto out;
6030 }
6031
6032 ksmbd_debug(SMB, "new name %s\n", new_name);
6033 if (ksmbd_share_veto_filename(share, new_name)) {
6034 rc = -ENOENT;
6035 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6036 goto out;
6037 }
6038
6039 if (!file_info->ReplaceIfExists)
6040 flags = RENAME_NOREPLACE;
6041
6042 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6043 if (!rc)
6044 smb_break_all_levII_oplock(work, fp, 0);
6045 out:
6046 kfree(new_name);
6047 return rc;
6048 }
6049
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)6050 static int smb2_create_link(struct ksmbd_work *work,
6051 struct ksmbd_share_config *share,
6052 struct smb2_file_link_info *file_info,
6053 unsigned int buf_len, struct file *filp,
6054 struct nls_table *local_nls)
6055 {
6056 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6057 struct path path;
6058 int rc;
6059
6060 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6061 le32_to_cpu(file_info->FileNameLength))
6062 return -EINVAL;
6063
6064 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6065 pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6066 if (!pathname)
6067 return -ENOMEM;
6068
6069 link_name = smb2_get_name(file_info->FileName,
6070 le32_to_cpu(file_info->FileNameLength),
6071 local_nls);
6072 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6073 rc = -EINVAL;
6074 goto out;
6075 }
6076
6077 ksmbd_debug(SMB, "link name is %s\n", link_name);
6078 target_name = file_path(filp, pathname, PATH_MAX);
6079 if (IS_ERR(target_name)) {
6080 rc = -EINVAL;
6081 goto out;
6082 }
6083
6084 ksmbd_debug(SMB, "target name is %s\n", target_name);
6085 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
6086 &path, 0);
6087 if (rc) {
6088 if (rc != -ENOENT)
6089 goto out;
6090 } else {
6091 if (file_info->ReplaceIfExists) {
6092 rc = ksmbd_vfs_remove_file(work, &path);
6093 if (rc) {
6094 rc = -EINVAL;
6095 ksmbd_debug(SMB, "cannot delete %s\n",
6096 link_name);
6097 goto out;
6098 }
6099 } else {
6100 rc = -EEXIST;
6101 ksmbd_debug(SMB, "link already exists\n");
6102 goto out;
6103 }
6104 ksmbd_vfs_kern_path_unlock(&path);
6105 }
6106 rc = ksmbd_vfs_link(work, target_name, link_name);
6107 if (rc)
6108 rc = -EINVAL;
6109 out:
6110
6111 if (!IS_ERR(link_name))
6112 kfree(link_name);
6113 kfree(pathname);
6114 return rc;
6115 }
6116
set_file_basic_info(struct ksmbd_file * fp,struct smb2_file_basic_info * file_info,struct ksmbd_share_config * share)6117 static int set_file_basic_info(struct ksmbd_file *fp,
6118 struct smb2_file_basic_info *file_info,
6119 struct ksmbd_share_config *share)
6120 {
6121 struct iattr attrs;
6122 struct file *filp;
6123 struct inode *inode;
6124 struct mnt_idmap *idmap;
6125 int rc = 0;
6126
6127 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6128 return -EACCES;
6129
6130 attrs.ia_valid = 0;
6131 filp = fp->filp;
6132 inode = file_inode(filp);
6133 idmap = file_mnt_idmap(filp);
6134
6135 if (file_info->CreationTime)
6136 fp->create_time = le64_to_cpu(file_info->CreationTime);
6137
6138 if (file_info->LastAccessTime) {
6139 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6140 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6141 }
6142
6143 if (file_info->ChangeTime)
6144 inode_set_ctime_to_ts(inode,
6145 ksmbd_NTtimeToUnix(file_info->ChangeTime));
6146
6147 if (file_info->LastWriteTime) {
6148 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6149 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6150 }
6151
6152 if (file_info->Attributes) {
6153 if (!S_ISDIR(inode->i_mode) &&
6154 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6155 pr_err("can't change a file to a directory\n");
6156 return -EINVAL;
6157 }
6158
6159 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6160 fp->f_ci->m_fattr = file_info->Attributes |
6161 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6162 }
6163
6164 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6165 (file_info->CreationTime || file_info->Attributes)) {
6166 struct xattr_dos_attrib da = {0};
6167
6168 da.version = 4;
6169 da.itime = fp->itime;
6170 da.create_time = fp->create_time;
6171 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6172 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6173 XATTR_DOSINFO_ITIME;
6174
6175 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6176 true);
6177 if (rc)
6178 ksmbd_debug(SMB,
6179 "failed to restore file attribute in EA\n");
6180 rc = 0;
6181 }
6182
6183 if (attrs.ia_valid) {
6184 struct dentry *dentry = filp->f_path.dentry;
6185 struct inode *inode = d_inode(dentry);
6186
6187 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6188 return -EACCES;
6189
6190 inode_lock(inode);
6191 rc = notify_change(idmap, dentry, &attrs, NULL);
6192 inode_unlock(inode);
6193 }
6194 return rc;
6195 }
6196
set_file_allocation_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_alloc_info * file_alloc_info)6197 static int set_file_allocation_info(struct ksmbd_work *work,
6198 struct ksmbd_file *fp,
6199 struct smb2_file_alloc_info *file_alloc_info)
6200 {
6201 /*
6202 * TODO : It's working fine only when store dos attributes
6203 * is not yes. need to implement a logic which works
6204 * properly with any smb.conf option
6205 */
6206
6207 loff_t alloc_blks;
6208 struct inode *inode;
6209 struct kstat stat;
6210 int rc;
6211
6212 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6213 return -EACCES;
6214
6215 if (ksmbd_stream_fd(fp) == true)
6216 return 0;
6217
6218 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6219 AT_STATX_SYNC_AS_STAT);
6220 if (rc)
6221 return rc;
6222
6223 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6224 inode = file_inode(fp->filp);
6225
6226 if (alloc_blks > stat.blocks) {
6227 smb_break_all_levII_oplock(work, fp, 1);
6228 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6229 alloc_blks * 512);
6230 if (rc && rc != -EOPNOTSUPP) {
6231 pr_err("vfs_fallocate is failed : %d\n", rc);
6232 return rc;
6233 }
6234 } else if (alloc_blks < stat.blocks) {
6235 loff_t size;
6236
6237 /*
6238 * Allocation size could be smaller than original one
6239 * which means allocated blocks in file should be
6240 * deallocated. use truncate to cut out it, but inode
6241 * size is also updated with truncate offset.
6242 * inode size is retained by backup inode size.
6243 */
6244 size = i_size_read(inode);
6245 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6246 if (rc) {
6247 pr_err("truncate failed!, err %d\n", rc);
6248 return rc;
6249 }
6250 if (size < alloc_blks * 512)
6251 i_size_write(inode, size);
6252 }
6253 return 0;
6254 }
6255
set_end_of_file_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_eof_info * file_eof_info)6256 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6257 struct smb2_file_eof_info *file_eof_info)
6258 {
6259 loff_t newsize;
6260 struct inode *inode;
6261 int rc;
6262
6263 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6264 return -EACCES;
6265
6266 newsize = le64_to_cpu(file_eof_info->EndOfFile);
6267 inode = file_inode(fp->filp);
6268
6269 /*
6270 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6271 * on FAT32 shared device, truncate execution time is too long
6272 * and network error could cause from windows client. because
6273 * truncate of some filesystem like FAT32 fill zero data in
6274 * truncated range.
6275 */
6276 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6277 ksmbd_stream_fd(fp) == false) {
6278 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6279 rc = ksmbd_vfs_truncate(work, fp, newsize);
6280 if (rc) {
6281 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6282 if (rc != -EAGAIN)
6283 rc = -EBADF;
6284 return rc;
6285 }
6286 }
6287 return 0;
6288 }
6289
set_rename_info(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_file_rename_info * rename_info,unsigned int buf_len)6290 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6291 struct smb2_file_rename_info *rename_info,
6292 unsigned int buf_len)
6293 {
6294 if (!(fp->daccess & FILE_DELETE_LE)) {
6295 pr_err("no right to delete : 0x%x\n", fp->daccess);
6296 return -EACCES;
6297 }
6298
6299 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6300 le32_to_cpu(rename_info->FileNameLength))
6301 return -EINVAL;
6302
6303 if (!le32_to_cpu(rename_info->FileNameLength))
6304 return -EINVAL;
6305
6306 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6307 }
6308
set_file_disposition_info(struct ksmbd_file * fp,struct smb2_file_disposition_info * file_info)6309 static int set_file_disposition_info(struct ksmbd_file *fp,
6310 struct smb2_file_disposition_info *file_info)
6311 {
6312 struct inode *inode;
6313
6314 if (!(fp->daccess & FILE_DELETE_LE)) {
6315 pr_err("no right to delete : 0x%x\n", fp->daccess);
6316 return -EACCES;
6317 }
6318
6319 inode = file_inode(fp->filp);
6320 if (file_info->DeletePending) {
6321 if (S_ISDIR(inode->i_mode) &&
6322 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6323 return -EBUSY;
6324 ksmbd_set_inode_pending_delete(fp);
6325 } else {
6326 ksmbd_clear_inode_pending_delete(fp);
6327 }
6328 return 0;
6329 }
6330
set_file_position_info(struct ksmbd_file * fp,struct smb2_file_pos_info * file_info)6331 static int set_file_position_info(struct ksmbd_file *fp,
6332 struct smb2_file_pos_info *file_info)
6333 {
6334 loff_t current_byte_offset;
6335 unsigned long sector_size;
6336 struct inode *inode;
6337
6338 inode = file_inode(fp->filp);
6339 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6340 sector_size = inode->i_sb->s_blocksize;
6341
6342 if (current_byte_offset < 0 ||
6343 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6344 current_byte_offset & (sector_size - 1))) {
6345 pr_err("CurrentByteOffset is not valid : %llu\n",
6346 current_byte_offset);
6347 return -EINVAL;
6348 }
6349
6350 if (ksmbd_stream_fd(fp) == false)
6351 fp->filp->f_pos = current_byte_offset;
6352 else {
6353 if (current_byte_offset > XATTR_SIZE_MAX)
6354 current_byte_offset = XATTR_SIZE_MAX;
6355 fp->stream.pos = current_byte_offset;
6356 }
6357 return 0;
6358 }
6359
set_file_mode_info(struct ksmbd_file * fp,struct smb2_file_mode_info * file_info)6360 static int set_file_mode_info(struct ksmbd_file *fp,
6361 struct smb2_file_mode_info *file_info)
6362 {
6363 __le32 mode;
6364
6365 mode = file_info->Mode;
6366
6367 if ((mode & ~FILE_MODE_INFO_MASK)) {
6368 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6369 return -EINVAL;
6370 }
6371
6372 /*
6373 * TODO : need to implement consideration for
6374 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6375 */
6376 ksmbd_vfs_set_fadvise(fp->filp, mode);
6377 fp->coption = mode;
6378 return 0;
6379 }
6380
6381 /**
6382 * smb2_set_info_file() - handler for smb2 set info command
6383 * @work: smb work containing set info command buffer
6384 * @fp: ksmbd_file pointer
6385 * @req: request buffer pointer
6386 * @share: ksmbd_share_config pointer
6387 *
6388 * Return: 0 on success, otherwise error
6389 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
6390 */
smb2_set_info_file(struct ksmbd_work * work,struct ksmbd_file * fp,struct smb2_set_info_req * req,struct ksmbd_share_config * share)6391 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6392 struct smb2_set_info_req *req,
6393 struct ksmbd_share_config *share)
6394 {
6395 unsigned int buf_len = le32_to_cpu(req->BufferLength);
6396 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6397
6398 switch (req->FileInfoClass) {
6399 case FILE_BASIC_INFORMATION:
6400 {
6401 if (buf_len < sizeof(struct smb2_file_basic_info))
6402 return -EINVAL;
6403
6404 return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6405 }
6406 case FILE_ALLOCATION_INFORMATION:
6407 {
6408 if (buf_len < sizeof(struct smb2_file_alloc_info))
6409 return -EINVAL;
6410
6411 return set_file_allocation_info(work, fp,
6412 (struct smb2_file_alloc_info *)buffer);
6413 }
6414 case FILE_END_OF_FILE_INFORMATION:
6415 {
6416 if (buf_len < sizeof(struct smb2_file_eof_info))
6417 return -EINVAL;
6418
6419 return set_end_of_file_info(work, fp,
6420 (struct smb2_file_eof_info *)buffer);
6421 }
6422 case FILE_RENAME_INFORMATION:
6423 {
6424 if (buf_len < sizeof(struct smb2_file_rename_info))
6425 return -EINVAL;
6426
6427 return set_rename_info(work, fp,
6428 (struct smb2_file_rename_info *)buffer,
6429 buf_len);
6430 }
6431 case FILE_LINK_INFORMATION:
6432 {
6433 if (buf_len < sizeof(struct smb2_file_link_info))
6434 return -EINVAL;
6435
6436 return smb2_create_link(work, work->tcon->share_conf,
6437 (struct smb2_file_link_info *)buffer,
6438 buf_len, fp->filp,
6439 work->conn->local_nls);
6440 }
6441 case FILE_DISPOSITION_INFORMATION:
6442 {
6443 if (buf_len < sizeof(struct smb2_file_disposition_info))
6444 return -EINVAL;
6445
6446 return set_file_disposition_info(fp,
6447 (struct smb2_file_disposition_info *)buffer);
6448 }
6449 case FILE_FULL_EA_INFORMATION:
6450 {
6451 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6452 pr_err("Not permitted to write ext attr: 0x%x\n",
6453 fp->daccess);
6454 return -EACCES;
6455 }
6456
6457 if (buf_len < sizeof(struct smb2_ea_info))
6458 return -EINVAL;
6459
6460 return smb2_set_ea((struct smb2_ea_info *)buffer,
6461 buf_len, &fp->filp->f_path, true);
6462 }
6463 case FILE_POSITION_INFORMATION:
6464 {
6465 if (buf_len < sizeof(struct smb2_file_pos_info))
6466 return -EINVAL;
6467
6468 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6469 }
6470 case FILE_MODE_INFORMATION:
6471 {
6472 if (buf_len < sizeof(struct smb2_file_mode_info))
6473 return -EINVAL;
6474
6475 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6476 }
6477 }
6478
6479 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6480 return -EOPNOTSUPP;
6481 }
6482
smb2_set_info_sec(struct ksmbd_file * fp,int addition_info,char * buffer,int buf_len)6483 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6484 char *buffer, int buf_len)
6485 {
6486 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6487
6488 fp->saccess |= FILE_SHARE_DELETE_LE;
6489
6490 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6491 buf_len, false, true);
6492 }
6493
6494 /**
6495 * smb2_set_info() - handler for smb2 set info command handler
6496 * @work: smb work containing set info request buffer
6497 *
6498 * Return: 0 on success, otherwise error
6499 */
smb2_set_info(struct ksmbd_work * work)6500 int smb2_set_info(struct ksmbd_work *work)
6501 {
6502 struct smb2_set_info_req *req;
6503 struct smb2_set_info_rsp *rsp;
6504 struct ksmbd_file *fp = NULL;
6505 int rc = 0;
6506 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6507
6508 ksmbd_debug(SMB, "Received smb2 set info request\n");
6509
6510 if (work->next_smb2_rcv_hdr_off) {
6511 req = ksmbd_req_buf_next(work);
6512 rsp = ksmbd_resp_buf_next(work);
6513 if (!has_file_id(req->VolatileFileId)) {
6514 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6515 work->compound_fid);
6516 id = work->compound_fid;
6517 pid = work->compound_pfid;
6518 }
6519 } else {
6520 req = smb2_get_msg(work->request_buf);
6521 rsp = smb2_get_msg(work->response_buf);
6522 }
6523
6524 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6525 ksmbd_debug(SMB, "User does not have write permission\n");
6526 pr_err("User does not have write permission\n");
6527 rc = -EACCES;
6528 goto err_out;
6529 }
6530
6531 if (!has_file_id(id)) {
6532 id = req->VolatileFileId;
6533 pid = req->PersistentFileId;
6534 }
6535
6536 fp = ksmbd_lookup_fd_slow(work, id, pid);
6537 if (!fp) {
6538 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6539 rc = -ENOENT;
6540 goto err_out;
6541 }
6542
6543 switch (req->InfoType) {
6544 case SMB2_O_INFO_FILE:
6545 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6546 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6547 break;
6548 case SMB2_O_INFO_SECURITY:
6549 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6550 if (ksmbd_override_fsids(work)) {
6551 rc = -ENOMEM;
6552 goto err_out;
6553 }
6554 rc = smb2_set_info_sec(fp,
6555 le32_to_cpu(req->AdditionalInformation),
6556 (char *)req + le16_to_cpu(req->BufferOffset),
6557 le32_to_cpu(req->BufferLength));
6558 ksmbd_revert_fsids(work);
6559 break;
6560 default:
6561 rc = -EOPNOTSUPP;
6562 }
6563
6564 if (rc < 0)
6565 goto err_out;
6566
6567 rsp->StructureSize = cpu_to_le16(2);
6568 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6569 sizeof(struct smb2_set_info_rsp));
6570 if (rc)
6571 goto err_out;
6572 ksmbd_fd_put(work, fp);
6573 return 0;
6574
6575 err_out:
6576 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6577 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6578 else if (rc == -EINVAL)
6579 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6580 else if (rc == -ESHARE)
6581 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6582 else if (rc == -ENOENT)
6583 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6584 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6585 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6586 else if (rc == -EAGAIN)
6587 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6588 else if (rc == -EBADF || rc == -ESTALE)
6589 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6590 else if (rc == -EEXIST)
6591 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6592 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6593 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6594 smb2_set_err_rsp(work);
6595 ksmbd_fd_put(work, fp);
6596 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6597 return rc;
6598 }
6599
6600 /**
6601 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6602 * @work: smb work containing read IPC pipe command buffer
6603 *
6604 * Return: 0 on success, otherwise error
6605 */
smb2_read_pipe(struct ksmbd_work * work)6606 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6607 {
6608 int nbytes = 0, err;
6609 u64 id;
6610 struct ksmbd_rpc_command *rpc_resp;
6611 struct smb2_read_req *req;
6612 struct smb2_read_rsp *rsp;
6613
6614 WORK_BUFFERS(work, req, rsp);
6615
6616 id = req->VolatileFileId;
6617
6618 rpc_resp = ksmbd_rpc_read(work->sess, id);
6619 if (rpc_resp) {
6620 void *aux_payload_buf;
6621
6622 if (rpc_resp->flags != KSMBD_RPC_OK) {
6623 err = -EINVAL;
6624 goto out;
6625 }
6626
6627 aux_payload_buf =
6628 kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
6629 if (!aux_payload_buf) {
6630 err = -ENOMEM;
6631 goto out;
6632 }
6633
6634 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6635
6636 nbytes = rpc_resp->payload_sz;
6637 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6638 offsetof(struct smb2_read_rsp, Buffer),
6639 aux_payload_buf, nbytes);
6640 if (err) {
6641 kvfree(aux_payload_buf);
6642 goto out;
6643 }
6644 kvfree(rpc_resp);
6645 } else {
6646 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6647 offsetof(struct smb2_read_rsp, Buffer));
6648 if (err)
6649 goto out;
6650 }
6651
6652 rsp->StructureSize = cpu_to_le16(17);
6653 rsp->DataOffset = 80;
6654 rsp->Reserved = 0;
6655 rsp->DataLength = cpu_to_le32(nbytes);
6656 rsp->DataRemaining = 0;
6657 rsp->Flags = 0;
6658 return 0;
6659
6660 out:
6661 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6662 smb2_set_err_rsp(work);
6663 kvfree(rpc_resp);
6664 return err;
6665 }
6666
smb2_set_remote_key_for_rdma(struct ksmbd_work * work,struct smb2_buffer_desc_v1 * desc,__le32 Channel,__le16 ChannelInfoLength)6667 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6668 struct smb2_buffer_desc_v1 *desc,
6669 __le32 Channel,
6670 __le16 ChannelInfoLength)
6671 {
6672 unsigned int i, ch_count;
6673
6674 if (work->conn->dialect == SMB30_PROT_ID &&
6675 Channel != SMB2_CHANNEL_RDMA_V1)
6676 return -EINVAL;
6677
6678 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6679 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6680 for (i = 0; i < ch_count; i++) {
6681 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6682 i,
6683 le32_to_cpu(desc[i].token),
6684 le32_to_cpu(desc[i].length));
6685 }
6686 }
6687 if (!ch_count)
6688 return -EINVAL;
6689
6690 work->need_invalidate_rkey =
6691 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6692 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6693 work->remote_key = le32_to_cpu(desc->token);
6694 return 0;
6695 }
6696
smb2_read_rdma_channel(struct ksmbd_work * work,struct smb2_read_req * req,void * data_buf,size_t length)6697 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6698 struct smb2_read_req *req, void *data_buf,
6699 size_t length)
6700 {
6701 int err;
6702
6703 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6704 (struct smb2_buffer_desc_v1 *)
6705 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6706 le16_to_cpu(req->ReadChannelInfoLength));
6707 if (err)
6708 return err;
6709
6710 return length;
6711 }
6712
6713 /**
6714 * smb2_read() - handler for smb2 read from file
6715 * @work: smb work containing read command buffer
6716 *
6717 * Return: 0 on success, otherwise error
6718 */
smb2_read(struct ksmbd_work * work)6719 int smb2_read(struct ksmbd_work *work)
6720 {
6721 struct ksmbd_conn *conn = work->conn;
6722 struct smb2_read_req *req;
6723 struct smb2_read_rsp *rsp;
6724 struct ksmbd_file *fp = NULL;
6725 loff_t offset;
6726 size_t length, mincount;
6727 ssize_t nbytes = 0, remain_bytes = 0;
6728 int err = 0;
6729 bool is_rdma_channel = false;
6730 unsigned int max_read_size = conn->vals->max_read_size;
6731 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6732 void *aux_payload_buf;
6733
6734 ksmbd_debug(SMB, "Received smb2 read request\n");
6735
6736 if (test_share_config_flag(work->tcon->share_conf,
6737 KSMBD_SHARE_FLAG_PIPE)) {
6738 ksmbd_debug(SMB, "IPC pipe read request\n");
6739 return smb2_read_pipe(work);
6740 }
6741
6742 if (work->next_smb2_rcv_hdr_off) {
6743 req = ksmbd_req_buf_next(work);
6744 rsp = ksmbd_resp_buf_next(work);
6745 if (!has_file_id(req->VolatileFileId)) {
6746 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6747 work->compound_fid);
6748 id = work->compound_fid;
6749 pid = work->compound_pfid;
6750 }
6751 } else {
6752 req = smb2_get_msg(work->request_buf);
6753 rsp = smb2_get_msg(work->response_buf);
6754 }
6755
6756 if (!has_file_id(id)) {
6757 id = req->VolatileFileId;
6758 pid = req->PersistentFileId;
6759 }
6760
6761 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6762 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6763 is_rdma_channel = true;
6764 max_read_size = get_smbd_max_read_write_size();
6765 }
6766
6767 if (is_rdma_channel == true) {
6768 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6769
6770 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6771 err = -EINVAL;
6772 goto out;
6773 }
6774 err = smb2_set_remote_key_for_rdma(work,
6775 (struct smb2_buffer_desc_v1 *)
6776 ((char *)req + ch_offset),
6777 req->Channel,
6778 req->ReadChannelInfoLength);
6779 if (err)
6780 goto out;
6781 }
6782
6783 fp = ksmbd_lookup_fd_slow(work, id, pid);
6784 if (!fp) {
6785 err = -ENOENT;
6786 goto out;
6787 }
6788
6789 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6790 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6791 err = -EACCES;
6792 goto out;
6793 }
6794
6795 offset = le64_to_cpu(req->Offset);
6796 if (offset < 0) {
6797 err = -EINVAL;
6798 goto out;
6799 }
6800 length = le32_to_cpu(req->Length);
6801 mincount = le32_to_cpu(req->MinimumCount);
6802
6803 if (length > max_read_size) {
6804 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6805 max_read_size);
6806 err = -EINVAL;
6807 goto out;
6808 }
6809
6810 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6811 fp->filp, offset, length);
6812
6813 aux_payload_buf = kvzalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
6814 if (!aux_payload_buf) {
6815 err = -ENOMEM;
6816 goto out;
6817 }
6818
6819 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6820 if (nbytes < 0) {
6821 err = nbytes;
6822 goto out;
6823 }
6824
6825 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6826 kvfree(aux_payload_buf);
6827 rsp->hdr.Status = STATUS_END_OF_FILE;
6828 smb2_set_err_rsp(work);
6829 ksmbd_fd_put(work, fp);
6830 return 0;
6831 }
6832
6833 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6834 nbytes, offset, mincount);
6835
6836 if (is_rdma_channel == true) {
6837 /* write data to the client using rdma channel */
6838 remain_bytes = smb2_read_rdma_channel(work, req,
6839 aux_payload_buf,
6840 nbytes);
6841 kvfree(aux_payload_buf);
6842 aux_payload_buf = NULL;
6843 nbytes = 0;
6844 if (remain_bytes < 0) {
6845 err = (int)remain_bytes;
6846 goto out;
6847 }
6848 }
6849
6850 rsp->StructureSize = cpu_to_le16(17);
6851 rsp->DataOffset = 80;
6852 rsp->Reserved = 0;
6853 rsp->DataLength = cpu_to_le32(nbytes);
6854 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6855 rsp->Flags = 0;
6856 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6857 offsetof(struct smb2_read_rsp, Buffer),
6858 aux_payload_buf, nbytes);
6859 if (err) {
6860 kvfree(aux_payload_buf);
6861 goto out;
6862 }
6863 ksmbd_fd_put(work, fp);
6864 return 0;
6865
6866 out:
6867 if (err) {
6868 if (err == -EISDIR)
6869 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6870 else if (err == -EAGAIN)
6871 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6872 else if (err == -ENOENT)
6873 rsp->hdr.Status = STATUS_FILE_CLOSED;
6874 else if (err == -EACCES)
6875 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6876 else if (err == -ESHARE)
6877 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6878 else if (err == -EINVAL)
6879 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6880 else
6881 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6882
6883 smb2_set_err_rsp(work);
6884 }
6885 ksmbd_fd_put(work, fp);
6886 return err;
6887 }
6888
6889 /**
6890 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6891 * @work: smb work containing write IPC pipe command buffer
6892 *
6893 * Return: 0 on success, otherwise error
6894 */
smb2_write_pipe(struct ksmbd_work * work)6895 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6896 {
6897 struct smb2_write_req *req;
6898 struct smb2_write_rsp *rsp;
6899 struct ksmbd_rpc_command *rpc_resp;
6900 u64 id = 0;
6901 int err = 0, ret = 0;
6902 char *data_buf;
6903 size_t length;
6904
6905 WORK_BUFFERS(work, req, rsp);
6906
6907 length = le32_to_cpu(req->Length);
6908 id = req->VolatileFileId;
6909
6910 if ((u64)le16_to_cpu(req->DataOffset) + length >
6911 get_rfc1002_len(work->request_buf)) {
6912 pr_err("invalid write data offset %u, smb_len %u\n",
6913 le16_to_cpu(req->DataOffset),
6914 get_rfc1002_len(work->request_buf));
6915 err = -EINVAL;
6916 goto out;
6917 }
6918
6919 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6920 le16_to_cpu(req->DataOffset));
6921
6922 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6923 if (rpc_resp) {
6924 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6925 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6926 kvfree(rpc_resp);
6927 smb2_set_err_rsp(work);
6928 return -EOPNOTSUPP;
6929 }
6930 if (rpc_resp->flags != KSMBD_RPC_OK) {
6931 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6932 smb2_set_err_rsp(work);
6933 kvfree(rpc_resp);
6934 return ret;
6935 }
6936 kvfree(rpc_resp);
6937 }
6938
6939 rsp->StructureSize = cpu_to_le16(17);
6940 rsp->DataOffset = 0;
6941 rsp->Reserved = 0;
6942 rsp->DataLength = cpu_to_le32(length);
6943 rsp->DataRemaining = 0;
6944 rsp->Reserved2 = 0;
6945 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6946 offsetof(struct smb2_write_rsp, Buffer));
6947 out:
6948 if (err) {
6949 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6950 smb2_set_err_rsp(work);
6951 }
6952
6953 return err;
6954 }
6955
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)6956 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6957 struct smb2_write_req *req,
6958 struct ksmbd_file *fp,
6959 loff_t offset, size_t length, bool sync)
6960 {
6961 char *data_buf;
6962 int ret;
6963 ssize_t nbytes;
6964
6965 data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
6966 if (!data_buf)
6967 return -ENOMEM;
6968
6969 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6970 (struct smb2_buffer_desc_v1 *)
6971 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6972 le16_to_cpu(req->WriteChannelInfoLength));
6973 if (ret < 0) {
6974 kvfree(data_buf);
6975 return ret;
6976 }
6977
6978 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6979 kvfree(data_buf);
6980 if (ret < 0)
6981 return ret;
6982
6983 return nbytes;
6984 }
6985
6986 /**
6987 * smb2_write() - handler for smb2 write from file
6988 * @work: smb work containing write command buffer
6989 *
6990 * Return: 0 on success, otherwise error
6991 */
smb2_write(struct ksmbd_work * work)6992 int smb2_write(struct ksmbd_work *work)
6993 {
6994 struct smb2_write_req *req;
6995 struct smb2_write_rsp *rsp;
6996 struct ksmbd_file *fp = NULL;
6997 loff_t offset;
6998 size_t length;
6999 ssize_t nbytes;
7000 char *data_buf;
7001 bool writethrough = false, is_rdma_channel = false;
7002 int err = 0;
7003 unsigned int max_write_size = work->conn->vals->max_write_size;
7004
7005 ksmbd_debug(SMB, "Received smb2 write request\n");
7006
7007 WORK_BUFFERS(work, req, rsp);
7008
7009 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7010 ksmbd_debug(SMB, "IPC pipe write request\n");
7011 return smb2_write_pipe(work);
7012 }
7013
7014 offset = le64_to_cpu(req->Offset);
7015 if (offset < 0)
7016 return -EINVAL;
7017 length = le32_to_cpu(req->Length);
7018
7019 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7020 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7021 is_rdma_channel = true;
7022 max_write_size = get_smbd_max_read_write_size();
7023 length = le32_to_cpu(req->RemainingBytes);
7024 }
7025
7026 if (is_rdma_channel == true) {
7027 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7028
7029 if (req->Length != 0 || req->DataOffset != 0 ||
7030 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7031 err = -EINVAL;
7032 goto out;
7033 }
7034 err = smb2_set_remote_key_for_rdma(work,
7035 (struct smb2_buffer_desc_v1 *)
7036 ((char *)req + ch_offset),
7037 req->Channel,
7038 req->WriteChannelInfoLength);
7039 if (err)
7040 goto out;
7041 }
7042
7043 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7044 ksmbd_debug(SMB, "User does not have write permission\n");
7045 err = -EACCES;
7046 goto out;
7047 }
7048
7049 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7050 if (!fp) {
7051 err = -ENOENT;
7052 goto out;
7053 }
7054
7055 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7056 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7057 err = -EACCES;
7058 goto out;
7059 }
7060
7061 if (length > max_write_size) {
7062 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7063 max_write_size);
7064 err = -EINVAL;
7065 goto out;
7066 }
7067
7068 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7069 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7070 writethrough = true;
7071
7072 if (is_rdma_channel == false) {
7073 if (le16_to_cpu(req->DataOffset) <
7074 offsetof(struct smb2_write_req, Buffer)) {
7075 err = -EINVAL;
7076 goto out;
7077 }
7078
7079 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7080 le16_to_cpu(req->DataOffset));
7081
7082 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7083 fp->filp, offset, length);
7084 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7085 writethrough, &nbytes);
7086 if (err < 0)
7087 goto out;
7088 } else {
7089 /* read data from the client using rdma channel, and
7090 * write the data.
7091 */
7092 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7093 writethrough);
7094 if (nbytes < 0) {
7095 err = (int)nbytes;
7096 goto out;
7097 }
7098 }
7099
7100 rsp->StructureSize = cpu_to_le16(17);
7101 rsp->DataOffset = 0;
7102 rsp->Reserved = 0;
7103 rsp->DataLength = cpu_to_le32(nbytes);
7104 rsp->DataRemaining = 0;
7105 rsp->Reserved2 = 0;
7106 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7107 if (err)
7108 goto out;
7109 ksmbd_fd_put(work, fp);
7110 return 0;
7111
7112 out:
7113 if (err == -EAGAIN)
7114 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7115 else if (err == -ENOSPC || err == -EFBIG)
7116 rsp->hdr.Status = STATUS_DISK_FULL;
7117 else if (err == -ENOENT)
7118 rsp->hdr.Status = STATUS_FILE_CLOSED;
7119 else if (err == -EACCES)
7120 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7121 else if (err == -ESHARE)
7122 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7123 else if (err == -EINVAL)
7124 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7125 else
7126 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7127
7128 smb2_set_err_rsp(work);
7129 ksmbd_fd_put(work, fp);
7130 return err;
7131 }
7132
7133 /**
7134 * smb2_flush() - handler for smb2 flush file - fsync
7135 * @work: smb work containing flush command buffer
7136 *
7137 * Return: 0 on success, otherwise error
7138 */
smb2_flush(struct ksmbd_work * work)7139 int smb2_flush(struct ksmbd_work *work)
7140 {
7141 struct smb2_flush_req *req;
7142 struct smb2_flush_rsp *rsp;
7143 int err;
7144
7145 WORK_BUFFERS(work, req, rsp);
7146
7147 ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7148
7149 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
7150 if (err)
7151 goto out;
7152
7153 rsp->StructureSize = cpu_to_le16(4);
7154 rsp->Reserved = 0;
7155 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7156
7157 out:
7158 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7159 smb2_set_err_rsp(work);
7160 return err;
7161 }
7162
7163 /**
7164 * smb2_cancel() - handler for smb2 cancel command
7165 * @work: smb work containing cancel command buffer
7166 *
7167 * Return: 0 on success, otherwise error
7168 */
smb2_cancel(struct ksmbd_work * work)7169 int smb2_cancel(struct ksmbd_work *work)
7170 {
7171 struct ksmbd_conn *conn = work->conn;
7172 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
7173 struct smb2_hdr *chdr;
7174 struct ksmbd_work *iter;
7175 struct list_head *command_list;
7176
7177 if (work->next_smb2_rcv_hdr_off)
7178 hdr = ksmbd_resp_buf_next(work);
7179
7180 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7181 hdr->MessageId, hdr->Flags);
7182
7183 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7184 command_list = &conn->async_requests;
7185
7186 spin_lock(&conn->request_lock);
7187 list_for_each_entry(iter, command_list,
7188 async_request_entry) {
7189 chdr = smb2_get_msg(iter->request_buf);
7190
7191 if (iter->async_id !=
7192 le64_to_cpu(hdr->Id.AsyncId))
7193 continue;
7194
7195 ksmbd_debug(SMB,
7196 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7197 le64_to_cpu(hdr->Id.AsyncId),
7198 le16_to_cpu(chdr->Command));
7199 iter->state = KSMBD_WORK_CANCELLED;
7200 if (iter->cancel_fn)
7201 iter->cancel_fn(iter->cancel_argv);
7202 break;
7203 }
7204 spin_unlock(&conn->request_lock);
7205 } else {
7206 command_list = &conn->requests;
7207
7208 spin_lock(&conn->request_lock);
7209 list_for_each_entry(iter, command_list, request_entry) {
7210 chdr = smb2_get_msg(iter->request_buf);
7211
7212 if (chdr->MessageId != hdr->MessageId ||
7213 iter == work)
7214 continue;
7215
7216 ksmbd_debug(SMB,
7217 "smb2 with mid %llu cancelled command = 0x%x\n",
7218 le64_to_cpu(hdr->MessageId),
7219 le16_to_cpu(chdr->Command));
7220 iter->state = KSMBD_WORK_CANCELLED;
7221 break;
7222 }
7223 spin_unlock(&conn->request_lock);
7224 }
7225
7226 /* For SMB2_CANCEL command itself send no response*/
7227 work->send_no_response = 1;
7228 return 0;
7229 }
7230
smb_flock_init(struct file * f)7231 struct file_lock *smb_flock_init(struct file *f)
7232 {
7233 struct file_lock *fl;
7234
7235 fl = locks_alloc_lock();
7236 if (!fl)
7237 goto out;
7238
7239 locks_init_lock(fl);
7240
7241 fl->c.flc_owner = f;
7242 fl->c.flc_pid = current->tgid;
7243 fl->c.flc_file = f;
7244 fl->c.flc_flags = FL_POSIX;
7245 fl->fl_ops = NULL;
7246 fl->fl_lmops = NULL;
7247
7248 out:
7249 return fl;
7250 }
7251
smb2_set_flock_flags(struct file_lock * flock,int flags)7252 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7253 {
7254 int cmd = -EINVAL;
7255
7256 /* Checking for wrong flag combination during lock request*/
7257 switch (flags) {
7258 case SMB2_LOCKFLAG_SHARED:
7259 ksmbd_debug(SMB, "received shared request\n");
7260 cmd = F_SETLKW;
7261 flock->c.flc_type = F_RDLCK;
7262 flock->c.flc_flags |= FL_SLEEP;
7263 break;
7264 case SMB2_LOCKFLAG_EXCLUSIVE:
7265 ksmbd_debug(SMB, "received exclusive request\n");
7266 cmd = F_SETLKW;
7267 flock->c.flc_type = F_WRLCK;
7268 flock->c.flc_flags |= FL_SLEEP;
7269 break;
7270 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7271 ksmbd_debug(SMB,
7272 "received shared & fail immediately request\n");
7273 cmd = F_SETLK;
7274 flock->c.flc_type = F_RDLCK;
7275 break;
7276 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7277 ksmbd_debug(SMB,
7278 "received exclusive & fail immediately request\n");
7279 cmd = F_SETLK;
7280 flock->c.flc_type = F_WRLCK;
7281 break;
7282 case SMB2_LOCKFLAG_UNLOCK:
7283 ksmbd_debug(SMB, "received unlock request\n");
7284 flock->c.flc_type = F_UNLCK;
7285 cmd = F_SETLK;
7286 break;
7287 }
7288
7289 return cmd;
7290 }
7291
smb2_lock_init(struct file_lock * flock,unsigned int cmd,int flags,struct list_head * lock_list)7292 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7293 unsigned int cmd, int flags,
7294 struct list_head *lock_list)
7295 {
7296 struct ksmbd_lock *lock;
7297
7298 lock = kzalloc(sizeof(struct ksmbd_lock), KSMBD_DEFAULT_GFP);
7299 if (!lock)
7300 return NULL;
7301
7302 lock->cmd = cmd;
7303 lock->fl = flock;
7304 lock->start = flock->fl_start;
7305 lock->end = flock->fl_end;
7306 lock->flags = flags;
7307 if (lock->start == lock->end)
7308 lock->zero_len = 1;
7309 INIT_LIST_HEAD(&lock->clist);
7310 INIT_LIST_HEAD(&lock->flist);
7311 INIT_LIST_HEAD(&lock->llist);
7312 list_add_tail(&lock->llist, lock_list);
7313
7314 return lock;
7315 }
7316
smb2_remove_blocked_lock(void ** argv)7317 static void smb2_remove_blocked_lock(void **argv)
7318 {
7319 struct file_lock *flock = (struct file_lock *)argv[0];
7320
7321 ksmbd_vfs_posix_lock_unblock(flock);
7322 locks_wake_up(flock);
7323 }
7324
lock_defer_pending(struct file_lock * fl)7325 static inline bool lock_defer_pending(struct file_lock *fl)
7326 {
7327 /* check pending lock waiters */
7328 return waitqueue_active(&fl->c.flc_wait);
7329 }
7330
7331 /**
7332 * smb2_lock() - handler for smb2 file lock command
7333 * @work: smb work containing lock command buffer
7334 *
7335 * Return: 0 on success, otherwise error
7336 */
smb2_lock(struct ksmbd_work * work)7337 int smb2_lock(struct ksmbd_work *work)
7338 {
7339 struct smb2_lock_req *req;
7340 struct smb2_lock_rsp *rsp;
7341 struct smb2_lock_element *lock_ele;
7342 struct ksmbd_file *fp = NULL;
7343 struct file_lock *flock = NULL;
7344 struct file *filp = NULL;
7345 int lock_count;
7346 int flags = 0;
7347 int cmd = 0;
7348 int err = -EIO, i, rc = 0;
7349 u64 lock_start, lock_length;
7350 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7351 struct ksmbd_conn *conn;
7352 int nolock = 0;
7353 LIST_HEAD(lock_list);
7354 LIST_HEAD(rollback_list);
7355 int prior_lock = 0;
7356
7357 WORK_BUFFERS(work, req, rsp);
7358
7359 ksmbd_debug(SMB, "Received smb2 lock request\n");
7360 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7361 if (!fp) {
7362 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7363 err = -ENOENT;
7364 goto out2;
7365 }
7366
7367 filp = fp->filp;
7368 lock_count = le16_to_cpu(req->LockCount);
7369 lock_ele = req->locks;
7370
7371 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7372 if (!lock_count) {
7373 err = -EINVAL;
7374 goto out2;
7375 }
7376
7377 for (i = 0; i < lock_count; i++) {
7378 flags = le32_to_cpu(lock_ele[i].Flags);
7379
7380 flock = smb_flock_init(filp);
7381 if (!flock)
7382 goto out;
7383
7384 cmd = smb2_set_flock_flags(flock, flags);
7385
7386 lock_start = le64_to_cpu(lock_ele[i].Offset);
7387 lock_length = le64_to_cpu(lock_ele[i].Length);
7388 if (lock_start > U64_MAX - lock_length) {
7389 pr_err("Invalid lock range requested\n");
7390 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7391 locks_free_lock(flock);
7392 goto out;
7393 }
7394
7395 if (lock_start > OFFSET_MAX)
7396 flock->fl_start = OFFSET_MAX;
7397 else
7398 flock->fl_start = lock_start;
7399
7400 lock_length = le64_to_cpu(lock_ele[i].Length);
7401 if (lock_length > OFFSET_MAX - flock->fl_start)
7402 lock_length = OFFSET_MAX - flock->fl_start;
7403
7404 flock->fl_end = flock->fl_start + lock_length;
7405
7406 if (flock->fl_end < flock->fl_start) {
7407 ksmbd_debug(SMB,
7408 "the end offset(%llx) is smaller than the start offset(%llx)\n",
7409 flock->fl_end, flock->fl_start);
7410 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7411 locks_free_lock(flock);
7412 goto out;
7413 }
7414
7415 /* Check conflict locks in one request */
7416 list_for_each_entry(cmp_lock, &lock_list, llist) {
7417 if (cmp_lock->fl->fl_start <= flock->fl_start &&
7418 cmp_lock->fl->fl_end >= flock->fl_end) {
7419 if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7420 flock->c.flc_type != F_UNLCK) {
7421 pr_err("conflict two locks in one request\n");
7422 err = -EINVAL;
7423 locks_free_lock(flock);
7424 goto out;
7425 }
7426 }
7427 }
7428
7429 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7430 if (!smb_lock) {
7431 err = -EINVAL;
7432 locks_free_lock(flock);
7433 goto out;
7434 }
7435 }
7436
7437 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7438 if (smb_lock->cmd < 0) {
7439 err = -EINVAL;
7440 goto out;
7441 }
7442
7443 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7444 err = -EINVAL;
7445 goto out;
7446 }
7447
7448 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7449 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7450 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7451 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7452 err = -EINVAL;
7453 goto out;
7454 }
7455
7456 prior_lock = smb_lock->flags;
7457
7458 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7459 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7460 goto no_check_cl;
7461
7462 nolock = 1;
7463 /* check locks in connection list */
7464 down_read(&conn_list_lock);
7465 list_for_each_entry(conn, &conn_list, conns_list) {
7466 spin_lock(&conn->llist_lock);
7467 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7468 if (file_inode(cmp_lock->fl->c.flc_file) !=
7469 file_inode(smb_lock->fl->c.flc_file))
7470 continue;
7471
7472 if (lock_is_unlock(smb_lock->fl)) {
7473 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7474 cmp_lock->start == smb_lock->start &&
7475 cmp_lock->end == smb_lock->end &&
7476 !lock_defer_pending(cmp_lock->fl)) {
7477 nolock = 0;
7478 list_del(&cmp_lock->flist);
7479 list_del(&cmp_lock->clist);
7480 spin_unlock(&conn->llist_lock);
7481 up_read(&conn_list_lock);
7482
7483 locks_free_lock(cmp_lock->fl);
7484 kfree(cmp_lock);
7485 goto out_check_cl;
7486 }
7487 continue;
7488 }
7489
7490 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7491 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7492 continue;
7493 } else {
7494 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7495 continue;
7496 }
7497
7498 /* check zero byte lock range */
7499 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7500 cmp_lock->start > smb_lock->start &&
7501 cmp_lock->start < smb_lock->end) {
7502 spin_unlock(&conn->llist_lock);
7503 up_read(&conn_list_lock);
7504 pr_err("previous lock conflict with zero byte lock range\n");
7505 goto out;
7506 }
7507
7508 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7509 smb_lock->start > cmp_lock->start &&
7510 smb_lock->start < cmp_lock->end) {
7511 spin_unlock(&conn->llist_lock);
7512 up_read(&conn_list_lock);
7513 pr_err("current lock conflict with zero byte lock range\n");
7514 goto out;
7515 }
7516
7517 if (((cmp_lock->start <= smb_lock->start &&
7518 cmp_lock->end > smb_lock->start) ||
7519 (cmp_lock->start < smb_lock->end &&
7520 cmp_lock->end >= smb_lock->end)) &&
7521 !cmp_lock->zero_len && !smb_lock->zero_len) {
7522 spin_unlock(&conn->llist_lock);
7523 up_read(&conn_list_lock);
7524 pr_err("Not allow lock operation on exclusive lock range\n");
7525 goto out;
7526 }
7527 }
7528 spin_unlock(&conn->llist_lock);
7529 }
7530 up_read(&conn_list_lock);
7531 out_check_cl:
7532 if (lock_is_unlock(smb_lock->fl) && nolock) {
7533 pr_err("Try to unlock nolocked range\n");
7534 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7535 goto out;
7536 }
7537
7538 no_check_cl:
7539 flock = smb_lock->fl;
7540 list_del(&smb_lock->llist);
7541
7542 if (smb_lock->zero_len) {
7543 err = 0;
7544 goto skip;
7545 }
7546 retry:
7547 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7548 skip:
7549 if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
7550 if (!rc) {
7551 ksmbd_debug(SMB, "File unlocked\n");
7552 } else if (rc == -ENOENT) {
7553 rsp->hdr.Status = STATUS_NOT_LOCKED;
7554 goto out;
7555 }
7556 locks_free_lock(flock);
7557 kfree(smb_lock);
7558 } else {
7559 if (rc == FILE_LOCK_DEFERRED) {
7560 void **argv;
7561
7562 ksmbd_debug(SMB,
7563 "would have to wait for getting lock\n");
7564 list_add(&smb_lock->llist, &rollback_list);
7565
7566 argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
7567 if (!argv) {
7568 err = -ENOMEM;
7569 goto out;
7570 }
7571 argv[0] = flock;
7572
7573 rc = setup_async_work(work,
7574 smb2_remove_blocked_lock,
7575 argv);
7576 if (rc) {
7577 kfree(argv);
7578 err = -ENOMEM;
7579 goto out;
7580 }
7581 spin_lock(&fp->f_lock);
7582 list_add(&work->fp_entry, &fp->blocked_works);
7583 spin_unlock(&fp->f_lock);
7584
7585 smb2_send_interim_resp(work, STATUS_PENDING);
7586
7587 ksmbd_vfs_posix_lock_wait(flock);
7588
7589 spin_lock(&fp->f_lock);
7590 list_del(&work->fp_entry);
7591 spin_unlock(&fp->f_lock);
7592
7593 if (work->state != KSMBD_WORK_ACTIVE) {
7594 list_del(&smb_lock->llist);
7595 locks_free_lock(flock);
7596
7597 if (work->state == KSMBD_WORK_CANCELLED) {
7598 rsp->hdr.Status =
7599 STATUS_CANCELLED;
7600 kfree(smb_lock);
7601 smb2_send_interim_resp(work,
7602 STATUS_CANCELLED);
7603 work->send_no_response = 1;
7604 goto out;
7605 }
7606
7607 rsp->hdr.Status =
7608 STATUS_RANGE_NOT_LOCKED;
7609 kfree(smb_lock);
7610 goto out2;
7611 }
7612
7613 list_del(&smb_lock->llist);
7614 release_async_work(work);
7615 goto retry;
7616 } else if (!rc) {
7617 list_add(&smb_lock->llist, &rollback_list);
7618 spin_lock(&work->conn->llist_lock);
7619 list_add_tail(&smb_lock->clist,
7620 &work->conn->lock_list);
7621 list_add_tail(&smb_lock->flist,
7622 &fp->lock_list);
7623 spin_unlock(&work->conn->llist_lock);
7624 ksmbd_debug(SMB, "successful in taking lock\n");
7625 } else {
7626 goto out;
7627 }
7628 }
7629 }
7630
7631 if (atomic_read(&fp->f_ci->op_count) > 1)
7632 smb_break_all_oplock(work, fp);
7633
7634 rsp->StructureSize = cpu_to_le16(4);
7635 ksmbd_debug(SMB, "successful in taking lock\n");
7636 rsp->hdr.Status = STATUS_SUCCESS;
7637 rsp->Reserved = 0;
7638 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7639 if (err)
7640 goto out;
7641
7642 ksmbd_fd_put(work, fp);
7643 return 0;
7644
7645 out:
7646 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7647 locks_free_lock(smb_lock->fl);
7648 list_del(&smb_lock->llist);
7649 kfree(smb_lock);
7650 }
7651
7652 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7653 struct file_lock *rlock = NULL;
7654
7655 rlock = smb_flock_init(filp);
7656 rlock->c.flc_type = F_UNLCK;
7657 rlock->fl_start = smb_lock->start;
7658 rlock->fl_end = smb_lock->end;
7659
7660 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7661 if (rc)
7662 pr_err("rollback unlock fail : %d\n", rc);
7663
7664 list_del(&smb_lock->llist);
7665 spin_lock(&work->conn->llist_lock);
7666 if (!list_empty(&smb_lock->flist))
7667 list_del(&smb_lock->flist);
7668 list_del(&smb_lock->clist);
7669 spin_unlock(&work->conn->llist_lock);
7670
7671 locks_free_lock(smb_lock->fl);
7672 locks_free_lock(rlock);
7673 kfree(smb_lock);
7674 }
7675 out2:
7676 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7677
7678 if (!rsp->hdr.Status) {
7679 if (err == -EINVAL)
7680 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7681 else if (err == -ENOMEM)
7682 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7683 else if (err == -ENOENT)
7684 rsp->hdr.Status = STATUS_FILE_CLOSED;
7685 else
7686 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7687 }
7688
7689 smb2_set_err_rsp(work);
7690 ksmbd_fd_put(work, fp);
7691 return err;
7692 }
7693
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)7694 static int fsctl_copychunk(struct ksmbd_work *work,
7695 struct copychunk_ioctl_req *ci_req,
7696 unsigned int cnt_code,
7697 unsigned int input_count,
7698 unsigned long long volatile_id,
7699 unsigned long long persistent_id,
7700 struct smb2_ioctl_rsp *rsp)
7701 {
7702 struct copychunk_ioctl_rsp *ci_rsp;
7703 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7704 struct srv_copychunk *chunks;
7705 unsigned int i, chunk_count, chunk_count_written = 0;
7706 unsigned int chunk_size_written = 0;
7707 loff_t total_size_written = 0;
7708 int ret = 0;
7709
7710 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7711
7712 rsp->VolatileFileId = volatile_id;
7713 rsp->PersistentFileId = persistent_id;
7714 ci_rsp->ChunksWritten =
7715 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7716 ci_rsp->ChunkBytesWritten =
7717 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7718 ci_rsp->TotalBytesWritten =
7719 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7720
7721 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7722 if (chunk_count == 0)
7723 goto out;
7724 total_size_written = 0;
7725
7726 /* verify the SRV_COPYCHUNK_COPY packet */
7727 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7728 input_count < struct_size(ci_req, Chunks, chunk_count)) {
7729 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7730 return -EINVAL;
7731 }
7732
7733 chunks = &ci_req->Chunks[0];
7734 for (i = 0; i < chunk_count; i++) {
7735 if (le32_to_cpu(chunks[i].Length) == 0 ||
7736 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7737 break;
7738 total_size_written += le32_to_cpu(chunks[i].Length);
7739 }
7740
7741 if (i < chunk_count ||
7742 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7743 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7744 return -EINVAL;
7745 }
7746
7747 src_fp = ksmbd_lookup_foreign_fd(work,
7748 le64_to_cpu(ci_req->ResumeKey[0]));
7749 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7750 ret = -EINVAL;
7751 if (!src_fp ||
7752 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7753 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7754 goto out;
7755 }
7756
7757 if (!dst_fp) {
7758 rsp->hdr.Status = STATUS_FILE_CLOSED;
7759 goto out;
7760 }
7761
7762 /*
7763 * FILE_READ_DATA should only be included in
7764 * the FSCTL_COPYCHUNK case
7765 */
7766 if (cnt_code == FSCTL_COPYCHUNK &&
7767 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7768 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7769 goto out;
7770 }
7771
7772 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7773 chunks, chunk_count,
7774 &chunk_count_written,
7775 &chunk_size_written,
7776 &total_size_written);
7777 if (ret < 0) {
7778 if (ret == -EACCES)
7779 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7780 if (ret == -EAGAIN)
7781 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7782 else if (ret == -EBADF)
7783 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7784 else if (ret == -EFBIG || ret == -ENOSPC)
7785 rsp->hdr.Status = STATUS_DISK_FULL;
7786 else if (ret == -EINVAL)
7787 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7788 else if (ret == -EISDIR)
7789 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7790 else if (ret == -E2BIG)
7791 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7792 else
7793 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7794 }
7795
7796 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7797 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7798 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7799 out:
7800 ksmbd_fd_put(work, src_fp);
7801 ksmbd_fd_put(work, dst_fp);
7802 return ret;
7803 }
7804
idev_ipv4_address(struct in_device * idev)7805 static __be32 idev_ipv4_address(struct in_device *idev)
7806 {
7807 __be32 addr = 0;
7808
7809 struct in_ifaddr *ifa;
7810
7811 rcu_read_lock();
7812 in_dev_for_each_ifa_rcu(ifa, idev) {
7813 if (ifa->ifa_flags & IFA_F_SECONDARY)
7814 continue;
7815
7816 addr = ifa->ifa_address;
7817 break;
7818 }
7819 rcu_read_unlock();
7820 return addr;
7821 }
7822
fsctl_query_iface_info_ioctl(struct ksmbd_conn * conn,struct smb2_ioctl_rsp * rsp,unsigned int out_buf_len)7823 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7824 struct smb2_ioctl_rsp *rsp,
7825 unsigned int out_buf_len)
7826 {
7827 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7828 int nbytes = 0;
7829 struct net_device *netdev;
7830 struct sockaddr_storage_rsp *sockaddr_storage;
7831 unsigned int flags;
7832 unsigned long long speed;
7833
7834 rtnl_lock();
7835 for_each_netdev(&init_net, netdev) {
7836 bool ipv4_set = false;
7837
7838 if (netdev->type == ARPHRD_LOOPBACK)
7839 continue;
7840
7841 if (!ksmbd_find_netdev_name_iface_list(netdev->name))
7842 continue;
7843
7844 flags = netif_get_flags(netdev);
7845 if (!(flags & IFF_RUNNING))
7846 continue;
7847 ipv6_retry:
7848 if (out_buf_len <
7849 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7850 rtnl_unlock();
7851 return -ENOSPC;
7852 }
7853
7854 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7855 &rsp->Buffer[nbytes];
7856 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7857
7858 nii_rsp->Capability = 0;
7859 if (netdev->real_num_tx_queues > 1)
7860 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7861 if (ksmbd_rdma_capable_netdev(netdev))
7862 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7863
7864 nii_rsp->Next = cpu_to_le32(152);
7865 nii_rsp->Reserved = 0;
7866
7867 if (netdev->ethtool_ops->get_link_ksettings) {
7868 struct ethtool_link_ksettings cmd;
7869
7870 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7871 speed = cmd.base.speed;
7872 } else {
7873 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7874 "speed is unknown, defaulting to 1Gb/sec");
7875 speed = SPEED_1000;
7876 }
7877
7878 speed *= 1000000;
7879 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7880
7881 sockaddr_storage = (struct sockaddr_storage_rsp *)
7882 nii_rsp->SockAddr_Storage;
7883 memset(sockaddr_storage, 0, 128);
7884
7885 if (!ipv4_set) {
7886 struct in_device *idev;
7887
7888 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7889 sockaddr_storage->addr4.Port = 0;
7890
7891 idev = __in_dev_get_rtnl(netdev);
7892 if (!idev)
7893 continue;
7894 sockaddr_storage->addr4.IPv4address =
7895 idev_ipv4_address(idev);
7896 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7897 ipv4_set = true;
7898 goto ipv6_retry;
7899 } else {
7900 struct inet6_dev *idev6;
7901 struct inet6_ifaddr *ifa;
7902 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7903
7904 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7905 sockaddr_storage->addr6.Port = 0;
7906 sockaddr_storage->addr6.FlowInfo = 0;
7907
7908 idev6 = __in6_dev_get(netdev);
7909 if (!idev6)
7910 continue;
7911
7912 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7913 if (ifa->flags & (IFA_F_TENTATIVE |
7914 IFA_F_DEPRECATED))
7915 continue;
7916 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7917 break;
7918 }
7919 sockaddr_storage->addr6.ScopeId = 0;
7920 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7921 }
7922 }
7923 rtnl_unlock();
7924
7925 /* zero if this is last one */
7926 if (nii_rsp)
7927 nii_rsp->Next = 0;
7928
7929 rsp->PersistentFileId = SMB2_NO_FID;
7930 rsp->VolatileFileId = SMB2_NO_FID;
7931 return nbytes;
7932 }
7933
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)7934 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7935 struct validate_negotiate_info_req *neg_req,
7936 struct validate_negotiate_info_rsp *neg_rsp,
7937 unsigned int in_buf_len)
7938 {
7939 int ret = 0;
7940 int dialect;
7941
7942 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7943 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7944 return -EINVAL;
7945
7946 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7947 neg_req->DialectCount);
7948 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7949 ret = -EINVAL;
7950 goto err_out;
7951 }
7952
7953 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7954 ret = -EINVAL;
7955 goto err_out;
7956 }
7957
7958 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7959 ret = -EINVAL;
7960 goto err_out;
7961 }
7962
7963 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7964 ret = -EINVAL;
7965 goto err_out;
7966 }
7967
7968 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7969 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7970 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7971 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7972 err_out:
7973 return ret;
7974 }
7975
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)7976 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7977 struct file_allocated_range_buffer *qar_req,
7978 struct file_allocated_range_buffer *qar_rsp,
7979 unsigned int in_count, unsigned int *out_count)
7980 {
7981 struct ksmbd_file *fp;
7982 loff_t start, length;
7983 int ret = 0;
7984
7985 *out_count = 0;
7986 if (in_count == 0)
7987 return -EINVAL;
7988
7989 start = le64_to_cpu(qar_req->file_offset);
7990 length = le64_to_cpu(qar_req->length);
7991
7992 if (start < 0 || length < 0)
7993 return -EINVAL;
7994
7995 fp = ksmbd_lookup_fd_fast(work, id);
7996 if (!fp)
7997 return -ENOENT;
7998
7999 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8000 qar_rsp, in_count, out_count);
8001 if (ret && ret != -E2BIG)
8002 *out_count = 0;
8003
8004 ksmbd_fd_put(work, fp);
8005 return ret;
8006 }
8007
fsctl_pipe_transceive(struct ksmbd_work * work,u64 id,unsigned int out_buf_len,struct smb2_ioctl_req * req,struct smb2_ioctl_rsp * rsp)8008 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8009 unsigned int out_buf_len,
8010 struct smb2_ioctl_req *req,
8011 struct smb2_ioctl_rsp *rsp)
8012 {
8013 struct ksmbd_rpc_command *rpc_resp;
8014 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8015 int nbytes = 0;
8016
8017 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8018 le32_to_cpu(req->InputCount));
8019 if (rpc_resp) {
8020 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8021 /*
8022 * set STATUS_SOME_NOT_MAPPED response
8023 * for unknown domain sid.
8024 */
8025 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8026 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8027 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8028 goto out;
8029 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
8030 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8031 goto out;
8032 }
8033
8034 nbytes = rpc_resp->payload_sz;
8035 if (rpc_resp->payload_sz > out_buf_len) {
8036 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8037 nbytes = out_buf_len;
8038 }
8039
8040 if (!rpc_resp->payload_sz) {
8041 rsp->hdr.Status =
8042 STATUS_UNEXPECTED_IO_ERROR;
8043 goto out;
8044 }
8045
8046 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8047 }
8048 out:
8049 kvfree(rpc_resp);
8050 return nbytes;
8051 }
8052
fsctl_set_sparse(struct ksmbd_work * work,u64 id,struct file_sparse * sparse)8053 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8054 struct file_sparse *sparse)
8055 {
8056 struct ksmbd_file *fp;
8057 struct mnt_idmap *idmap;
8058 int ret = 0;
8059 __le32 old_fattr;
8060
8061 fp = ksmbd_lookup_fd_fast(work, id);
8062 if (!fp)
8063 return -ENOENT;
8064 idmap = file_mnt_idmap(fp->filp);
8065
8066 old_fattr = fp->f_ci->m_fattr;
8067 if (sparse->SetSparse)
8068 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8069 else
8070 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8071
8072 if (fp->f_ci->m_fattr != old_fattr &&
8073 test_share_config_flag(work->tcon->share_conf,
8074 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8075 struct xattr_dos_attrib da;
8076
8077 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8078 fp->filp->f_path.dentry, &da);
8079 if (ret <= 0)
8080 goto out;
8081
8082 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8083 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8084 &fp->filp->f_path,
8085 &da, true);
8086 if (ret)
8087 fp->f_ci->m_fattr = old_fattr;
8088 }
8089
8090 out:
8091 ksmbd_fd_put(work, fp);
8092 return ret;
8093 }
8094
fsctl_request_resume_key(struct ksmbd_work * work,struct smb2_ioctl_req * req,struct resume_key_ioctl_rsp * key_rsp)8095 static int fsctl_request_resume_key(struct ksmbd_work *work,
8096 struct smb2_ioctl_req *req,
8097 struct resume_key_ioctl_rsp *key_rsp)
8098 {
8099 struct ksmbd_file *fp;
8100
8101 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8102 if (!fp)
8103 return -ENOENT;
8104
8105 memset(key_rsp, 0, sizeof(*key_rsp));
8106 key_rsp->ResumeKey[0] = req->VolatileFileId;
8107 key_rsp->ResumeKey[1] = req->PersistentFileId;
8108 ksmbd_fd_put(work, fp);
8109
8110 return 0;
8111 }
8112
8113 /**
8114 * smb2_ioctl() - handler for smb2 ioctl command
8115 * @work: smb work containing ioctl command buffer
8116 *
8117 * Return: 0 on success, otherwise error
8118 */
smb2_ioctl(struct ksmbd_work * work)8119 int smb2_ioctl(struct ksmbd_work *work)
8120 {
8121 struct smb2_ioctl_req *req;
8122 struct smb2_ioctl_rsp *rsp;
8123 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8124 u64 id = KSMBD_NO_FID;
8125 struct ksmbd_conn *conn = work->conn;
8126 int ret = 0;
8127 char *buffer;
8128
8129 ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8130
8131 if (work->next_smb2_rcv_hdr_off) {
8132 req = ksmbd_req_buf_next(work);
8133 rsp = ksmbd_resp_buf_next(work);
8134 if (!has_file_id(req->VolatileFileId)) {
8135 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8136 work->compound_fid);
8137 id = work->compound_fid;
8138 }
8139 } else {
8140 req = smb2_get_msg(work->request_buf);
8141 rsp = smb2_get_msg(work->response_buf);
8142 }
8143
8144 if (!has_file_id(id))
8145 id = req->VolatileFileId;
8146
8147 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8148 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8149 goto out;
8150 }
8151
8152 buffer = (char *)req + le32_to_cpu(req->InputOffset);
8153
8154 cnt_code = le32_to_cpu(req->CtlCode);
8155 ret = smb2_calc_max_out_buf_len(work, 48,
8156 le32_to_cpu(req->MaxOutputResponse));
8157 if (ret < 0) {
8158 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8159 goto out;
8160 }
8161 out_buf_len = (unsigned int)ret;
8162 in_buf_len = le32_to_cpu(req->InputCount);
8163
8164 switch (cnt_code) {
8165 case FSCTL_DFS_GET_REFERRALS:
8166 case FSCTL_DFS_GET_REFERRALS_EX:
8167 /* Not support DFS yet */
8168 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8169 goto out;
8170 case FSCTL_CREATE_OR_GET_OBJECT_ID:
8171 {
8172 struct file_object_buf_type1_ioctl_rsp *obj_buf;
8173
8174 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8175 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8176 &rsp->Buffer[0];
8177
8178 /*
8179 * TODO: This is dummy implementation to pass smbtorture
8180 * Need to check correct response later
8181 */
8182 memset(obj_buf->ObjectId, 0x0, 16);
8183 memset(obj_buf->BirthVolumeId, 0x0, 16);
8184 memset(obj_buf->BirthObjectId, 0x0, 16);
8185 memset(obj_buf->DomainId, 0x0, 16);
8186
8187 break;
8188 }
8189 case FSCTL_PIPE_TRANSCEIVE:
8190 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8191 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8192 break;
8193 case FSCTL_VALIDATE_NEGOTIATE_INFO:
8194 if (conn->dialect < SMB30_PROT_ID) {
8195 ret = -EOPNOTSUPP;
8196 goto out;
8197 }
8198
8199 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8200 Dialects)) {
8201 ret = -EINVAL;
8202 goto out;
8203 }
8204
8205 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8206 ret = -EINVAL;
8207 goto out;
8208 }
8209
8210 ret = fsctl_validate_negotiate_info(conn,
8211 (struct validate_negotiate_info_req *)buffer,
8212 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8213 in_buf_len);
8214 if (ret < 0)
8215 goto out;
8216
8217 nbytes = sizeof(struct validate_negotiate_info_rsp);
8218 rsp->PersistentFileId = SMB2_NO_FID;
8219 rsp->VolatileFileId = SMB2_NO_FID;
8220 break;
8221 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8222 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8223 if (ret < 0)
8224 goto out;
8225 nbytes = ret;
8226 break;
8227 case FSCTL_REQUEST_RESUME_KEY:
8228 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8229 ret = -EINVAL;
8230 goto out;
8231 }
8232
8233 ret = fsctl_request_resume_key(work, req,
8234 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8235 if (ret < 0)
8236 goto out;
8237 rsp->PersistentFileId = req->PersistentFileId;
8238 rsp->VolatileFileId = req->VolatileFileId;
8239 nbytes = sizeof(struct resume_key_ioctl_rsp);
8240 break;
8241 case FSCTL_COPYCHUNK:
8242 case FSCTL_COPYCHUNK_WRITE:
8243 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8244 ksmbd_debug(SMB,
8245 "User does not have write permission\n");
8246 ret = -EACCES;
8247 goto out;
8248 }
8249
8250 if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
8251 ret = -EINVAL;
8252 goto out;
8253 }
8254
8255 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8256 ret = -EINVAL;
8257 goto out;
8258 }
8259
8260 nbytes = sizeof(struct copychunk_ioctl_rsp);
8261 rsp->VolatileFileId = req->VolatileFileId;
8262 rsp->PersistentFileId = req->PersistentFileId;
8263 fsctl_copychunk(work,
8264 (struct copychunk_ioctl_req *)buffer,
8265 le32_to_cpu(req->CtlCode),
8266 le32_to_cpu(req->InputCount),
8267 req->VolatileFileId,
8268 req->PersistentFileId,
8269 rsp);
8270 break;
8271 case FSCTL_SET_SPARSE:
8272 if (in_buf_len < sizeof(struct file_sparse)) {
8273 ret = -EINVAL;
8274 goto out;
8275 }
8276
8277 ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8278 if (ret < 0)
8279 goto out;
8280 break;
8281 case FSCTL_SET_ZERO_DATA:
8282 {
8283 struct file_zero_data_information *zero_data;
8284 struct ksmbd_file *fp;
8285 loff_t off, len, bfz;
8286
8287 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8288 ksmbd_debug(SMB,
8289 "User does not have write permission\n");
8290 ret = -EACCES;
8291 goto out;
8292 }
8293
8294 if (in_buf_len < sizeof(struct file_zero_data_information)) {
8295 ret = -EINVAL;
8296 goto out;
8297 }
8298
8299 zero_data =
8300 (struct file_zero_data_information *)buffer;
8301
8302 off = le64_to_cpu(zero_data->FileOffset);
8303 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8304 if (off < 0 || bfz < 0 || off > bfz) {
8305 ret = -EINVAL;
8306 goto out;
8307 }
8308
8309 len = bfz - off;
8310 if (len) {
8311 fp = ksmbd_lookup_fd_fast(work, id);
8312 if (!fp) {
8313 ret = -ENOENT;
8314 goto out;
8315 }
8316
8317 ret = ksmbd_vfs_zero_data(work, fp, off, len);
8318 ksmbd_fd_put(work, fp);
8319 if (ret < 0)
8320 goto out;
8321 }
8322 break;
8323 }
8324 case FSCTL_QUERY_ALLOCATED_RANGES:
8325 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8326 ret = -EINVAL;
8327 goto out;
8328 }
8329
8330 ret = fsctl_query_allocated_ranges(work, id,
8331 (struct file_allocated_range_buffer *)buffer,
8332 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
8333 out_buf_len /
8334 sizeof(struct file_allocated_range_buffer), &nbytes);
8335 if (ret == -E2BIG) {
8336 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8337 } else if (ret < 0) {
8338 nbytes = 0;
8339 goto out;
8340 }
8341
8342 nbytes *= sizeof(struct file_allocated_range_buffer);
8343 break;
8344 case FSCTL_GET_REPARSE_POINT:
8345 {
8346 struct reparse_data_buffer *reparse_ptr;
8347 struct ksmbd_file *fp;
8348
8349 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8350 fp = ksmbd_lookup_fd_fast(work, id);
8351 if (!fp) {
8352 pr_err("not found fp!!\n");
8353 ret = -ENOENT;
8354 goto out;
8355 }
8356
8357 reparse_ptr->ReparseTag =
8358 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8359 reparse_ptr->ReparseDataLength = 0;
8360 ksmbd_fd_put(work, fp);
8361 nbytes = sizeof(struct reparse_data_buffer);
8362 break;
8363 }
8364 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8365 {
8366 struct ksmbd_file *fp_in, *fp_out = NULL;
8367 struct duplicate_extents_to_file *dup_ext;
8368 loff_t src_off, dst_off, length, cloned;
8369
8370 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8371 ret = -EINVAL;
8372 goto out;
8373 }
8374
8375 dup_ext = (struct duplicate_extents_to_file *)buffer;
8376
8377 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8378 dup_ext->PersistentFileHandle);
8379 if (!fp_in) {
8380 pr_err("not found file handle in duplicate extent to file\n");
8381 ret = -ENOENT;
8382 goto out;
8383 }
8384
8385 fp_out = ksmbd_lookup_fd_fast(work, id);
8386 if (!fp_out) {
8387 pr_err("not found fp\n");
8388 ret = -ENOENT;
8389 goto dup_ext_out;
8390 }
8391
8392 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8393 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8394 length = le64_to_cpu(dup_ext->ByteCount);
8395 /*
8396 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8397 * should fall back to vfs_copy_file_range(). This could be
8398 * beneficial when re-exporting nfs/smb mount, but note that
8399 * this can result in partial copy that returns an error status.
8400 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8401 * fall back to vfs_copy_file_range(), should be avoided when
8402 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8403 */
8404 cloned = vfs_clone_file_range(fp_in->filp, src_off,
8405 fp_out->filp, dst_off, length, 0);
8406 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8407 ret = -EOPNOTSUPP;
8408 goto dup_ext_out;
8409 } else if (cloned != length) {
8410 cloned = vfs_copy_file_range(fp_in->filp, src_off,
8411 fp_out->filp, dst_off,
8412 length, 0);
8413 if (cloned != length) {
8414 if (cloned < 0)
8415 ret = cloned;
8416 else
8417 ret = -EINVAL;
8418 }
8419 }
8420
8421 dup_ext_out:
8422 ksmbd_fd_put(work, fp_in);
8423 ksmbd_fd_put(work, fp_out);
8424 if (ret < 0)
8425 goto out;
8426 break;
8427 }
8428 default:
8429 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8430 cnt_code);
8431 ret = -EOPNOTSUPP;
8432 goto out;
8433 }
8434
8435 rsp->CtlCode = cpu_to_le32(cnt_code);
8436 rsp->InputCount = cpu_to_le32(0);
8437 rsp->InputOffset = cpu_to_le32(112);
8438 rsp->OutputOffset = cpu_to_le32(112);
8439 rsp->OutputCount = cpu_to_le32(nbytes);
8440 rsp->StructureSize = cpu_to_le16(49);
8441 rsp->Reserved = cpu_to_le16(0);
8442 rsp->Flags = cpu_to_le32(0);
8443 rsp->Reserved2 = cpu_to_le32(0);
8444 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8445 if (!ret)
8446 return ret;
8447
8448 out:
8449 if (ret == -EACCES)
8450 rsp->hdr.Status = STATUS_ACCESS_DENIED;
8451 else if (ret == -ENOENT)
8452 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8453 else if (ret == -EOPNOTSUPP)
8454 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8455 else if (ret == -ENOSPC)
8456 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8457 else if (ret < 0 || rsp->hdr.Status == 0)
8458 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8459 smb2_set_err_rsp(work);
8460 return 0;
8461 }
8462
8463 /**
8464 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8465 * @work: smb work containing oplock break command buffer
8466 *
8467 * Return: 0
8468 */
smb20_oplock_break_ack(struct ksmbd_work * work)8469 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8470 {
8471 struct smb2_oplock_break *req;
8472 struct smb2_oplock_break *rsp;
8473 struct ksmbd_file *fp;
8474 struct oplock_info *opinfo = NULL;
8475 __le32 err = 0;
8476 int ret = 0;
8477 u64 volatile_id, persistent_id;
8478 char req_oplevel = 0, rsp_oplevel = 0;
8479 unsigned int oplock_change_type;
8480
8481 WORK_BUFFERS(work, req, rsp);
8482
8483 volatile_id = req->VolatileFid;
8484 persistent_id = req->PersistentFid;
8485 req_oplevel = req->OplockLevel;
8486 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8487 volatile_id, persistent_id, req_oplevel);
8488
8489 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8490 if (!fp) {
8491 rsp->hdr.Status = STATUS_FILE_CLOSED;
8492 smb2_set_err_rsp(work);
8493 return;
8494 }
8495
8496 opinfo = opinfo_get(fp);
8497 if (!opinfo) {
8498 pr_err("unexpected null oplock_info\n");
8499 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8500 smb2_set_err_rsp(work);
8501 ksmbd_fd_put(work, fp);
8502 return;
8503 }
8504
8505 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8506 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8507 goto err_out;
8508 }
8509
8510 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8511 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8512 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8513 goto err_out;
8514 }
8515
8516 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8517 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8518 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8519 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8520 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8521 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8522 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8523 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8524 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8525 oplock_change_type = OPLOCK_READ_TO_NONE;
8526 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8527 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8528 err = STATUS_INVALID_DEVICE_STATE;
8529 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8530 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8531 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8532 oplock_change_type = OPLOCK_WRITE_TO_READ;
8533 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8534 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8535 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8536 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8537 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8538 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8539 oplock_change_type = OPLOCK_READ_TO_NONE;
8540 } else {
8541 oplock_change_type = 0;
8542 }
8543 } else {
8544 oplock_change_type = 0;
8545 }
8546
8547 switch (oplock_change_type) {
8548 case OPLOCK_WRITE_TO_READ:
8549 ret = opinfo_write_to_read(opinfo);
8550 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8551 break;
8552 case OPLOCK_WRITE_TO_NONE:
8553 ret = opinfo_write_to_none(opinfo);
8554 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8555 break;
8556 case OPLOCK_READ_TO_NONE:
8557 ret = opinfo_read_to_none(opinfo);
8558 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8559 break;
8560 default:
8561 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8562 opinfo->level, rsp_oplevel);
8563 }
8564
8565 if (ret < 0) {
8566 rsp->hdr.Status = err;
8567 goto err_out;
8568 }
8569
8570 rsp->StructureSize = cpu_to_le16(24);
8571 rsp->OplockLevel = rsp_oplevel;
8572 rsp->Reserved = 0;
8573 rsp->Reserved2 = 0;
8574 rsp->VolatileFid = volatile_id;
8575 rsp->PersistentFid = persistent_id;
8576 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8577 if (ret) {
8578 err_out:
8579 smb2_set_err_rsp(work);
8580 }
8581
8582 opinfo->op_state = OPLOCK_STATE_NONE;
8583 wake_up_interruptible_all(&opinfo->oplock_q);
8584 opinfo_put(opinfo);
8585 ksmbd_fd_put(work, fp);
8586 }
8587
check_lease_state(struct lease * lease,__le32 req_state)8588 static int check_lease_state(struct lease *lease, __le32 req_state)
8589 {
8590 if ((lease->new_state ==
8591 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8592 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8593 lease->new_state = req_state;
8594 return 0;
8595 }
8596
8597 if (lease->new_state == req_state)
8598 return 0;
8599
8600 return 1;
8601 }
8602
8603 /**
8604 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8605 * @work: smb work containing lease break command buffer
8606 *
8607 * Return: 0
8608 */
smb21_lease_break_ack(struct ksmbd_work * work)8609 static void smb21_lease_break_ack(struct ksmbd_work *work)
8610 {
8611 struct ksmbd_conn *conn = work->conn;
8612 struct smb2_lease_ack *req;
8613 struct smb2_lease_ack *rsp;
8614 struct oplock_info *opinfo;
8615 __le32 err = 0;
8616 int ret = 0;
8617 unsigned int lease_change_type;
8618 __le32 lease_state;
8619 struct lease *lease;
8620
8621 WORK_BUFFERS(work, req, rsp);
8622
8623 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8624 le32_to_cpu(req->LeaseState));
8625 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8626 if (!opinfo) {
8627 ksmbd_debug(OPLOCK, "file not opened\n");
8628 smb2_set_err_rsp(work);
8629 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8630 return;
8631 }
8632 lease = opinfo->o_lease;
8633
8634 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8635 pr_err("unexpected lease break state 0x%x\n",
8636 opinfo->op_state);
8637 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8638 goto err_out;
8639 }
8640
8641 if (check_lease_state(lease, req->LeaseState)) {
8642 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8643 ksmbd_debug(OPLOCK,
8644 "req lease state: 0x%x, expected state: 0x%x\n",
8645 req->LeaseState, lease->new_state);
8646 goto err_out;
8647 }
8648
8649 if (!atomic_read(&opinfo->breaking_cnt)) {
8650 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8651 goto err_out;
8652 }
8653
8654 /* check for bad lease state */
8655 if (req->LeaseState &
8656 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8657 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8658 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8659 lease_change_type = OPLOCK_WRITE_TO_NONE;
8660 else
8661 lease_change_type = OPLOCK_READ_TO_NONE;
8662 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8663 le32_to_cpu(lease->state),
8664 le32_to_cpu(req->LeaseState));
8665 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8666 req->LeaseState != SMB2_LEASE_NONE_LE) {
8667 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8668 lease_change_type = OPLOCK_READ_TO_NONE;
8669 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8670 le32_to_cpu(lease->state),
8671 le32_to_cpu(req->LeaseState));
8672 } else {
8673 /* valid lease state changes */
8674 err = STATUS_INVALID_DEVICE_STATE;
8675 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8676 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8677 lease_change_type = OPLOCK_WRITE_TO_NONE;
8678 else
8679 lease_change_type = OPLOCK_READ_TO_NONE;
8680 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8681 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8682 lease_change_type = OPLOCK_WRITE_TO_READ;
8683 else
8684 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8685 } else {
8686 lease_change_type = 0;
8687 }
8688 }
8689
8690 switch (lease_change_type) {
8691 case OPLOCK_WRITE_TO_READ:
8692 ret = opinfo_write_to_read(opinfo);
8693 break;
8694 case OPLOCK_READ_HANDLE_TO_READ:
8695 ret = opinfo_read_handle_to_read(opinfo);
8696 break;
8697 case OPLOCK_WRITE_TO_NONE:
8698 ret = opinfo_write_to_none(opinfo);
8699 break;
8700 case OPLOCK_READ_TO_NONE:
8701 ret = opinfo_read_to_none(opinfo);
8702 break;
8703 default:
8704 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8705 le32_to_cpu(lease->state),
8706 le32_to_cpu(req->LeaseState));
8707 }
8708
8709 if (ret < 0) {
8710 rsp->hdr.Status = err;
8711 goto err_out;
8712 }
8713
8714 lease_state = lease->state;
8715
8716 rsp->StructureSize = cpu_to_le16(36);
8717 rsp->Reserved = 0;
8718 rsp->Flags = 0;
8719 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8720 rsp->LeaseState = lease_state;
8721 rsp->LeaseDuration = 0;
8722 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8723 if (ret) {
8724 err_out:
8725 smb2_set_err_rsp(work);
8726 }
8727
8728 opinfo->op_state = OPLOCK_STATE_NONE;
8729 wake_up_interruptible_all(&opinfo->oplock_q);
8730 atomic_dec(&opinfo->breaking_cnt);
8731 wake_up_interruptible_all(&opinfo->oplock_brk);
8732 opinfo_put(opinfo);
8733 }
8734
8735 /**
8736 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8737 * @work: smb work containing oplock/lease break command buffer
8738 *
8739 * Return: 0
8740 */
smb2_oplock_break(struct ksmbd_work * work)8741 int smb2_oplock_break(struct ksmbd_work *work)
8742 {
8743 struct smb2_oplock_break *req;
8744 struct smb2_oplock_break *rsp;
8745
8746 ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
8747
8748 WORK_BUFFERS(work, req, rsp);
8749
8750 switch (le16_to_cpu(req->StructureSize)) {
8751 case OP_BREAK_STRUCT_SIZE_20:
8752 smb20_oplock_break_ack(work);
8753 break;
8754 case OP_BREAK_STRUCT_SIZE_21:
8755 smb21_lease_break_ack(work);
8756 break;
8757 default:
8758 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8759 le16_to_cpu(req->StructureSize));
8760 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8761 smb2_set_err_rsp(work);
8762 }
8763
8764 return 0;
8765 }
8766
8767 /**
8768 * smb2_notify() - handler for smb2 notify request
8769 * @work: smb work containing notify command buffer
8770 *
8771 * Return: 0
8772 */
smb2_notify(struct ksmbd_work * work)8773 int smb2_notify(struct ksmbd_work *work)
8774 {
8775 struct smb2_change_notify_req *req;
8776 struct smb2_change_notify_rsp *rsp;
8777
8778 ksmbd_debug(SMB, "Received smb2 notify\n");
8779
8780 WORK_BUFFERS(work, req, rsp);
8781
8782 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8783 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8784 smb2_set_err_rsp(work);
8785 return 0;
8786 }
8787
8788 smb2_set_err_rsp(work);
8789 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8790 return 0;
8791 }
8792
8793 /**
8794 * smb2_is_sign_req() - handler for checking packet signing status
8795 * @work: smb work containing notify command buffer
8796 * @command: SMB2 command id
8797 *
8798 * Return: true if packed is signed, false otherwise
8799 */
smb2_is_sign_req(struct ksmbd_work * work,unsigned int command)8800 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8801 {
8802 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8803
8804 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8805 command != SMB2_NEGOTIATE_HE &&
8806 command != SMB2_SESSION_SETUP_HE &&
8807 command != SMB2_OPLOCK_BREAK_HE)
8808 return true;
8809
8810 return false;
8811 }
8812
8813 /**
8814 * smb2_check_sign_req() - handler for req packet sign processing
8815 * @work: smb work containing notify command buffer
8816 *
8817 * Return: 1 on success, 0 otherwise
8818 */
smb2_check_sign_req(struct ksmbd_work * work)8819 int smb2_check_sign_req(struct ksmbd_work *work)
8820 {
8821 struct smb2_hdr *hdr;
8822 char signature_req[SMB2_SIGNATURE_SIZE];
8823 char signature[SMB2_HMACSHA256_SIZE];
8824 struct kvec iov[1];
8825 size_t len;
8826
8827 hdr = smb2_get_msg(work->request_buf);
8828 if (work->next_smb2_rcv_hdr_off)
8829 hdr = ksmbd_req_buf_next(work);
8830
8831 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8832 len = get_rfc1002_len(work->request_buf);
8833 else if (hdr->NextCommand)
8834 len = le32_to_cpu(hdr->NextCommand);
8835 else
8836 len = get_rfc1002_len(work->request_buf) -
8837 work->next_smb2_rcv_hdr_off;
8838
8839 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8840 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8841
8842 iov[0].iov_base = (char *)&hdr->ProtocolId;
8843 iov[0].iov_len = len;
8844
8845 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8846 signature))
8847 return 0;
8848
8849 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8850 pr_err("bad smb2 signature\n");
8851 return 0;
8852 }
8853
8854 return 1;
8855 }
8856
8857 /**
8858 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8859 * @work: smb work containing notify command buffer
8860 *
8861 */
smb2_set_sign_rsp(struct ksmbd_work * work)8862 void smb2_set_sign_rsp(struct ksmbd_work *work)
8863 {
8864 struct smb2_hdr *hdr;
8865 char signature[SMB2_HMACSHA256_SIZE];
8866 struct kvec *iov;
8867 int n_vec = 1;
8868
8869 hdr = ksmbd_resp_buf_curr(work);
8870 hdr->Flags |= SMB2_FLAGS_SIGNED;
8871 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8872
8873 if (hdr->Command == SMB2_READ) {
8874 iov = &work->iov[work->iov_idx - 1];
8875 n_vec++;
8876 } else {
8877 iov = &work->iov[work->iov_idx];
8878 }
8879
8880 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8881 signature))
8882 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8883 }
8884
8885 /**
8886 * smb3_check_sign_req() - handler for req packet sign processing
8887 * @work: smb work containing notify command buffer
8888 *
8889 * Return: 1 on success, 0 otherwise
8890 */
smb3_check_sign_req(struct ksmbd_work * work)8891 int smb3_check_sign_req(struct ksmbd_work *work)
8892 {
8893 struct ksmbd_conn *conn = work->conn;
8894 char *signing_key;
8895 struct smb2_hdr *hdr;
8896 struct channel *chann;
8897 char signature_req[SMB2_SIGNATURE_SIZE];
8898 char signature[SMB2_CMACAES_SIZE];
8899 struct kvec iov[1];
8900 size_t len;
8901
8902 hdr = smb2_get_msg(work->request_buf);
8903 if (work->next_smb2_rcv_hdr_off)
8904 hdr = ksmbd_req_buf_next(work);
8905
8906 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8907 len = get_rfc1002_len(work->request_buf);
8908 else if (hdr->NextCommand)
8909 len = le32_to_cpu(hdr->NextCommand);
8910 else
8911 len = get_rfc1002_len(work->request_buf) -
8912 work->next_smb2_rcv_hdr_off;
8913
8914 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8915 signing_key = work->sess->smb3signingkey;
8916 } else {
8917 chann = lookup_chann_list(work->sess, conn);
8918 if (!chann) {
8919 return 0;
8920 }
8921 signing_key = chann->smb3signingkey;
8922 }
8923
8924 if (!signing_key) {
8925 pr_err("SMB3 signing key is not generated\n");
8926 return 0;
8927 }
8928
8929 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8930 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8931 iov[0].iov_base = (char *)&hdr->ProtocolId;
8932 iov[0].iov_len = len;
8933
8934 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8935 return 0;
8936
8937 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8938 pr_err("bad smb2 signature\n");
8939 return 0;
8940 }
8941
8942 return 1;
8943 }
8944
8945 /**
8946 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8947 * @work: smb work containing notify command buffer
8948 *
8949 */
smb3_set_sign_rsp(struct ksmbd_work * work)8950 void smb3_set_sign_rsp(struct ksmbd_work *work)
8951 {
8952 struct ksmbd_conn *conn = work->conn;
8953 struct smb2_hdr *hdr;
8954 struct channel *chann;
8955 char signature[SMB2_CMACAES_SIZE];
8956 struct kvec *iov;
8957 int n_vec = 1;
8958 char *signing_key;
8959
8960 hdr = ksmbd_resp_buf_curr(work);
8961
8962 if (conn->binding == false &&
8963 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8964 signing_key = work->sess->smb3signingkey;
8965 } else {
8966 chann = lookup_chann_list(work->sess, work->conn);
8967 if (!chann) {
8968 return;
8969 }
8970 signing_key = chann->smb3signingkey;
8971 }
8972
8973 if (!signing_key)
8974 return;
8975
8976 hdr->Flags |= SMB2_FLAGS_SIGNED;
8977 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8978
8979 if (hdr->Command == SMB2_READ) {
8980 iov = &work->iov[work->iov_idx - 1];
8981 n_vec++;
8982 } else {
8983 iov = &work->iov[work->iov_idx];
8984 }
8985
8986 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8987 signature))
8988 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8989 }
8990
8991 /**
8992 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8993 * @work: smb work containing response buffer
8994 *
8995 */
smb3_preauth_hash_rsp(struct ksmbd_work * work)8996 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8997 {
8998 struct ksmbd_conn *conn = work->conn;
8999 struct ksmbd_session *sess = work->sess;
9000 struct smb2_hdr *req, *rsp;
9001
9002 if (conn->dialect != SMB311_PROT_ID)
9003 return;
9004
9005 WORK_BUFFERS(work, req, rsp);
9006
9007 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
9008 conn->preauth_info)
9009 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9010 conn->preauth_info->Preauth_HashValue);
9011
9012 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9013 __u8 *hash_value;
9014
9015 if (conn->binding) {
9016 struct preauth_session *preauth_sess;
9017
9018 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9019 if (!preauth_sess)
9020 return;
9021 hash_value = preauth_sess->Preauth_HashValue;
9022 } else {
9023 hash_value = sess->Preauth_HashValue;
9024 if (!hash_value)
9025 return;
9026 }
9027 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9028 hash_value);
9029 }
9030 }
9031
fill_transform_hdr(void * tr_buf,char * old_buf,__le16 cipher_type)9032 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9033 {
9034 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9035 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
9036 unsigned int orig_len = get_rfc1002_len(old_buf);
9037
9038 /* tr_buf must be cleared by the caller */
9039 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9040 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9041 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9042 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9043 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9044 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9045 else
9046 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9047 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9048 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9049 inc_rfc1001_len(tr_buf, orig_len);
9050 }
9051
smb3_encrypt_resp(struct ksmbd_work * work)9052 int smb3_encrypt_resp(struct ksmbd_work *work)
9053 {
9054 struct kvec *iov = work->iov;
9055 int rc = -ENOMEM;
9056 void *tr_buf;
9057
9058 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9059 if (!tr_buf)
9060 return rc;
9061
9062 /* fill transform header */
9063 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9064
9065 iov[0].iov_base = tr_buf;
9066 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9067 work->tr_buf = tr_buf;
9068
9069 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9070 }
9071
smb3_is_transform_hdr(void * buf)9072 bool smb3_is_transform_hdr(void *buf)
9073 {
9074 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
9075
9076 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9077 }
9078
smb3_decrypt_req(struct ksmbd_work * work)9079 int smb3_decrypt_req(struct ksmbd_work *work)
9080 {
9081 struct ksmbd_session *sess;
9082 char *buf = work->request_buf;
9083 unsigned int pdu_length = get_rfc1002_len(buf);
9084 struct kvec iov[2];
9085 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9086 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
9087 int rc = 0;
9088
9089 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9090 buf_data_size < sizeof(struct smb2_hdr)) {
9091 pr_err("Transform message is too small (%u)\n",
9092 pdu_length);
9093 return -ECONNABORTED;
9094 }
9095
9096 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9097 pr_err("Transform message is broken\n");
9098 return -ECONNABORTED;
9099 }
9100
9101 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9102 if (!sess) {
9103 pr_err("invalid session id(%llx) in transform header\n",
9104 le64_to_cpu(tr_hdr->SessionId));
9105 return -ECONNABORTED;
9106 }
9107 ksmbd_user_session_put(sess);
9108
9109 iov[0].iov_base = buf;
9110 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9111 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9112 iov[1].iov_len = buf_data_size;
9113 rc = ksmbd_crypt_message(work, iov, 2, 0);
9114 if (rc)
9115 return rc;
9116
9117 memmove(buf + 4, iov[1].iov_base, buf_data_size);
9118 *(__be32 *)buf = cpu_to_be32(buf_data_size);
9119
9120 return rc;
9121 }
9122
smb3_11_final_sess_setup_resp(struct ksmbd_work * work)9123 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9124 {
9125 struct ksmbd_conn *conn = work->conn;
9126 struct ksmbd_session *sess = work->sess;
9127 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
9128
9129 if (conn->dialect < SMB30_PROT_ID)
9130 return false;
9131
9132 if (work->next_smb2_rcv_hdr_off)
9133 rsp = ksmbd_resp_buf_next(work);
9134
9135 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9136 sess->user && !user_guest(sess->user) &&
9137 rsp->Status == STATUS_SUCCESS)
9138 return true;
9139 return false;
9140 }
9141