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