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