]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - fs/ksmbd/smb2pdu.c
Merge tag 'net-5.15-rc8' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net
[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 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4454 if (xattr_list_len < 0) {
4455 goto out;
4456 } else if (!xattr_list_len) {
4457 ksmbd_debug(SMB, "empty xattr in the file\n");
4458 goto out;
4459 }
4460
4461 buf_free_len =
4462 smb2_calc_max_out_buf_len(work, 8,
4463 le32_to_cpu(req->OutputBufferLength));
4464 if (buf_free_len < 0)
4465 goto out;
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 if (!S_ISDIR(stat.mode) &&
4511 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4512 file_info = (struct smb2_file_stream_info *)
4513 &rsp->Buffer[nbytes];
4514 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4515 "::$DATA", 7, conn->local_nls, 0);
4516 streamlen *= 2;
4517 file_info->StreamNameLength = cpu_to_le32(streamlen);
4518 file_info->StreamSize = 0;
4519 file_info->StreamAllocationSize = 0;
4520 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4521 }
4522
4523 /* last entry offset should be 0 */
4524 file_info->NextEntryOffset = 0;
4525 out:
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
4895 info = (struct filesystem_vol_info *)(rsp->Buffer);
4896 info->VolumeCreationTime = 0;
4897 /* Taking dummy value of serial number*/
4898 info->SerialNumber = cpu_to_le32(0xbc3ac512);
4899 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4900 share->name, PATH_MAX,
4901 conn->local_nls, 0);
4902 len = len * 2;
4903 info->VolumeLabelSize = cpu_to_le32(len);
4904 info->Reserved = 0;
4905 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4906 rsp->OutputBufferLength = cpu_to_le32(sz);
4907 inc_rfc1001_len(rsp_org, sz);
4908 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4909 break;
4910 }
4911 case FS_SIZE_INFORMATION:
4912 {
4913 struct filesystem_info *info;
4914
4915 info = (struct filesystem_info *)(rsp->Buffer);
4916 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4917 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4918 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4919 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4920 rsp->OutputBufferLength = cpu_to_le32(24);
4921 inc_rfc1001_len(rsp_org, 24);
4922 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4923 break;
4924 }
4925 case FS_FULL_SIZE_INFORMATION:
4926 {
4927 struct smb2_fs_full_size_info *info;
4928
4929 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4930 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4931 info->CallerAvailableAllocationUnits =
4932 cpu_to_le64(stfs.f_bavail);
4933 info->ActualAvailableAllocationUnits =
4934 cpu_to_le64(stfs.f_bfree);
4935 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4936 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4937 rsp->OutputBufferLength = cpu_to_le32(32);
4938 inc_rfc1001_len(rsp_org, 32);
4939 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4940 break;
4941 }
4942 case FS_OBJECT_ID_INFORMATION:
4943 {
4944 struct object_id_info *info;
4945
4946 info = (struct object_id_info *)(rsp->Buffer);
4947
4948 if (!user_guest(sess->user))
4949 memcpy(info->objid, user_passkey(sess->user), 16);
4950 else
4951 memset(info->objid, 0, 16);
4952
4953 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4954 info->extended_info.version = cpu_to_le32(1);
4955 info->extended_info.release = cpu_to_le32(1);
4956 info->extended_info.rel_date = 0;
4957 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
4958 rsp->OutputBufferLength = cpu_to_le32(64);
4959 inc_rfc1001_len(rsp_org, 64);
4960 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
4961 break;
4962 }
4963 case FS_SECTOR_SIZE_INFORMATION:
4964 {
4965 struct smb3_fs_ss_info *info;
4966
4967 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
4968
4969 info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
4970 info->PhysicalBytesPerSectorForAtomicity =
4971 cpu_to_le32(stfs.f_bsize);
4972 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
4973 info->FSEffPhysicalBytesPerSectorForAtomicity =
4974 cpu_to_le32(stfs.f_bsize);
4975 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
4976 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
4977 info->ByteOffsetForSectorAlignment = 0;
4978 info->ByteOffsetForPartitionAlignment = 0;
4979 rsp->OutputBufferLength = cpu_to_le32(28);
4980 inc_rfc1001_len(rsp_org, 28);
4981 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
4982 break;
4983 }
4984 case FS_CONTROL_INFORMATION:
4985 {
4986 /*
4987 * TODO : The current implementation is based on
4988 * test result with win7(NTFS) server. It's need to
4989 * modify this to get valid Quota values
4990 * from Linux kernel
4991 */
4992 struct smb2_fs_control_info *info;
4993
4994 info = (struct smb2_fs_control_info *)(rsp->Buffer);
4995 info->FreeSpaceStartFiltering = 0;
4996 info->FreeSpaceThreshold = 0;
4997 info->FreeSpaceStopFiltering = 0;
4998 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
4999 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5000 info->Padding = 0;
5001 rsp->OutputBufferLength = cpu_to_le32(48);
5002 inc_rfc1001_len(rsp_org, 48);
5003 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5004 break;
5005 }
5006 case FS_POSIX_INFORMATION:
5007 {
5008 struct filesystem_posix_info *info;
5009
5010 if (!work->tcon->posix_extensions) {
5011 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5012 rc = -EOPNOTSUPP;
5013 } else {
5014 info = (struct filesystem_posix_info *)(rsp->Buffer);
5015 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5016 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5017 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5018 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5019 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5020 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5021 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5022 rsp->OutputBufferLength = cpu_to_le32(56);
5023 inc_rfc1001_len(rsp_org, 56);
5024 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5025 }
5026 break;
5027 }
5028 default:
5029 path_put(&path);
5030 return -EOPNOTSUPP;
5031 }
5032 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5033 rsp,
5034 fs_infoclass_size);
5035 path_put(&path);
5036 return rc;
5037 }
5038
5039 static int smb2_get_info_sec(struct ksmbd_work *work,
5040 struct smb2_query_info_req *req,
5041 struct smb2_query_info_rsp *rsp, void *rsp_org)
5042 {
5043 struct ksmbd_file *fp;
5044 struct user_namespace *user_ns;
5045 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5046 struct smb_fattr fattr = {{0}};
5047 struct inode *inode;
5048 __u32 secdesclen;
5049 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5050 int addition_info = le32_to_cpu(req->AdditionalInformation);
5051 int rc;
5052
5053 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5054 PROTECTED_DACL_SECINFO |
5055 UNPROTECTED_DACL_SECINFO)) {
5056 pr_err("Unsupported addition info: 0x%x)\n",
5057 addition_info);
5058
5059 pntsd->revision = cpu_to_le16(1);
5060 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5061 pntsd->osidoffset = 0;
5062 pntsd->gsidoffset = 0;
5063 pntsd->sacloffset = 0;
5064 pntsd->dacloffset = 0;
5065
5066 secdesclen = sizeof(struct smb_ntsd);
5067 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5068 inc_rfc1001_len(rsp_org, secdesclen);
5069
5070 return 0;
5071 }
5072
5073 if (work->next_smb2_rcv_hdr_off) {
5074 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
5075 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5076 work->compound_fid);
5077 id = work->compound_fid;
5078 pid = work->compound_pfid;
5079 }
5080 }
5081
5082 if (!has_file_id(id)) {
5083 id = le64_to_cpu(req->VolatileFileId);
5084 pid = le64_to_cpu(req->PersistentFileId);
5085 }
5086
5087 fp = ksmbd_lookup_fd_slow(work, id, pid);
5088 if (!fp)
5089 return -ENOENT;
5090
5091 user_ns = file_mnt_user_ns(fp->filp);
5092 inode = file_inode(fp->filp);
5093 ksmbd_acls_fattr(&fattr, user_ns, inode);
5094
5095 if (test_share_config_flag(work->tcon->share_conf,
5096 KSMBD_SHARE_FLAG_ACL_XATTR))
5097 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5098 fp->filp->f_path.dentry, &ppntsd);
5099
5100 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5101 &secdesclen, &fattr);
5102 posix_acl_release(fattr.cf_acls);
5103 posix_acl_release(fattr.cf_dacls);
5104 kfree(ppntsd);
5105 ksmbd_fd_put(work, fp);
5106 if (rc)
5107 return rc;
5108
5109 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5110 inc_rfc1001_len(rsp_org, secdesclen);
5111 return 0;
5112 }
5113
5114 /**
5115 * smb2_query_info() - handler for smb2 query info command
5116 * @work: smb work containing query info request buffer
5117 *
5118 * Return: 0 on success, otherwise error
5119 */
5120 int smb2_query_info(struct ksmbd_work *work)
5121 {
5122 struct smb2_query_info_req *req;
5123 struct smb2_query_info_rsp *rsp, *rsp_org;
5124 int rc = 0;
5125
5126 rsp_org = work->response_buf;
5127 WORK_BUFFERS(work, req, rsp);
5128
5129 ksmbd_debug(SMB, "GOT query info request\n");
5130
5131 switch (req->InfoType) {
5132 case SMB2_O_INFO_FILE:
5133 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5134 rc = smb2_get_info_file(work, req, rsp, (void *)rsp_org);
5135 break;
5136 case SMB2_O_INFO_FILESYSTEM:
5137 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5138 rc = smb2_get_info_filesystem(work, req, rsp, (void *)rsp_org);
5139 break;
5140 case SMB2_O_INFO_SECURITY:
5141 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5142 rc = smb2_get_info_sec(work, req, rsp, (void *)rsp_org);
5143 break;
5144 default:
5145 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5146 req->InfoType);
5147 rc = -EOPNOTSUPP;
5148 }
5149
5150 if (rc < 0) {
5151 if (rc == -EACCES)
5152 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5153 else if (rc == -ENOENT)
5154 rsp->hdr.Status = STATUS_FILE_CLOSED;
5155 else if (rc == -EIO)
5156 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5157 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5158 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5159 smb2_set_err_rsp(work);
5160
5161 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5162 rc);
5163 return rc;
5164 }
5165 rsp->StructureSize = cpu_to_le16(9);
5166 rsp->OutputBufferOffset = cpu_to_le16(72);
5167 inc_rfc1001_len(rsp_org, 8);
5168 return 0;
5169 }
5170
5171 /**
5172 * smb2_close_pipe() - handler for closing IPC pipe
5173 * @work: smb work containing close request buffer
5174 *
5175 * Return: 0
5176 */
5177 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5178 {
5179 u64 id;
5180 struct smb2_close_req *req = work->request_buf;
5181 struct smb2_close_rsp *rsp = work->response_buf;
5182
5183 id = le64_to_cpu(req->VolatileFileId);
5184 ksmbd_session_rpc_close(work->sess, id);
5185
5186 rsp->StructureSize = cpu_to_le16(60);
5187 rsp->Flags = 0;
5188 rsp->Reserved = 0;
5189 rsp->CreationTime = 0;
5190 rsp->LastAccessTime = 0;
5191 rsp->LastWriteTime = 0;
5192 rsp->ChangeTime = 0;
5193 rsp->AllocationSize = 0;
5194 rsp->EndOfFile = 0;
5195 rsp->Attributes = 0;
5196 inc_rfc1001_len(rsp, 60);
5197 return 0;
5198 }
5199
5200 /**
5201 * smb2_close() - handler for smb2 close file command
5202 * @work: smb work containing close request buffer
5203 *
5204 * Return: 0
5205 */
5206 int smb2_close(struct ksmbd_work *work)
5207 {
5208 u64 volatile_id = KSMBD_NO_FID;
5209 u64 sess_id;
5210 struct smb2_close_req *req;
5211 struct smb2_close_rsp *rsp;
5212 struct smb2_close_rsp *rsp_org;
5213 struct ksmbd_conn *conn = work->conn;
5214 struct ksmbd_file *fp;
5215 struct inode *inode;
5216 u64 time;
5217 int err = 0;
5218
5219 rsp_org = work->response_buf;
5220 WORK_BUFFERS(work, req, rsp);
5221
5222 if (test_share_config_flag(work->tcon->share_conf,
5223 KSMBD_SHARE_FLAG_PIPE)) {
5224 ksmbd_debug(SMB, "IPC pipe close request\n");
5225 return smb2_close_pipe(work);
5226 }
5227
5228 sess_id = le64_to_cpu(req->hdr.SessionId);
5229 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5230 sess_id = work->compound_sid;
5231
5232 work->compound_sid = 0;
5233 if (check_session_id(conn, sess_id)) {
5234 work->compound_sid = sess_id;
5235 } else {
5236 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5237 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5238 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5239 err = -EBADF;
5240 goto out;
5241 }
5242
5243 if (work->next_smb2_rcv_hdr_off &&
5244 !has_file_id(le64_to_cpu(req->VolatileFileId))) {
5245 if (!has_file_id(work->compound_fid)) {
5246 /* file already closed, return FILE_CLOSED */
5247 ksmbd_debug(SMB, "file already closed\n");
5248 rsp->hdr.Status = STATUS_FILE_CLOSED;
5249 err = -EBADF;
5250 goto out;
5251 } else {
5252 ksmbd_debug(SMB,
5253 "Compound request set FID = %llu:%llu\n",
5254 work->compound_fid,
5255 work->compound_pfid);
5256 volatile_id = work->compound_fid;
5257
5258 /* file closed, stored id is not valid anymore */
5259 work->compound_fid = KSMBD_NO_FID;
5260 work->compound_pfid = KSMBD_NO_FID;
5261 }
5262 } else {
5263 volatile_id = le64_to_cpu(req->VolatileFileId);
5264 }
5265 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5266
5267 rsp->StructureSize = cpu_to_le16(60);
5268 rsp->Reserved = 0;
5269
5270 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5271 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5272 if (!fp) {
5273 err = -ENOENT;
5274 goto out;
5275 }
5276
5277 inode = file_inode(fp->filp);
5278 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5279 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5280 cpu_to_le64(inode->i_blocks << 9);
5281 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5282 rsp->Attributes = fp->f_ci->m_fattr;
5283 rsp->CreationTime = cpu_to_le64(fp->create_time);
5284 time = ksmbd_UnixTimeToNT(inode->i_atime);
5285 rsp->LastAccessTime = cpu_to_le64(time);
5286 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5287 rsp->LastWriteTime = cpu_to_le64(time);
5288 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5289 rsp->ChangeTime = cpu_to_le64(time);
5290 ksmbd_fd_put(work, fp);
5291 } else {
5292 rsp->Flags = 0;
5293 rsp->AllocationSize = 0;
5294 rsp->EndOfFile = 0;
5295 rsp->Attributes = 0;
5296 rsp->CreationTime = 0;
5297 rsp->LastAccessTime = 0;
5298 rsp->LastWriteTime = 0;
5299 rsp->ChangeTime = 0;
5300 }
5301
5302 err = ksmbd_close_fd(work, volatile_id);
5303 out:
5304 if (err) {
5305 if (rsp->hdr.Status == 0)
5306 rsp->hdr.Status = STATUS_FILE_CLOSED;
5307 smb2_set_err_rsp(work);
5308 } else {
5309 inc_rfc1001_len(rsp_org, 60);
5310 }
5311
5312 return 0;
5313 }
5314
5315 /**
5316 * smb2_echo() - handler for smb2 echo(ping) command
5317 * @work: smb work containing echo request buffer
5318 *
5319 * Return: 0
5320 */
5321 int smb2_echo(struct ksmbd_work *work)
5322 {
5323 struct smb2_echo_rsp *rsp = work->response_buf;
5324
5325 rsp->StructureSize = cpu_to_le16(4);
5326 rsp->Reserved = 0;
5327 inc_rfc1001_len(rsp, 4);
5328 return 0;
5329 }
5330
5331 static int smb2_rename(struct ksmbd_work *work,
5332 struct ksmbd_file *fp,
5333 struct user_namespace *user_ns,
5334 struct smb2_file_rename_info *file_info,
5335 struct nls_table *local_nls)
5336 {
5337 struct ksmbd_share_config *share = fp->tcon->share_conf;
5338 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5339 char *pathname = NULL;
5340 struct path path;
5341 bool file_present = true;
5342 int rc;
5343
5344 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5345 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5346 if (!pathname)
5347 return -ENOMEM;
5348
5349 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5350 if (IS_ERR(abs_oldname)) {
5351 rc = -EINVAL;
5352 goto out;
5353 }
5354 old_name = strrchr(abs_oldname, '/');
5355 if (old_name && old_name[1] != '\0') {
5356 old_name++;
5357 } else {
5358 ksmbd_debug(SMB, "can't get last component in path %s\n",
5359 abs_oldname);
5360 rc = -ENOENT;
5361 goto out;
5362 }
5363
5364 new_name = smb2_get_name(share,
5365 file_info->FileName,
5366 le32_to_cpu(file_info->FileNameLength),
5367 local_nls);
5368 if (IS_ERR(new_name)) {
5369 rc = PTR_ERR(new_name);
5370 goto out;
5371 }
5372
5373 if (strchr(new_name, ':')) {
5374 int s_type;
5375 char *xattr_stream_name, *stream_name = NULL;
5376 size_t xattr_stream_size;
5377 int len;
5378
5379 rc = parse_stream_name(new_name, &stream_name, &s_type);
5380 if (rc < 0)
5381 goto out;
5382
5383 len = strlen(new_name);
5384 if (len > 0 && new_name[len - 1] != '/') {
5385 pr_err("not allow base filename in rename\n");
5386 rc = -ESHARE;
5387 goto out;
5388 }
5389
5390 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5391 &xattr_stream_name,
5392 &xattr_stream_size,
5393 s_type);
5394 if (rc)
5395 goto out;
5396
5397 rc = ksmbd_vfs_setxattr(user_ns,
5398 fp->filp->f_path.dentry,
5399 xattr_stream_name,
5400 NULL, 0, 0);
5401 if (rc < 0) {
5402 pr_err("failed to store stream name in xattr: %d\n",
5403 rc);
5404 rc = -EINVAL;
5405 goto out;
5406 }
5407
5408 goto out;
5409 }
5410
5411 ksmbd_debug(SMB, "new name %s\n", new_name);
5412 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5413 if (rc) {
5414 if (rc != -ENOENT)
5415 goto out;
5416 file_present = false;
5417 } else {
5418 path_put(&path);
5419 }
5420
5421 if (ksmbd_share_veto_filename(share, new_name)) {
5422 rc = -ENOENT;
5423 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5424 goto out;
5425 }
5426
5427 if (file_info->ReplaceIfExists) {
5428 if (file_present) {
5429 rc = ksmbd_vfs_remove_file(work, new_name);
5430 if (rc) {
5431 if (rc != -ENOTEMPTY)
5432 rc = -EINVAL;
5433 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5434 new_name, rc);
5435 goto out;
5436 }
5437 }
5438 } else {
5439 if (file_present &&
5440 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5441 rc = -EEXIST;
5442 ksmbd_debug(SMB,
5443 "cannot rename already existing file\n");
5444 goto out;
5445 }
5446 }
5447
5448 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5449 out:
5450 kfree(pathname);
5451 if (!IS_ERR(new_name))
5452 kfree(new_name);
5453 return rc;
5454 }
5455
5456 static int smb2_create_link(struct ksmbd_work *work,
5457 struct ksmbd_share_config *share,
5458 struct smb2_file_link_info *file_info,
5459 unsigned int buf_len, struct file *filp,
5460 struct nls_table *local_nls)
5461 {
5462 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5463 struct path path;
5464 bool file_present = true;
5465 int rc;
5466
5467 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5468 le32_to_cpu(file_info->FileNameLength))
5469 return -EINVAL;
5470
5471 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5472 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5473 if (!pathname)
5474 return -ENOMEM;
5475
5476 link_name = smb2_get_name(share,
5477 file_info->FileName,
5478 le32_to_cpu(file_info->FileNameLength),
5479 local_nls);
5480 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5481 rc = -EINVAL;
5482 goto out;
5483 }
5484
5485 ksmbd_debug(SMB, "link name is %s\n", link_name);
5486 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5487 if (IS_ERR(target_name)) {
5488 rc = -EINVAL;
5489 goto out;
5490 }
5491
5492 ksmbd_debug(SMB, "target name is %s\n", target_name);
5493 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5494 if (rc) {
5495 if (rc != -ENOENT)
5496 goto out;
5497 file_present = false;
5498 } else {
5499 path_put(&path);
5500 }
5501
5502 if (file_info->ReplaceIfExists) {
5503 if (file_present) {
5504 rc = ksmbd_vfs_remove_file(work, link_name);
5505 if (rc) {
5506 rc = -EINVAL;
5507 ksmbd_debug(SMB, "cannot delete %s\n",
5508 link_name);
5509 goto out;
5510 }
5511 }
5512 } else {
5513 if (file_present) {
5514 rc = -EEXIST;
5515 ksmbd_debug(SMB, "link already exists\n");
5516 goto out;
5517 }
5518 }
5519
5520 rc = ksmbd_vfs_link(work, target_name, link_name);
5521 if (rc)
5522 rc = -EINVAL;
5523 out:
5524 if (!IS_ERR(link_name))
5525 kfree(link_name);
5526 kfree(pathname);
5527 return rc;
5528 }
5529
5530 static int set_file_basic_info(struct ksmbd_file *fp,
5531 struct smb2_file_basic_info *file_info,
5532 struct ksmbd_share_config *share)
5533 {
5534 struct iattr attrs;
5535 struct file *filp;
5536 struct inode *inode;
5537 struct user_namespace *user_ns;
5538 int rc = 0;
5539
5540 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5541 return -EACCES;
5542
5543 attrs.ia_valid = 0;
5544 filp = fp->filp;
5545 inode = file_inode(filp);
5546 user_ns = file_mnt_user_ns(filp);
5547
5548 if (file_info->CreationTime)
5549 fp->create_time = le64_to_cpu(file_info->CreationTime);
5550
5551 if (file_info->LastAccessTime) {
5552 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5553 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5554 }
5555
5556 attrs.ia_valid |= ATTR_CTIME;
5557 if (file_info->ChangeTime)
5558 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5559 else
5560 attrs.ia_ctime = inode->i_ctime;
5561
5562 if (file_info->LastWriteTime) {
5563 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5564 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5565 }
5566
5567 if (file_info->Attributes) {
5568 if (!S_ISDIR(inode->i_mode) &&
5569 file_info->Attributes & ATTR_DIRECTORY_LE) {
5570 pr_err("can't change a file to a directory\n");
5571 return -EINVAL;
5572 }
5573
5574 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == ATTR_NORMAL_LE))
5575 fp->f_ci->m_fattr = file_info->Attributes |
5576 (fp->f_ci->m_fattr & ATTR_DIRECTORY_LE);
5577 }
5578
5579 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5580 (file_info->CreationTime || file_info->Attributes)) {
5581 struct xattr_dos_attrib da = {0};
5582
5583 da.version = 4;
5584 da.itime = fp->itime;
5585 da.create_time = fp->create_time;
5586 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5587 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5588 XATTR_DOSINFO_ITIME;
5589
5590 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5591 filp->f_path.dentry, &da);
5592 if (rc)
5593 ksmbd_debug(SMB,
5594 "failed to restore file attribute in EA\n");
5595 rc = 0;
5596 }
5597
5598 if (attrs.ia_valid) {
5599 struct dentry *dentry = filp->f_path.dentry;
5600 struct inode *inode = d_inode(dentry);
5601
5602 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5603 return -EACCES;
5604
5605 inode_lock(inode);
5606 inode->i_ctime = attrs.ia_ctime;
5607 attrs.ia_valid &= ~ATTR_CTIME;
5608 rc = notify_change(user_ns, dentry, &attrs, NULL);
5609 inode_unlock(inode);
5610 }
5611 return rc;
5612 }
5613
5614 static int set_file_allocation_info(struct ksmbd_work *work,
5615 struct ksmbd_file *fp,
5616 struct smb2_file_alloc_info *file_alloc_info)
5617 {
5618 /*
5619 * TODO : It's working fine only when store dos attributes
5620 * is not yes. need to implement a logic which works
5621 * properly with any smb.conf option
5622 */
5623
5624 loff_t alloc_blks;
5625 struct inode *inode;
5626 int rc;
5627
5628 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5629 return -EACCES;
5630
5631 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5632 inode = file_inode(fp->filp);
5633
5634 if (alloc_blks > inode->i_blocks) {
5635 smb_break_all_levII_oplock(work, fp, 1);
5636 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5637 alloc_blks * 512);
5638 if (rc && rc != -EOPNOTSUPP) {
5639 pr_err("vfs_fallocate is failed : %d\n", rc);
5640 return rc;
5641 }
5642 } else if (alloc_blks < inode->i_blocks) {
5643 loff_t size;
5644
5645 /*
5646 * Allocation size could be smaller than original one
5647 * which means allocated blocks in file should be
5648 * deallocated. use truncate to cut out it, but inode
5649 * size is also updated with truncate offset.
5650 * inode size is retained by backup inode size.
5651 */
5652 size = i_size_read(inode);
5653 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5654 if (rc) {
5655 pr_err("truncate failed! filename : %s, err %d\n",
5656 fp->filename, rc);
5657 return rc;
5658 }
5659 if (size < alloc_blks * 512)
5660 i_size_write(inode, size);
5661 }
5662 return 0;
5663 }
5664
5665 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5666 struct smb2_file_eof_info *file_eof_info)
5667 {
5668 loff_t newsize;
5669 struct inode *inode;
5670 int rc;
5671
5672 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5673 return -EACCES;
5674
5675 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5676 inode = file_inode(fp->filp);
5677
5678 /*
5679 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5680 * on FAT32 shared device, truncate execution time is too long
5681 * and network error could cause from windows client. because
5682 * truncate of some filesystem like FAT32 fill zero data in
5683 * truncated range.
5684 */
5685 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5686 ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5687 fp->filename, newsize);
5688 rc = ksmbd_vfs_truncate(work, fp, newsize);
5689 if (rc) {
5690 ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5691 fp->filename, rc);
5692 if (rc != -EAGAIN)
5693 rc = -EBADF;
5694 return rc;
5695 }
5696 }
5697 return 0;
5698 }
5699
5700 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5701 struct smb2_file_rename_info *rename_info,
5702 unsigned int buf_len)
5703 {
5704 struct user_namespace *user_ns;
5705 struct ksmbd_file *parent_fp;
5706 struct dentry *parent;
5707 struct dentry *dentry = fp->filp->f_path.dentry;
5708 int ret;
5709
5710 if (!(fp->daccess & FILE_DELETE_LE)) {
5711 pr_err("no right to delete : 0x%x\n", fp->daccess);
5712 return -EACCES;
5713 }
5714
5715 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5716 le32_to_cpu(rename_info->FileNameLength))
5717 return -EINVAL;
5718
5719 user_ns = file_mnt_user_ns(fp->filp);
5720 if (ksmbd_stream_fd(fp))
5721 goto next;
5722
5723 parent = dget_parent(dentry);
5724 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5725 if (ret) {
5726 dput(parent);
5727 return ret;
5728 }
5729
5730 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5731 inode_unlock(d_inode(parent));
5732 dput(parent);
5733
5734 if (parent_fp) {
5735 if (parent_fp->daccess & FILE_DELETE_LE) {
5736 pr_err("parent dir is opened with delete access\n");
5737 return -ESHARE;
5738 }
5739 }
5740 next:
5741 return smb2_rename(work, fp, user_ns, rename_info,
5742 work->sess->conn->local_nls);
5743 }
5744
5745 static int set_file_disposition_info(struct ksmbd_file *fp,
5746 struct smb2_file_disposition_info *file_info)
5747 {
5748 struct inode *inode;
5749
5750 if (!(fp->daccess & FILE_DELETE_LE)) {
5751 pr_err("no right to delete : 0x%x\n", fp->daccess);
5752 return -EACCES;
5753 }
5754
5755 inode = file_inode(fp->filp);
5756 if (file_info->DeletePending) {
5757 if (S_ISDIR(inode->i_mode) &&
5758 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5759 return -EBUSY;
5760 ksmbd_set_inode_pending_delete(fp);
5761 } else {
5762 ksmbd_clear_inode_pending_delete(fp);
5763 }
5764 return 0;
5765 }
5766
5767 static int set_file_position_info(struct ksmbd_file *fp,
5768 struct smb2_file_pos_info *file_info)
5769 {
5770 loff_t current_byte_offset;
5771 unsigned long sector_size;
5772 struct inode *inode;
5773
5774 inode = file_inode(fp->filp);
5775 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5776 sector_size = inode->i_sb->s_blocksize;
5777
5778 if (current_byte_offset < 0 ||
5779 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5780 current_byte_offset & (sector_size - 1))) {
5781 pr_err("CurrentByteOffset is not valid : %llu\n",
5782 current_byte_offset);
5783 return -EINVAL;
5784 }
5785
5786 fp->filp->f_pos = current_byte_offset;
5787 return 0;
5788 }
5789
5790 static int set_file_mode_info(struct ksmbd_file *fp,
5791 struct smb2_file_mode_info *file_info)
5792 {
5793 __le32 mode;
5794
5795 mode = file_info->Mode;
5796
5797 if ((mode & ~FILE_MODE_INFO_MASK) ||
5798 (mode & FILE_SYNCHRONOUS_IO_ALERT_LE &&
5799 mode & FILE_SYNCHRONOUS_IO_NONALERT_LE)) {
5800 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5801 return -EINVAL;
5802 }
5803
5804 /*
5805 * TODO : need to implement consideration for
5806 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5807 */
5808 ksmbd_vfs_set_fadvise(fp->filp, mode);
5809 fp->coption = mode;
5810 return 0;
5811 }
5812
5813 /**
5814 * smb2_set_info_file() - handler for smb2 set info command
5815 * @work: smb work containing set info command buffer
5816 * @fp: ksmbd_file pointer
5817 * @info_class: smb2 set info class
5818 * @share: ksmbd_share_config pointer
5819 *
5820 * Return: 0 on success, otherwise error
5821 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5822 */
5823 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5824 struct smb2_set_info_req *req,
5825 struct ksmbd_share_config *share)
5826 {
5827 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5828
5829 switch (req->FileInfoClass) {
5830 case FILE_BASIC_INFORMATION:
5831 {
5832 if (buf_len < sizeof(struct smb2_file_basic_info))
5833 return -EINVAL;
5834
5835 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5836 }
5837 case FILE_ALLOCATION_INFORMATION:
5838 {
5839 if (buf_len < sizeof(struct smb2_file_alloc_info))
5840 return -EINVAL;
5841
5842 return set_file_allocation_info(work, fp,
5843 (struct smb2_file_alloc_info *)req->Buffer);
5844 }
5845 case FILE_END_OF_FILE_INFORMATION:
5846 {
5847 if (buf_len < sizeof(struct smb2_file_eof_info))
5848 return -EINVAL;
5849
5850 return set_end_of_file_info(work, fp,
5851 (struct smb2_file_eof_info *)req->Buffer);
5852 }
5853 case FILE_RENAME_INFORMATION:
5854 {
5855 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5856 ksmbd_debug(SMB,
5857 "User does not have write permission\n");
5858 return -EACCES;
5859 }
5860
5861 if (buf_len < sizeof(struct smb2_file_rename_info))
5862 return -EINVAL;
5863
5864 return set_rename_info(work, fp,
5865 (struct smb2_file_rename_info *)req->Buffer,
5866 buf_len);
5867 }
5868 case FILE_LINK_INFORMATION:
5869 {
5870 if (buf_len < sizeof(struct smb2_file_link_info))
5871 return -EINVAL;
5872
5873 return smb2_create_link(work, work->tcon->share_conf,
5874 (struct smb2_file_link_info *)req->Buffer,
5875 buf_len, fp->filp,
5876 work->sess->conn->local_nls);
5877 }
5878 case FILE_DISPOSITION_INFORMATION:
5879 {
5880 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5881 ksmbd_debug(SMB,
5882 "User does not have write permission\n");
5883 return -EACCES;
5884 }
5885
5886 if (buf_len < sizeof(struct smb2_file_disposition_info))
5887 return -EINVAL;
5888
5889 return set_file_disposition_info(fp,
5890 (struct smb2_file_disposition_info *)req->Buffer);
5891 }
5892 case FILE_FULL_EA_INFORMATION:
5893 {
5894 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5895 pr_err("Not permitted to write ext attr: 0x%x\n",
5896 fp->daccess);
5897 return -EACCES;
5898 }
5899
5900 if (buf_len < sizeof(struct smb2_ea_info))
5901 return -EINVAL;
5902
5903 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5904 buf_len, &fp->filp->f_path);
5905 }
5906 case FILE_POSITION_INFORMATION:
5907 {
5908 if (buf_len < sizeof(struct smb2_file_pos_info))
5909 return -EINVAL;
5910
5911 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5912 }
5913 case FILE_MODE_INFORMATION:
5914 {
5915 if (buf_len < sizeof(struct smb2_file_mode_info))
5916 return -EINVAL;
5917
5918 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5919 }
5920 }
5921
5922 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5923 return -EOPNOTSUPP;
5924 }
5925
5926 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5927 char *buffer, int buf_len)
5928 {
5929 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5930
5931 fp->saccess |= FILE_SHARE_DELETE_LE;
5932
5933 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5934 buf_len, false);
5935 }
5936
5937 /**
5938 * smb2_set_info() - handler for smb2 set info command handler
5939 * @work: smb work containing set info request buffer
5940 *
5941 * Return: 0 on success, otherwise error
5942 */
5943 int smb2_set_info(struct ksmbd_work *work)
5944 {
5945 struct smb2_set_info_req *req;
5946 struct smb2_set_info_rsp *rsp, *rsp_org;
5947 struct ksmbd_file *fp;
5948 int rc = 0;
5949 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5950
5951 ksmbd_debug(SMB, "Received set info request\n");
5952
5953 rsp_org = work->response_buf;
5954 if (work->next_smb2_rcv_hdr_off) {
5955 req = ksmbd_req_buf_next(work);
5956 rsp = ksmbd_resp_buf_next(work);
5957 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
5958 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5959 work->compound_fid);
5960 id = work->compound_fid;
5961 pid = work->compound_pfid;
5962 }
5963 } else {
5964 req = work->request_buf;
5965 rsp = work->response_buf;
5966 }
5967
5968 if (!has_file_id(id)) {
5969 id = le64_to_cpu(req->VolatileFileId);
5970 pid = le64_to_cpu(req->PersistentFileId);
5971 }
5972
5973 fp = ksmbd_lookup_fd_slow(work, id, pid);
5974 if (!fp) {
5975 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
5976 rc = -ENOENT;
5977 goto err_out;
5978 }
5979
5980 switch (req->InfoType) {
5981 case SMB2_O_INFO_FILE:
5982 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5983 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
5984 break;
5985 case SMB2_O_INFO_SECURITY:
5986 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5987 if (ksmbd_override_fsids(work)) {
5988 rc = -ENOMEM;
5989 goto err_out;
5990 }
5991 rc = smb2_set_info_sec(fp,
5992 le32_to_cpu(req->AdditionalInformation),
5993 req->Buffer,
5994 le32_to_cpu(req->BufferLength));
5995 ksmbd_revert_fsids(work);
5996 break;
5997 default:
5998 rc = -EOPNOTSUPP;
5999 }
6000
6001 if (rc < 0)
6002 goto err_out;
6003
6004 rsp->StructureSize = cpu_to_le16(2);
6005 inc_rfc1001_len(rsp_org, 2);
6006 ksmbd_fd_put(work, fp);
6007 return 0;
6008
6009 err_out:
6010 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6011 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6012 else if (rc == -EINVAL)
6013 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6014 else if (rc == -ESHARE)
6015 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6016 else if (rc == -ENOENT)
6017 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6018 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6019 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6020 else if (rc == -EAGAIN)
6021 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6022 else if (rc == -EBADF || rc == -ESTALE)
6023 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6024 else if (rc == -EEXIST)
6025 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6026 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6027 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6028 smb2_set_err_rsp(work);
6029 ksmbd_fd_put(work, fp);
6030 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6031 return rc;
6032 }
6033
6034 /**
6035 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6036 * @work: smb work containing read IPC pipe command buffer
6037 *
6038 * Return: 0 on success, otherwise error
6039 */
6040 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6041 {
6042 int nbytes = 0, err;
6043 u64 id;
6044 struct ksmbd_rpc_command *rpc_resp;
6045 struct smb2_read_req *req = work->request_buf;
6046 struct smb2_read_rsp *rsp = work->response_buf;
6047
6048 id = le64_to_cpu(req->VolatileFileId);
6049
6050 inc_rfc1001_len(rsp, 16);
6051 rpc_resp = ksmbd_rpc_read(work->sess, id);
6052 if (rpc_resp) {
6053 if (rpc_resp->flags != KSMBD_RPC_OK) {
6054 err = -EINVAL;
6055 goto out;
6056 }
6057
6058 work->aux_payload_buf =
6059 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6060 if (!work->aux_payload_buf) {
6061 err = -ENOMEM;
6062 goto out;
6063 }
6064
6065 memcpy(work->aux_payload_buf, rpc_resp->payload,
6066 rpc_resp->payload_sz);
6067
6068 nbytes = rpc_resp->payload_sz;
6069 work->resp_hdr_sz = get_rfc1002_len(rsp) + 4;
6070 work->aux_payload_sz = nbytes;
6071 kvfree(rpc_resp);
6072 }
6073
6074 rsp->StructureSize = cpu_to_le16(17);
6075 rsp->DataOffset = 80;
6076 rsp->Reserved = 0;
6077 rsp->DataLength = cpu_to_le32(nbytes);
6078 rsp->DataRemaining = 0;
6079 rsp->Reserved2 = 0;
6080 inc_rfc1001_len(rsp, nbytes);
6081 return 0;
6082
6083 out:
6084 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6085 smb2_set_err_rsp(work);
6086 kvfree(rpc_resp);
6087 return err;
6088 }
6089
6090 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6091 struct smb2_read_req *req, void *data_buf,
6092 size_t length)
6093 {
6094 struct smb2_buffer_desc_v1 *desc =
6095 (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6096 int err;
6097
6098 if (work->conn->dialect == SMB30_PROT_ID &&
6099 req->Channel != SMB2_CHANNEL_RDMA_V1)
6100 return -EINVAL;
6101
6102 if (req->ReadChannelInfoOffset == 0 ||
6103 le16_to_cpu(req->ReadChannelInfoLength) < sizeof(*desc))
6104 return -EINVAL;
6105
6106 work->need_invalidate_rkey =
6107 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6108 work->remote_key = le32_to_cpu(desc->token);
6109
6110 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6111 le32_to_cpu(desc->token),
6112 le64_to_cpu(desc->offset),
6113 le32_to_cpu(desc->length));
6114 if (err)
6115 return err;
6116
6117 return length;
6118 }
6119
6120 /**
6121 * smb2_read() - handler for smb2 read from file
6122 * @work: smb work containing read command buffer
6123 *
6124 * Return: 0 on success, otherwise error
6125 */
6126 int smb2_read(struct ksmbd_work *work)
6127 {
6128 struct ksmbd_conn *conn = work->conn;
6129 struct smb2_read_req *req;
6130 struct smb2_read_rsp *rsp, *rsp_org;
6131 struct ksmbd_file *fp;
6132 loff_t offset;
6133 size_t length, mincount;
6134 ssize_t nbytes = 0, remain_bytes = 0;
6135 int err = 0;
6136
6137 rsp_org = work->response_buf;
6138 WORK_BUFFERS(work, req, rsp);
6139
6140 if (test_share_config_flag(work->tcon->share_conf,
6141 KSMBD_SHARE_FLAG_PIPE)) {
6142 ksmbd_debug(SMB, "IPC pipe read request\n");
6143 return smb2_read_pipe(work);
6144 }
6145
6146 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6147 le64_to_cpu(req->PersistentFileId));
6148 if (!fp) {
6149 err = -ENOENT;
6150 goto out;
6151 }
6152
6153 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6154 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6155 err = -EACCES;
6156 goto out;
6157 }
6158
6159 offset = le64_to_cpu(req->Offset);
6160 length = le32_to_cpu(req->Length);
6161 mincount = le32_to_cpu(req->MinimumCount);
6162
6163 if (length > conn->vals->max_read_size) {
6164 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6165 conn->vals->max_read_size);
6166 err = -EINVAL;
6167 goto out;
6168 }
6169
6170 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6171 fp->filp->f_path.dentry, offset, length);
6172
6173 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6174 if (!work->aux_payload_buf) {
6175 err = -ENOMEM;
6176 goto out;
6177 }
6178
6179 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6180 if (nbytes < 0) {
6181 err = nbytes;
6182 goto out;
6183 }
6184
6185 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6186 kvfree(work->aux_payload_buf);
6187 work->aux_payload_buf = NULL;
6188 rsp->hdr.Status = STATUS_END_OF_FILE;
6189 smb2_set_err_rsp(work);
6190 ksmbd_fd_put(work, fp);
6191 return 0;
6192 }
6193
6194 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6195 nbytes, offset, mincount);
6196
6197 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6198 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6199 /* write data to the client using rdma channel */
6200 remain_bytes = smb2_read_rdma_channel(work, req,
6201 work->aux_payload_buf,
6202 nbytes);
6203 kvfree(work->aux_payload_buf);
6204 work->aux_payload_buf = NULL;
6205
6206 nbytes = 0;
6207 if (remain_bytes < 0) {
6208 err = (int)remain_bytes;
6209 goto out;
6210 }
6211 }
6212
6213 rsp->StructureSize = cpu_to_le16(17);
6214 rsp->DataOffset = 80;
6215 rsp->Reserved = 0;
6216 rsp->DataLength = cpu_to_le32(nbytes);
6217 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6218 rsp->Reserved2 = 0;
6219 inc_rfc1001_len(rsp_org, 16);
6220 work->resp_hdr_sz = get_rfc1002_len(rsp_org) + 4;
6221 work->aux_payload_sz = nbytes;
6222 inc_rfc1001_len(rsp_org, nbytes);
6223 ksmbd_fd_put(work, fp);
6224 return 0;
6225
6226 out:
6227 if (err) {
6228 if (err == -EISDIR)
6229 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6230 else if (err == -EAGAIN)
6231 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6232 else if (err == -ENOENT)
6233 rsp->hdr.Status = STATUS_FILE_CLOSED;
6234 else if (err == -EACCES)
6235 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6236 else if (err == -ESHARE)
6237 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6238 else if (err == -EINVAL)
6239 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6240 else
6241 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6242
6243 smb2_set_err_rsp(work);
6244 }
6245 ksmbd_fd_put(work, fp);
6246 return err;
6247 }
6248
6249 /**
6250 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6251 * @work: smb work containing write IPC pipe command buffer
6252 *
6253 * Return: 0 on success, otherwise error
6254 */
6255 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6256 {
6257 struct smb2_write_req *req = work->request_buf;
6258 struct smb2_write_rsp *rsp = work->response_buf;
6259 struct ksmbd_rpc_command *rpc_resp;
6260 u64 id = 0;
6261 int err = 0, ret = 0;
6262 char *data_buf;
6263 size_t length;
6264
6265 length = le32_to_cpu(req->Length);
6266 id = le64_to_cpu(req->VolatileFileId);
6267
6268 if (le16_to_cpu(req->DataOffset) ==
6269 (offsetof(struct smb2_write_req, Buffer) - 4)) {
6270 data_buf = (char *)&req->Buffer[0];
6271 } else {
6272 if ((u64)le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req)) {
6273 pr_err("invalid write data offset %u, smb_len %u\n",
6274 le16_to_cpu(req->DataOffset),
6275 get_rfc1002_len(req));
6276 err = -EINVAL;
6277 goto out;
6278 }
6279
6280 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6281 le16_to_cpu(req->DataOffset));
6282 }
6283
6284 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6285 if (rpc_resp) {
6286 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6287 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6288 kvfree(rpc_resp);
6289 smb2_set_err_rsp(work);
6290 return -EOPNOTSUPP;
6291 }
6292 if (rpc_resp->flags != KSMBD_RPC_OK) {
6293 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6294 smb2_set_err_rsp(work);
6295 kvfree(rpc_resp);
6296 return ret;
6297 }
6298 kvfree(rpc_resp);
6299 }
6300
6301 rsp->StructureSize = cpu_to_le16(17);
6302 rsp->DataOffset = 0;
6303 rsp->Reserved = 0;
6304 rsp->DataLength = cpu_to_le32(length);
6305 rsp->DataRemaining = 0;
6306 rsp->Reserved2 = 0;
6307 inc_rfc1001_len(rsp, 16);
6308 return 0;
6309 out:
6310 if (err) {
6311 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6312 smb2_set_err_rsp(work);
6313 }
6314
6315 return err;
6316 }
6317
6318 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6319 struct smb2_write_req *req,
6320 struct ksmbd_file *fp,
6321 loff_t offset, size_t length, bool sync)
6322 {
6323 struct smb2_buffer_desc_v1 *desc;
6324 char *data_buf;
6325 int ret;
6326 ssize_t nbytes;
6327
6328 desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6329
6330 if (work->conn->dialect == SMB30_PROT_ID &&
6331 req->Channel != SMB2_CHANNEL_RDMA_V1)
6332 return -EINVAL;
6333
6334 if (req->Length != 0 || req->DataOffset != 0)
6335 return -EINVAL;
6336
6337 if (req->WriteChannelInfoOffset == 0 ||
6338 le16_to_cpu(req->WriteChannelInfoLength) < sizeof(*desc))
6339 return -EINVAL;
6340
6341 work->need_invalidate_rkey =
6342 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6343 work->remote_key = le32_to_cpu(desc->token);
6344
6345 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6346 if (!data_buf)
6347 return -ENOMEM;
6348
6349 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6350 le32_to_cpu(desc->token),
6351 le64_to_cpu(desc->offset),
6352 le32_to_cpu(desc->length));
6353 if (ret < 0) {
6354 kvfree(data_buf);
6355 return ret;
6356 }
6357
6358 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6359 kvfree(data_buf);
6360 if (ret < 0)
6361 return ret;
6362
6363 return nbytes;
6364 }
6365
6366 /**
6367 * smb2_write() - handler for smb2 write from file
6368 * @work: smb work containing write command buffer
6369 *
6370 * Return: 0 on success, otherwise error
6371 */
6372 int smb2_write(struct ksmbd_work *work)
6373 {
6374 struct smb2_write_req *req;
6375 struct smb2_write_rsp *rsp, *rsp_org;
6376 struct ksmbd_file *fp = NULL;
6377 loff_t offset;
6378 size_t length;
6379 ssize_t nbytes;
6380 char *data_buf;
6381 bool writethrough = false;
6382 int err = 0;
6383
6384 rsp_org = work->response_buf;
6385 WORK_BUFFERS(work, req, rsp);
6386
6387 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6388 ksmbd_debug(SMB, "IPC pipe write request\n");
6389 return smb2_write_pipe(work);
6390 }
6391
6392 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6393 ksmbd_debug(SMB, "User does not have write permission\n");
6394 err = -EACCES;
6395 goto out;
6396 }
6397
6398 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6399 le64_to_cpu(req->PersistentFileId));
6400 if (!fp) {
6401 err = -ENOENT;
6402 goto out;
6403 }
6404
6405 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6406 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6407 err = -EACCES;
6408 goto out;
6409 }
6410
6411 offset = le64_to_cpu(req->Offset);
6412 length = le32_to_cpu(req->Length);
6413
6414 if (length > work->conn->vals->max_write_size) {
6415 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6416 work->conn->vals->max_write_size);
6417 err = -EINVAL;
6418 goto out;
6419 }
6420
6421 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6422 writethrough = true;
6423
6424 if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6425 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6426 if (le16_to_cpu(req->DataOffset) ==
6427 (offsetof(struct smb2_write_req, Buffer) - 4)) {
6428 data_buf = (char *)&req->Buffer[0];
6429 } else {
6430 if ((u64)le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req)) {
6431 pr_err("invalid write data offset %u, smb_len %u\n",
6432 le16_to_cpu(req->DataOffset),
6433 get_rfc1002_len(req));
6434 err = -EINVAL;
6435 goto out;
6436 }
6437
6438 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6439 le16_to_cpu(req->DataOffset));
6440 }
6441
6442 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6443 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6444 writethrough = true;
6445
6446 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6447 fp->filp->f_path.dentry, offset, length);
6448 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6449 writethrough, &nbytes);
6450 if (err < 0)
6451 goto out;
6452 } else {
6453 /* read data from the client using rdma channel, and
6454 * write the data.
6455 */
6456 nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6457 le32_to_cpu(req->RemainingBytes),
6458 writethrough);
6459 if (nbytes < 0) {
6460 err = (int)nbytes;
6461 goto out;
6462 }
6463 }
6464
6465 rsp->StructureSize = cpu_to_le16(17);
6466 rsp->DataOffset = 0;
6467 rsp->Reserved = 0;
6468 rsp->DataLength = cpu_to_le32(nbytes);
6469 rsp->DataRemaining = 0;
6470 rsp->Reserved2 = 0;
6471 inc_rfc1001_len(rsp_org, 16);
6472 ksmbd_fd_put(work, fp);
6473 return 0;
6474
6475 out:
6476 if (err == -EAGAIN)
6477 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6478 else if (err == -ENOSPC || err == -EFBIG)
6479 rsp->hdr.Status = STATUS_DISK_FULL;
6480 else if (err == -ENOENT)
6481 rsp->hdr.Status = STATUS_FILE_CLOSED;
6482 else if (err == -EACCES)
6483 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6484 else if (err == -ESHARE)
6485 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6486 else if (err == -EINVAL)
6487 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6488 else
6489 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6490
6491 smb2_set_err_rsp(work);
6492 ksmbd_fd_put(work, fp);
6493 return err;
6494 }
6495
6496 /**
6497 * smb2_flush() - handler for smb2 flush file - fsync
6498 * @work: smb work containing flush command buffer
6499 *
6500 * Return: 0 on success, otherwise error
6501 */
6502 int smb2_flush(struct ksmbd_work *work)
6503 {
6504 struct smb2_flush_req *req;
6505 struct smb2_flush_rsp *rsp, *rsp_org;
6506 int err;
6507
6508 rsp_org = work->response_buf;
6509 WORK_BUFFERS(work, req, rsp);
6510
6511 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n",
6512 le64_to_cpu(req->VolatileFileId));
6513
6514 err = ksmbd_vfs_fsync(work,
6515 le64_to_cpu(req->VolatileFileId),
6516 le64_to_cpu(req->PersistentFileId));
6517 if (err)
6518 goto out;
6519
6520 rsp->StructureSize = cpu_to_le16(4);
6521 rsp->Reserved = 0;
6522 inc_rfc1001_len(rsp_org, 4);
6523 return 0;
6524
6525 out:
6526 if (err) {
6527 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6528 smb2_set_err_rsp(work);
6529 }
6530
6531 return err;
6532 }
6533
6534 /**
6535 * smb2_cancel() - handler for smb2 cancel command
6536 * @work: smb work containing cancel command buffer
6537 *
6538 * Return: 0 on success, otherwise error
6539 */
6540 int smb2_cancel(struct ksmbd_work *work)
6541 {
6542 struct ksmbd_conn *conn = work->conn;
6543 struct smb2_hdr *hdr = work->request_buf;
6544 struct smb2_hdr *chdr;
6545 struct ksmbd_work *cancel_work = NULL;
6546 int canceled = 0;
6547 struct list_head *command_list;
6548
6549 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6550 hdr->MessageId, hdr->Flags);
6551
6552 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6553 command_list = &conn->async_requests;
6554
6555 spin_lock(&conn->request_lock);
6556 list_for_each_entry(cancel_work, command_list,
6557 async_request_entry) {
6558 chdr = cancel_work->request_buf;
6559
6560 if (cancel_work->async_id !=
6561 le64_to_cpu(hdr->Id.AsyncId))
6562 continue;
6563
6564 ksmbd_debug(SMB,
6565 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6566 le64_to_cpu(hdr->Id.AsyncId),
6567 le16_to_cpu(chdr->Command));
6568 canceled = 1;
6569 break;
6570 }
6571 spin_unlock(&conn->request_lock);
6572 } else {
6573 command_list = &conn->requests;
6574
6575 spin_lock(&conn->request_lock);
6576 list_for_each_entry(cancel_work, command_list, request_entry) {
6577 chdr = cancel_work->request_buf;
6578
6579 if (chdr->MessageId != hdr->MessageId ||
6580 cancel_work == work)
6581 continue;
6582
6583 ksmbd_debug(SMB,
6584 "smb2 with mid %llu cancelled command = 0x%x\n",
6585 le64_to_cpu(hdr->MessageId),
6586 le16_to_cpu(chdr->Command));
6587 canceled = 1;
6588 break;
6589 }
6590 spin_unlock(&conn->request_lock);
6591 }
6592
6593 if (canceled) {
6594 cancel_work->state = KSMBD_WORK_CANCELLED;
6595 if (cancel_work->cancel_fn)
6596 cancel_work->cancel_fn(cancel_work->cancel_argv);
6597 }
6598
6599 /* For SMB2_CANCEL command itself send no response*/
6600 work->send_no_response = 1;
6601 return 0;
6602 }
6603
6604 struct file_lock *smb_flock_init(struct file *f)
6605 {
6606 struct file_lock *fl;
6607
6608 fl = locks_alloc_lock();
6609 if (!fl)
6610 goto out;
6611
6612 locks_init_lock(fl);
6613
6614 fl->fl_owner = f;
6615 fl->fl_pid = current->tgid;
6616 fl->fl_file = f;
6617 fl->fl_flags = FL_POSIX;
6618 fl->fl_ops = NULL;
6619 fl->fl_lmops = NULL;
6620
6621 out:
6622 return fl;
6623 }
6624
6625 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6626 {
6627 int cmd = -EINVAL;
6628
6629 /* Checking for wrong flag combination during lock request*/
6630 switch (flags) {
6631 case SMB2_LOCKFLAG_SHARED:
6632 ksmbd_debug(SMB, "received shared request\n");
6633 cmd = F_SETLKW;
6634 flock->fl_type = F_RDLCK;
6635 flock->fl_flags |= FL_SLEEP;
6636 break;
6637 case SMB2_LOCKFLAG_EXCLUSIVE:
6638 ksmbd_debug(SMB, "received exclusive request\n");
6639 cmd = F_SETLKW;
6640 flock->fl_type = F_WRLCK;
6641 flock->fl_flags |= FL_SLEEP;
6642 break;
6643 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6644 ksmbd_debug(SMB,
6645 "received shared & fail immediately request\n");
6646 cmd = F_SETLK;
6647 flock->fl_type = F_RDLCK;
6648 break;
6649 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6650 ksmbd_debug(SMB,
6651 "received exclusive & fail immediately request\n");
6652 cmd = F_SETLK;
6653 flock->fl_type = F_WRLCK;
6654 break;
6655 case SMB2_LOCKFLAG_UNLOCK:
6656 ksmbd_debug(SMB, "received unlock request\n");
6657 flock->fl_type = F_UNLCK;
6658 cmd = 0;
6659 break;
6660 }
6661
6662 return cmd;
6663 }
6664
6665 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6666 unsigned int cmd, int flags,
6667 struct list_head *lock_list)
6668 {
6669 struct ksmbd_lock *lock;
6670
6671 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6672 if (!lock)
6673 return NULL;
6674
6675 lock->cmd = cmd;
6676 lock->fl = flock;
6677 lock->start = flock->fl_start;
6678 lock->end = flock->fl_end;
6679 lock->flags = flags;
6680 if (lock->start == lock->end)
6681 lock->zero_len = 1;
6682 INIT_LIST_HEAD(&lock->clist);
6683 INIT_LIST_HEAD(&lock->flist);
6684 INIT_LIST_HEAD(&lock->llist);
6685 list_add_tail(&lock->llist, lock_list);
6686
6687 return lock;
6688 }
6689
6690 static void smb2_remove_blocked_lock(void **argv)
6691 {
6692 struct file_lock *flock = (struct file_lock *)argv[0];
6693
6694 ksmbd_vfs_posix_lock_unblock(flock);
6695 wake_up(&flock->fl_wait);
6696 }
6697
6698 static inline bool lock_defer_pending(struct file_lock *fl)
6699 {
6700 /* check pending lock waiters */
6701 return waitqueue_active(&fl->fl_wait);
6702 }
6703
6704 /**
6705 * smb2_lock() - handler for smb2 file lock command
6706 * @work: smb work containing lock command buffer
6707 *
6708 * Return: 0 on success, otherwise error
6709 */
6710 int smb2_lock(struct ksmbd_work *work)
6711 {
6712 struct smb2_lock_req *req = work->request_buf;
6713 struct smb2_lock_rsp *rsp = work->response_buf;
6714 struct smb2_lock_element *lock_ele;
6715 struct ksmbd_file *fp = NULL;
6716 struct file_lock *flock = NULL;
6717 struct file *filp = NULL;
6718 int lock_count;
6719 int flags = 0;
6720 int cmd = 0;
6721 int err = -EIO, i, rc = 0;
6722 u64 lock_start, lock_length;
6723 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6724 struct ksmbd_conn *conn;
6725 int nolock = 0;
6726 LIST_HEAD(lock_list);
6727 LIST_HEAD(rollback_list);
6728 int prior_lock = 0;
6729
6730 ksmbd_debug(SMB, "Received lock request\n");
6731 fp = ksmbd_lookup_fd_slow(work,
6732 le64_to_cpu(req->VolatileFileId),
6733 le64_to_cpu(req->PersistentFileId));
6734 if (!fp) {
6735 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n",
6736 le64_to_cpu(req->VolatileFileId));
6737 err = -ENOENT;
6738 goto out2;
6739 }
6740
6741 filp = fp->filp;
6742 lock_count = le16_to_cpu(req->LockCount);
6743 lock_ele = req->locks;
6744
6745 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6746 if (!lock_count) {
6747 err = -EINVAL;
6748 goto out2;
6749 }
6750
6751 for (i = 0; i < lock_count; i++) {
6752 flags = le32_to_cpu(lock_ele[i].Flags);
6753
6754 flock = smb_flock_init(filp);
6755 if (!flock)
6756 goto out;
6757
6758 cmd = smb2_set_flock_flags(flock, flags);
6759
6760 lock_start = le64_to_cpu(lock_ele[i].Offset);
6761 lock_length = le64_to_cpu(lock_ele[i].Length);
6762 if (lock_start > U64_MAX - lock_length) {
6763 pr_err("Invalid lock range requested\n");
6764 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6765 goto out;
6766 }
6767
6768 if (lock_start > OFFSET_MAX)
6769 flock->fl_start = OFFSET_MAX;
6770 else
6771 flock->fl_start = lock_start;
6772
6773 lock_length = le64_to_cpu(lock_ele[i].Length);
6774 if (lock_length > OFFSET_MAX - flock->fl_start)
6775 lock_length = OFFSET_MAX - flock->fl_start;
6776
6777 flock->fl_end = flock->fl_start + lock_length;
6778
6779 if (flock->fl_end < flock->fl_start) {
6780 ksmbd_debug(SMB,
6781 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6782 flock->fl_end, flock->fl_start);
6783 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6784 goto out;
6785 }
6786
6787 /* Check conflict locks in one request */
6788 list_for_each_entry(cmp_lock, &lock_list, llist) {
6789 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6790 cmp_lock->fl->fl_end >= flock->fl_end) {
6791 if (cmp_lock->fl->fl_type != F_UNLCK &&
6792 flock->fl_type != F_UNLCK) {
6793 pr_err("conflict two locks in one request\n");
6794 err = -EINVAL;
6795 goto out;
6796 }
6797 }
6798 }
6799
6800 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6801 if (!smb_lock) {
6802 err = -EINVAL;
6803 goto out;
6804 }
6805 }
6806
6807 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6808 if (smb_lock->cmd < 0) {
6809 err = -EINVAL;
6810 goto out;
6811 }
6812
6813 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6814 err = -EINVAL;
6815 goto out;
6816 }
6817
6818 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6819 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6820 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6821 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6822 err = -EINVAL;
6823 goto out;
6824 }
6825
6826 prior_lock = smb_lock->flags;
6827
6828 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6829 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6830 goto no_check_cl;
6831
6832 nolock = 1;
6833 /* check locks in connection list */
6834 read_lock(&conn_list_lock);
6835 list_for_each_entry(conn, &conn_list, conns_list) {
6836 spin_lock(&conn->llist_lock);
6837 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6838 if (file_inode(cmp_lock->fl->fl_file) !=
6839 file_inode(smb_lock->fl->fl_file))
6840 continue;
6841
6842 if (smb_lock->fl->fl_type == F_UNLCK) {
6843 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6844 cmp_lock->start == smb_lock->start &&
6845 cmp_lock->end == smb_lock->end &&
6846 !lock_defer_pending(cmp_lock->fl)) {
6847 nolock = 0;
6848 list_del(&cmp_lock->flist);
6849 list_del(&cmp_lock->clist);
6850 spin_unlock(&conn->llist_lock);
6851 read_unlock(&conn_list_lock);
6852
6853 locks_free_lock(cmp_lock->fl);
6854 kfree(cmp_lock);
6855 goto out_check_cl;
6856 }
6857 continue;
6858 }
6859
6860 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6861 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6862 continue;
6863 } else {
6864 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6865 continue;
6866 }
6867
6868 /* check zero byte lock range */
6869 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6870 cmp_lock->start > smb_lock->start &&
6871 cmp_lock->start < smb_lock->end) {
6872 spin_unlock(&conn->llist_lock);
6873 read_unlock(&conn_list_lock);
6874 pr_err("previous lock conflict with zero byte lock range\n");
6875 goto out;
6876 }
6877
6878 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6879 smb_lock->start > cmp_lock->start &&
6880 smb_lock->start < cmp_lock->end) {
6881 spin_unlock(&conn->llist_lock);
6882 read_unlock(&conn_list_lock);
6883 pr_err("current lock conflict with zero byte lock range\n");
6884 goto out;
6885 }
6886
6887 if (((cmp_lock->start <= smb_lock->start &&
6888 cmp_lock->end > smb_lock->start) ||
6889 (cmp_lock->start < smb_lock->end &&
6890 cmp_lock->end >= smb_lock->end)) &&
6891 !cmp_lock->zero_len && !smb_lock->zero_len) {
6892 spin_unlock(&conn->llist_lock);
6893 read_unlock(&conn_list_lock);
6894 pr_err("Not allow lock operation on exclusive lock range\n");
6895 goto out;
6896 }
6897 }
6898 spin_unlock(&conn->llist_lock);
6899 }
6900 read_unlock(&conn_list_lock);
6901 out_check_cl:
6902 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6903 pr_err("Try to unlock nolocked range\n");
6904 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6905 goto out;
6906 }
6907
6908 no_check_cl:
6909 if (smb_lock->zero_len) {
6910 err = 0;
6911 goto skip;
6912 }
6913
6914 flock = smb_lock->fl;
6915 list_del(&smb_lock->llist);
6916 retry:
6917 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6918 skip:
6919 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6920 if (!rc) {
6921 ksmbd_debug(SMB, "File unlocked\n");
6922 } else if (rc == -ENOENT) {
6923 rsp->hdr.Status = STATUS_NOT_LOCKED;
6924 goto out;
6925 }
6926 locks_free_lock(flock);
6927 kfree(smb_lock);
6928 } else {
6929 if (rc == FILE_LOCK_DEFERRED) {
6930 void **argv;
6931
6932 ksmbd_debug(SMB,
6933 "would have to wait for getting lock\n");
6934 spin_lock(&work->conn->llist_lock);
6935 list_add_tail(&smb_lock->clist,
6936 &work->conn->lock_list);
6937 spin_unlock(&work->conn->llist_lock);
6938 list_add(&smb_lock->llist, &rollback_list);
6939
6940 argv = kmalloc(sizeof(void *), GFP_KERNEL);
6941 if (!argv) {
6942 err = -ENOMEM;
6943 goto out;
6944 }
6945 argv[0] = flock;
6946
6947 rc = setup_async_work(work,
6948 smb2_remove_blocked_lock,
6949 argv);
6950 if (rc) {
6951 err = -ENOMEM;
6952 goto out;
6953 }
6954 spin_lock(&fp->f_lock);
6955 list_add(&work->fp_entry, &fp->blocked_works);
6956 spin_unlock(&fp->f_lock);
6957
6958 smb2_send_interim_resp(work, STATUS_PENDING);
6959
6960 ksmbd_vfs_posix_lock_wait(flock);
6961
6962 if (work->state != KSMBD_WORK_ACTIVE) {
6963 list_del(&smb_lock->llist);
6964 spin_lock(&work->conn->llist_lock);
6965 list_del(&smb_lock->clist);
6966 spin_unlock(&work->conn->llist_lock);
6967 locks_free_lock(flock);
6968
6969 if (work->state == KSMBD_WORK_CANCELLED) {
6970 spin_lock(&fp->f_lock);
6971 list_del(&work->fp_entry);
6972 spin_unlock(&fp->f_lock);
6973 rsp->hdr.Status =
6974 STATUS_CANCELLED;
6975 kfree(smb_lock);
6976 smb2_send_interim_resp(work,
6977 STATUS_CANCELLED);
6978 work->send_no_response = 1;
6979 goto out;
6980 }
6981 init_smb2_rsp_hdr(work);
6982 smb2_set_err_rsp(work);
6983 rsp->hdr.Status =
6984 STATUS_RANGE_NOT_LOCKED;
6985 kfree(smb_lock);
6986 goto out2;
6987 }
6988
6989 list_del(&smb_lock->llist);
6990 spin_lock(&work->conn->llist_lock);
6991 list_del(&smb_lock->clist);
6992 spin_unlock(&work->conn->llist_lock);
6993
6994 spin_lock(&fp->f_lock);
6995 list_del(&work->fp_entry);
6996 spin_unlock(&fp->f_lock);
6997 goto retry;
6998 } else if (!rc) {
6999 spin_lock(&work->conn->llist_lock);
7000 list_add_tail(&smb_lock->clist,
7001 &work->conn->lock_list);
7002 list_add_tail(&smb_lock->flist,
7003 &fp->lock_list);
7004 spin_unlock(&work->conn->llist_lock);
7005 list_add(&smb_lock->llist, &rollback_list);
7006 ksmbd_debug(SMB, "successful in taking lock\n");
7007 } else {
7008 goto out;
7009 }
7010 }
7011 }
7012
7013 if (atomic_read(&fp->f_ci->op_count) > 1)
7014 smb_break_all_oplock(work, fp);
7015
7016 rsp->StructureSize = cpu_to_le16(4);
7017 ksmbd_debug(SMB, "successful in taking lock\n");
7018 rsp->hdr.Status = STATUS_SUCCESS;
7019 rsp->Reserved = 0;
7020 inc_rfc1001_len(rsp, 4);
7021 ksmbd_fd_put(work, fp);
7022 return 0;
7023
7024 out:
7025 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7026 locks_free_lock(smb_lock->fl);
7027 list_del(&smb_lock->llist);
7028 kfree(smb_lock);
7029 }
7030
7031 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7032 struct file_lock *rlock = NULL;
7033
7034 rlock = smb_flock_init(filp);
7035 rlock->fl_type = F_UNLCK;
7036 rlock->fl_start = smb_lock->start;
7037 rlock->fl_end = smb_lock->end;
7038
7039 rc = vfs_lock_file(filp, 0, rlock, NULL);
7040 if (rc)
7041 pr_err("rollback unlock fail : %d\n", rc);
7042
7043 list_del(&smb_lock->llist);
7044 spin_lock(&work->conn->llist_lock);
7045 if (!list_empty(&smb_lock->flist))
7046 list_del(&smb_lock->flist);
7047 list_del(&smb_lock->clist);
7048 spin_unlock(&work->conn->llist_lock);
7049
7050 locks_free_lock(smb_lock->fl);
7051 locks_free_lock(rlock);
7052 kfree(smb_lock);
7053 }
7054 out2:
7055 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7056
7057 if (!rsp->hdr.Status) {
7058 if (err == -EINVAL)
7059 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7060 else if (err == -ENOMEM)
7061 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7062 else if (err == -ENOENT)
7063 rsp->hdr.Status = STATUS_FILE_CLOSED;
7064 else
7065 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7066 }
7067
7068 smb2_set_err_rsp(work);
7069 ksmbd_fd_put(work, fp);
7070 return err;
7071 }
7072
7073 static int fsctl_copychunk(struct ksmbd_work *work,
7074 struct copychunk_ioctl_req *ci_req,
7075 unsigned int cnt_code,
7076 unsigned int input_count,
7077 unsigned long long volatile_id,
7078 unsigned long long persistent_id,
7079 struct smb2_ioctl_rsp *rsp)
7080 {
7081 struct copychunk_ioctl_rsp *ci_rsp;
7082 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7083 struct srv_copychunk *chunks;
7084 unsigned int i, chunk_count, chunk_count_written = 0;
7085 unsigned int chunk_size_written = 0;
7086 loff_t total_size_written = 0;
7087 int ret = 0;
7088
7089 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7090
7091 rsp->VolatileFileId = cpu_to_le64(volatile_id);
7092 rsp->PersistentFileId = cpu_to_le64(persistent_id);
7093 ci_rsp->ChunksWritten =
7094 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7095 ci_rsp->ChunkBytesWritten =
7096 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7097 ci_rsp->TotalBytesWritten =
7098 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7099
7100 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7101 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7102 if (chunk_count == 0)
7103 goto out;
7104 total_size_written = 0;
7105
7106 /* verify the SRV_COPYCHUNK_COPY packet */
7107 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7108 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7109 chunk_count * sizeof(struct srv_copychunk)) {
7110 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7111 return -EINVAL;
7112 }
7113
7114 for (i = 0; i < chunk_count; i++) {
7115 if (le32_to_cpu(chunks[i].Length) == 0 ||
7116 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7117 break;
7118 total_size_written += le32_to_cpu(chunks[i].Length);
7119 }
7120
7121 if (i < chunk_count ||
7122 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7123 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7124 return -EINVAL;
7125 }
7126
7127 src_fp = ksmbd_lookup_foreign_fd(work,
7128 le64_to_cpu(ci_req->ResumeKey[0]));
7129 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7130 ret = -EINVAL;
7131 if (!src_fp ||
7132 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7133 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7134 goto out;
7135 }
7136
7137 if (!dst_fp) {
7138 rsp->hdr.Status = STATUS_FILE_CLOSED;
7139 goto out;
7140 }
7141
7142 /*
7143 * FILE_READ_DATA should only be included in
7144 * the FSCTL_COPYCHUNK case
7145 */
7146 if (cnt_code == FSCTL_COPYCHUNK &&
7147 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7148 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7149 goto out;
7150 }
7151
7152 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7153 chunks, chunk_count,
7154 &chunk_count_written,
7155 &chunk_size_written,
7156 &total_size_written);
7157 if (ret < 0) {
7158 if (ret == -EACCES)
7159 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7160 if (ret == -EAGAIN)
7161 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7162 else if (ret == -EBADF)
7163 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7164 else if (ret == -EFBIG || ret == -ENOSPC)
7165 rsp->hdr.Status = STATUS_DISK_FULL;
7166 else if (ret == -EINVAL)
7167 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7168 else if (ret == -EISDIR)
7169 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7170 else if (ret == -E2BIG)
7171 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7172 else
7173 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7174 }
7175
7176 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7177 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7178 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7179 out:
7180 ksmbd_fd_put(work, src_fp);
7181 ksmbd_fd_put(work, dst_fp);
7182 return ret;
7183 }
7184
7185 static __be32 idev_ipv4_address(struct in_device *idev)
7186 {
7187 __be32 addr = 0;
7188
7189 struct in_ifaddr *ifa;
7190
7191 rcu_read_lock();
7192 in_dev_for_each_ifa_rcu(ifa, idev) {
7193 if (ifa->ifa_flags & IFA_F_SECONDARY)
7194 continue;
7195
7196 addr = ifa->ifa_address;
7197 break;
7198 }
7199 rcu_read_unlock();
7200 return addr;
7201 }
7202
7203 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7204 struct smb2_ioctl_rsp *rsp,
7205 unsigned int out_buf_len)
7206 {
7207 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7208 int nbytes = 0;
7209 struct net_device *netdev;
7210 struct sockaddr_storage_rsp *sockaddr_storage;
7211 unsigned int flags;
7212 unsigned long long speed;
7213 struct sockaddr_in6 *csin6 = (struct sockaddr_in6 *)&conn->peer_addr;
7214
7215 rtnl_lock();
7216 for_each_netdev(&init_net, netdev) {
7217 if (out_buf_len <
7218 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7219 rtnl_unlock();
7220 return -ENOSPC;
7221 }
7222
7223 if (netdev->type == ARPHRD_LOOPBACK)
7224 continue;
7225
7226 flags = dev_get_flags(netdev);
7227 if (!(flags & IFF_RUNNING))
7228 continue;
7229
7230 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7231 &rsp->Buffer[nbytes];
7232 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7233
7234 nii_rsp->Capability = 0;
7235 if (ksmbd_rdma_capable_netdev(netdev))
7236 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7237
7238 nii_rsp->Next = cpu_to_le32(152);
7239 nii_rsp->Reserved = 0;
7240
7241 if (netdev->ethtool_ops->get_link_ksettings) {
7242 struct ethtool_link_ksettings cmd;
7243
7244 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7245 speed = cmd.base.speed;
7246 } else {
7247 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7248 "speed is unknown, defaulting to 1Gb/sec");
7249 speed = SPEED_1000;
7250 }
7251
7252 speed *= 1000000;
7253 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7254
7255 sockaddr_storage = (struct sockaddr_storage_rsp *)
7256 nii_rsp->SockAddr_Storage;
7257 memset(sockaddr_storage, 0, 128);
7258
7259 if (conn->peer_addr.ss_family == PF_INET ||
7260 ipv6_addr_v4mapped(&csin6->sin6_addr)) {
7261 struct in_device *idev;
7262
7263 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7264 sockaddr_storage->addr4.Port = 0;
7265
7266 idev = __in_dev_get_rtnl(netdev);
7267 if (!idev)
7268 continue;
7269 sockaddr_storage->addr4.IPv4address =
7270 idev_ipv4_address(idev);
7271 } else {
7272 struct inet6_dev *idev6;
7273 struct inet6_ifaddr *ifa;
7274 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7275
7276 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7277 sockaddr_storage->addr6.Port = 0;
7278 sockaddr_storage->addr6.FlowInfo = 0;
7279
7280 idev6 = __in6_dev_get(netdev);
7281 if (!idev6)
7282 continue;
7283
7284 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7285 if (ifa->flags & (IFA_F_TENTATIVE |
7286 IFA_F_DEPRECATED))
7287 continue;
7288 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7289 break;
7290 }
7291 sockaddr_storage->addr6.ScopeId = 0;
7292 }
7293
7294 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7295 }
7296 rtnl_unlock();
7297
7298 /* zero if this is last one */
7299 if (nii_rsp)
7300 nii_rsp->Next = 0;
7301
7302 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7303 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7304 return nbytes;
7305 }
7306
7307 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7308 struct validate_negotiate_info_req *neg_req,
7309 struct validate_negotiate_info_rsp *neg_rsp,
7310 unsigned int in_buf_len)
7311 {
7312 int ret = 0;
7313 int dialect;
7314
7315 if (in_buf_len < sizeof(struct validate_negotiate_info_req) +
7316 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7317 return -EINVAL;
7318
7319 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7320 neg_req->DialectCount);
7321 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7322 ret = -EINVAL;
7323 goto err_out;
7324 }
7325
7326 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7327 ret = -EINVAL;
7328 goto err_out;
7329 }
7330
7331 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7332 ret = -EINVAL;
7333 goto err_out;
7334 }
7335
7336 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7337 ret = -EINVAL;
7338 goto err_out;
7339 }
7340
7341 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7342 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7343 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7344 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7345 err_out:
7346 return ret;
7347 }
7348
7349 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7350 struct file_allocated_range_buffer *qar_req,
7351 struct file_allocated_range_buffer *qar_rsp,
7352 unsigned int in_count, unsigned int *out_count)
7353 {
7354 struct ksmbd_file *fp;
7355 loff_t start, length;
7356 int ret = 0;
7357
7358 *out_count = 0;
7359 if (in_count == 0)
7360 return -EINVAL;
7361
7362 fp = ksmbd_lookup_fd_fast(work, id);
7363 if (!fp)
7364 return -ENOENT;
7365
7366 start = le64_to_cpu(qar_req->file_offset);
7367 length = le64_to_cpu(qar_req->length);
7368
7369 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7370 qar_rsp, in_count, out_count);
7371 if (ret && ret != -E2BIG)
7372 *out_count = 0;
7373
7374 ksmbd_fd_put(work, fp);
7375 return ret;
7376 }
7377
7378 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7379 unsigned int out_buf_len,
7380 struct smb2_ioctl_req *req,
7381 struct smb2_ioctl_rsp *rsp)
7382 {
7383 struct ksmbd_rpc_command *rpc_resp;
7384 char *data_buf = (char *)&req->Buffer[0];
7385 int nbytes = 0;
7386
7387 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7388 le32_to_cpu(req->InputCount));
7389 if (rpc_resp) {
7390 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7391 /*
7392 * set STATUS_SOME_NOT_MAPPED response
7393 * for unknown domain sid.
7394 */
7395 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7396 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7397 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7398 goto out;
7399 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7400 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7401 goto out;
7402 }
7403
7404 nbytes = rpc_resp->payload_sz;
7405 if (rpc_resp->payload_sz > out_buf_len) {
7406 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7407 nbytes = out_buf_len;
7408 }
7409
7410 if (!rpc_resp->payload_sz) {
7411 rsp->hdr.Status =
7412 STATUS_UNEXPECTED_IO_ERROR;
7413 goto out;
7414 }
7415
7416 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7417 }
7418 out:
7419 kvfree(rpc_resp);
7420 return nbytes;
7421 }
7422
7423 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7424 struct file_sparse *sparse)
7425 {
7426 struct ksmbd_file *fp;
7427 struct user_namespace *user_ns;
7428 int ret = 0;
7429 __le32 old_fattr;
7430
7431 fp = ksmbd_lookup_fd_fast(work, id);
7432 if (!fp)
7433 return -ENOENT;
7434 user_ns = file_mnt_user_ns(fp->filp);
7435
7436 old_fattr = fp->f_ci->m_fattr;
7437 if (sparse->SetSparse)
7438 fp->f_ci->m_fattr |= ATTR_SPARSE_FILE_LE;
7439 else
7440 fp->f_ci->m_fattr &= ~ATTR_SPARSE_FILE_LE;
7441
7442 if (fp->f_ci->m_fattr != old_fattr &&
7443 test_share_config_flag(work->tcon->share_conf,
7444 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7445 struct xattr_dos_attrib da;
7446
7447 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7448 fp->filp->f_path.dentry, &da);
7449 if (ret <= 0)
7450 goto out;
7451
7452 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7453 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7454 fp->filp->f_path.dentry, &da);
7455 if (ret)
7456 fp->f_ci->m_fattr = old_fattr;
7457 }
7458
7459 out:
7460 ksmbd_fd_put(work, fp);
7461 return ret;
7462 }
7463
7464 static int fsctl_request_resume_key(struct ksmbd_work *work,
7465 struct smb2_ioctl_req *req,
7466 struct resume_key_ioctl_rsp *key_rsp)
7467 {
7468 struct ksmbd_file *fp;
7469
7470 fp = ksmbd_lookup_fd_slow(work,
7471 le64_to_cpu(req->VolatileFileId),
7472 le64_to_cpu(req->PersistentFileId));
7473 if (!fp)
7474 return -ENOENT;
7475
7476 memset(key_rsp, 0, sizeof(*key_rsp));
7477 key_rsp->ResumeKey[0] = req->VolatileFileId;
7478 key_rsp->ResumeKey[1] = req->PersistentFileId;
7479 ksmbd_fd_put(work, fp);
7480
7481 return 0;
7482 }
7483
7484 /**
7485 * smb2_ioctl() - handler for smb2 ioctl command
7486 * @work: smb work containing ioctl command buffer
7487 *
7488 * Return: 0 on success, otherwise error
7489 */
7490 int smb2_ioctl(struct ksmbd_work *work)
7491 {
7492 struct smb2_ioctl_req *req;
7493 struct smb2_ioctl_rsp *rsp, *rsp_org;
7494 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7495 u64 id = KSMBD_NO_FID;
7496 struct ksmbd_conn *conn = work->conn;
7497 int ret = 0;
7498
7499 rsp_org = work->response_buf;
7500 if (work->next_smb2_rcv_hdr_off) {
7501 req = ksmbd_req_buf_next(work);
7502 rsp = ksmbd_resp_buf_next(work);
7503 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
7504 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7505 work->compound_fid);
7506 id = work->compound_fid;
7507 }
7508 } else {
7509 req = work->request_buf;
7510 rsp = work->response_buf;
7511 }
7512
7513 if (!has_file_id(id))
7514 id = le64_to_cpu(req->VolatileFileId);
7515
7516 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7517 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7518 goto out;
7519 }
7520
7521 cnt_code = le32_to_cpu(req->CntCode);
7522 ret = smb2_calc_max_out_buf_len(work, 48,
7523 le32_to_cpu(req->MaxOutputResponse));
7524 if (ret < 0) {
7525 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7526 goto out;
7527 }
7528 out_buf_len = (unsigned int)ret;
7529 in_buf_len = le32_to_cpu(req->InputCount);
7530
7531 switch (cnt_code) {
7532 case FSCTL_DFS_GET_REFERRALS:
7533 case FSCTL_DFS_GET_REFERRALS_EX:
7534 /* Not support DFS yet */
7535 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7536 goto out;
7537 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7538 {
7539 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7540
7541 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7542 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7543 &rsp->Buffer[0];
7544
7545 /*
7546 * TODO: This is dummy implementation to pass smbtorture
7547 * Need to check correct response later
7548 */
7549 memset(obj_buf->ObjectId, 0x0, 16);
7550 memset(obj_buf->BirthVolumeId, 0x0, 16);
7551 memset(obj_buf->BirthObjectId, 0x0, 16);
7552 memset(obj_buf->DomainId, 0x0, 16);
7553
7554 break;
7555 }
7556 case FSCTL_PIPE_TRANSCEIVE:
7557 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7558 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7559 break;
7560 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7561 if (conn->dialect < SMB30_PROT_ID) {
7562 ret = -EOPNOTSUPP;
7563 goto out;
7564 }
7565
7566 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7567 return -EINVAL;
7568
7569 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7570 return -EINVAL;
7571
7572 ret = fsctl_validate_negotiate_info(conn,
7573 (struct validate_negotiate_info_req *)&req->Buffer[0],
7574 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7575 in_buf_len);
7576 if (ret < 0)
7577 goto out;
7578
7579 nbytes = sizeof(struct validate_negotiate_info_rsp);
7580 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7581 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7582 break;
7583 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7584 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7585 if (ret < 0)
7586 goto out;
7587 nbytes = ret;
7588 break;
7589 case FSCTL_REQUEST_RESUME_KEY:
7590 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7591 ret = -EINVAL;
7592 goto out;
7593 }
7594
7595 ret = fsctl_request_resume_key(work, req,
7596 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7597 if (ret < 0)
7598 goto out;
7599 rsp->PersistentFileId = req->PersistentFileId;
7600 rsp->VolatileFileId = req->VolatileFileId;
7601 nbytes = sizeof(struct resume_key_ioctl_rsp);
7602 break;
7603 case FSCTL_COPYCHUNK:
7604 case FSCTL_COPYCHUNK_WRITE:
7605 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7606 ksmbd_debug(SMB,
7607 "User does not have write permission\n");
7608 ret = -EACCES;
7609 goto out;
7610 }
7611
7612 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7613 ret = -EINVAL;
7614 goto out;
7615 }
7616
7617 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7618 ret = -EINVAL;
7619 goto out;
7620 }
7621
7622 nbytes = sizeof(struct copychunk_ioctl_rsp);
7623 rsp->VolatileFileId = req->VolatileFileId;
7624 rsp->PersistentFileId = req->PersistentFileId;
7625 fsctl_copychunk(work,
7626 (struct copychunk_ioctl_req *)&req->Buffer[0],
7627 le32_to_cpu(req->CntCode),
7628 le32_to_cpu(req->InputCount),
7629 le64_to_cpu(req->VolatileFileId),
7630 le64_to_cpu(req->PersistentFileId),
7631 rsp);
7632 break;
7633 case FSCTL_SET_SPARSE:
7634 if (in_buf_len < sizeof(struct file_sparse)) {
7635 ret = -EINVAL;
7636 goto out;
7637 }
7638
7639 ret = fsctl_set_sparse(work, id,
7640 (struct file_sparse *)&req->Buffer[0]);
7641 if (ret < 0)
7642 goto out;
7643 break;
7644 case FSCTL_SET_ZERO_DATA:
7645 {
7646 struct file_zero_data_information *zero_data;
7647 struct ksmbd_file *fp;
7648 loff_t off, len;
7649
7650 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7651 ksmbd_debug(SMB,
7652 "User does not have write permission\n");
7653 ret = -EACCES;
7654 goto out;
7655 }
7656
7657 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7658 ret = -EINVAL;
7659 goto out;
7660 }
7661
7662 zero_data =
7663 (struct file_zero_data_information *)&req->Buffer[0];
7664
7665 fp = ksmbd_lookup_fd_fast(work, id);
7666 if (!fp) {
7667 ret = -ENOENT;
7668 goto out;
7669 }
7670
7671 off = le64_to_cpu(zero_data->FileOffset);
7672 len = le64_to_cpu(zero_data->BeyondFinalZero) - off;
7673
7674 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7675 ksmbd_fd_put(work, fp);
7676 if (ret < 0)
7677 goto out;
7678 break;
7679 }
7680 case FSCTL_QUERY_ALLOCATED_RANGES:
7681 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7682 ret = -EINVAL;
7683 goto out;
7684 }
7685
7686 ret = fsctl_query_allocated_ranges(work, id,
7687 (struct file_allocated_range_buffer *)&req->Buffer[0],
7688 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7689 out_buf_len /
7690 sizeof(struct file_allocated_range_buffer), &nbytes);
7691 if (ret == -E2BIG) {
7692 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7693 } else if (ret < 0) {
7694 nbytes = 0;
7695 goto out;
7696 }
7697
7698 nbytes *= sizeof(struct file_allocated_range_buffer);
7699 break;
7700 case FSCTL_GET_REPARSE_POINT:
7701 {
7702 struct reparse_data_buffer *reparse_ptr;
7703 struct ksmbd_file *fp;
7704
7705 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7706 fp = ksmbd_lookup_fd_fast(work, id);
7707 if (!fp) {
7708 pr_err("not found fp!!\n");
7709 ret = -ENOENT;
7710 goto out;
7711 }
7712
7713 reparse_ptr->ReparseTag =
7714 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7715 reparse_ptr->ReparseDataLength = 0;
7716 ksmbd_fd_put(work, fp);
7717 nbytes = sizeof(struct reparse_data_buffer);
7718 break;
7719 }
7720 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7721 {
7722 struct ksmbd_file *fp_in, *fp_out = NULL;
7723 struct duplicate_extents_to_file *dup_ext;
7724 loff_t src_off, dst_off, length, cloned;
7725
7726 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7727 ret = -EINVAL;
7728 goto out;
7729 }
7730
7731 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7732
7733 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7734 dup_ext->PersistentFileHandle);
7735 if (!fp_in) {
7736 pr_err("not found file handle in duplicate extent to file\n");
7737 ret = -ENOENT;
7738 goto out;
7739 }
7740
7741 fp_out = ksmbd_lookup_fd_fast(work, id);
7742 if (!fp_out) {
7743 pr_err("not found fp\n");
7744 ret = -ENOENT;
7745 goto dup_ext_out;
7746 }
7747
7748 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7749 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7750 length = le64_to_cpu(dup_ext->ByteCount);
7751 cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7752 dst_off, length, 0);
7753 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7754 ret = -EOPNOTSUPP;
7755 goto dup_ext_out;
7756 } else if (cloned != length) {
7757 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7758 fp_out->filp, dst_off, length, 0);
7759 if (cloned != length) {
7760 if (cloned < 0)
7761 ret = cloned;
7762 else
7763 ret = -EINVAL;
7764 }
7765 }
7766
7767 dup_ext_out:
7768 ksmbd_fd_put(work, fp_in);
7769 ksmbd_fd_put(work, fp_out);
7770 if (ret < 0)
7771 goto out;
7772 break;
7773 }
7774 default:
7775 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7776 cnt_code);
7777 ret = -EOPNOTSUPP;
7778 goto out;
7779 }
7780
7781 rsp->CntCode = cpu_to_le32(cnt_code);
7782 rsp->InputCount = cpu_to_le32(0);
7783 rsp->InputOffset = cpu_to_le32(112);
7784 rsp->OutputOffset = cpu_to_le32(112);
7785 rsp->OutputCount = cpu_to_le32(nbytes);
7786 rsp->StructureSize = cpu_to_le16(49);
7787 rsp->Reserved = cpu_to_le16(0);
7788 rsp->Flags = cpu_to_le32(0);
7789 rsp->Reserved2 = cpu_to_le32(0);
7790 inc_rfc1001_len(rsp_org, 48 + nbytes);
7791
7792 return 0;
7793
7794 out:
7795 if (ret == -EACCES)
7796 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7797 else if (ret == -ENOENT)
7798 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7799 else if (ret == -EOPNOTSUPP)
7800 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7801 else if (ret == -ENOSPC)
7802 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7803 else if (ret < 0 || rsp->hdr.Status == 0)
7804 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7805 smb2_set_err_rsp(work);
7806 return 0;
7807 }
7808
7809 /**
7810 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7811 * @work: smb work containing oplock break command buffer
7812 *
7813 * Return: 0
7814 */
7815 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7816 {
7817 struct smb2_oplock_break *req = work->request_buf;
7818 struct smb2_oplock_break *rsp = work->response_buf;
7819 struct ksmbd_file *fp;
7820 struct oplock_info *opinfo = NULL;
7821 __le32 err = 0;
7822 int ret = 0;
7823 u64 volatile_id, persistent_id;
7824 char req_oplevel = 0, rsp_oplevel = 0;
7825 unsigned int oplock_change_type;
7826
7827 volatile_id = le64_to_cpu(req->VolatileFid);
7828 persistent_id = le64_to_cpu(req->PersistentFid);
7829 req_oplevel = req->OplockLevel;
7830 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7831 volatile_id, persistent_id, req_oplevel);
7832
7833 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7834 if (!fp) {
7835 rsp->hdr.Status = STATUS_FILE_CLOSED;
7836 smb2_set_err_rsp(work);
7837 return;
7838 }
7839
7840 opinfo = opinfo_get(fp);
7841 if (!opinfo) {
7842 pr_err("unexpected null oplock_info\n");
7843 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7844 smb2_set_err_rsp(work);
7845 ksmbd_fd_put(work, fp);
7846 return;
7847 }
7848
7849 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7850 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7851 goto err_out;
7852 }
7853
7854 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7855 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7856 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7857 goto err_out;
7858 }
7859
7860 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7861 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7862 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7863 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7864 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7865 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7866 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7867 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7868 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7869 oplock_change_type = OPLOCK_READ_TO_NONE;
7870 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7871 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7872 err = STATUS_INVALID_DEVICE_STATE;
7873 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7874 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7875 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7876 oplock_change_type = OPLOCK_WRITE_TO_READ;
7877 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7878 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7879 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7880 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7881 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7882 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7883 oplock_change_type = OPLOCK_READ_TO_NONE;
7884 } else {
7885 oplock_change_type = 0;
7886 }
7887 } else {
7888 oplock_change_type = 0;
7889 }
7890
7891 switch (oplock_change_type) {
7892 case OPLOCK_WRITE_TO_READ:
7893 ret = opinfo_write_to_read(opinfo);
7894 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7895 break;
7896 case OPLOCK_WRITE_TO_NONE:
7897 ret = opinfo_write_to_none(opinfo);
7898 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7899 break;
7900 case OPLOCK_READ_TO_NONE:
7901 ret = opinfo_read_to_none(opinfo);
7902 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7903 break;
7904 default:
7905 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7906 opinfo->level, rsp_oplevel);
7907 }
7908
7909 if (ret < 0) {
7910 rsp->hdr.Status = err;
7911 goto err_out;
7912 }
7913
7914 opinfo_put(opinfo);
7915 ksmbd_fd_put(work, fp);
7916 opinfo->op_state = OPLOCK_STATE_NONE;
7917 wake_up_interruptible_all(&opinfo->oplock_q);
7918
7919 rsp->StructureSize = cpu_to_le16(24);
7920 rsp->OplockLevel = rsp_oplevel;
7921 rsp->Reserved = 0;
7922 rsp->Reserved2 = 0;
7923 rsp->VolatileFid = cpu_to_le64(volatile_id);
7924 rsp->PersistentFid = cpu_to_le64(persistent_id);
7925 inc_rfc1001_len(rsp, 24);
7926 return;
7927
7928 err_out:
7929 opinfo->op_state = OPLOCK_STATE_NONE;
7930 wake_up_interruptible_all(&opinfo->oplock_q);
7931
7932 opinfo_put(opinfo);
7933 ksmbd_fd_put(work, fp);
7934 smb2_set_err_rsp(work);
7935 }
7936
7937 static int check_lease_state(struct lease *lease, __le32 req_state)
7938 {
7939 if ((lease->new_state ==
7940 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
7941 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
7942 lease->new_state = req_state;
7943 return 0;
7944 }
7945
7946 if (lease->new_state == req_state)
7947 return 0;
7948
7949 return 1;
7950 }
7951
7952 /**
7953 * smb21_lease_break_ack() - handler for smb2.1 lease break command
7954 * @work: smb work containing lease break command buffer
7955 *
7956 * Return: 0
7957 */
7958 static void smb21_lease_break_ack(struct ksmbd_work *work)
7959 {
7960 struct ksmbd_conn *conn = work->conn;
7961 struct smb2_lease_ack *req = work->request_buf;
7962 struct smb2_lease_ack *rsp = work->response_buf;
7963 struct oplock_info *opinfo;
7964 __le32 err = 0;
7965 int ret = 0;
7966 unsigned int lease_change_type;
7967 __le32 lease_state;
7968 struct lease *lease;
7969
7970 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
7971 le32_to_cpu(req->LeaseState));
7972 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
7973 if (!opinfo) {
7974 ksmbd_debug(OPLOCK, "file not opened\n");
7975 smb2_set_err_rsp(work);
7976 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7977 return;
7978 }
7979 lease = opinfo->o_lease;
7980
7981 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7982 pr_err("unexpected lease break state 0x%x\n",
7983 opinfo->op_state);
7984 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7985 goto err_out;
7986 }
7987
7988 if (check_lease_state(lease, req->LeaseState)) {
7989 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
7990 ksmbd_debug(OPLOCK,
7991 "req lease state: 0x%x, expected state: 0x%x\n",
7992 req->LeaseState, lease->new_state);
7993 goto err_out;
7994 }
7995
7996 if (!atomic_read(&opinfo->breaking_cnt)) {
7997 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7998 goto err_out;
7999 }
8000
8001 /* check for bad lease state */
8002 if (req->LeaseState &
8003 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8004 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8005 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8006 lease_change_type = OPLOCK_WRITE_TO_NONE;
8007 else
8008 lease_change_type = OPLOCK_READ_TO_NONE;
8009 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8010 le32_to_cpu(lease->state),
8011 le32_to_cpu(req->LeaseState));
8012 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8013 req->LeaseState != SMB2_LEASE_NONE_LE) {
8014 err = STATUS_INVALID_OPLOCK_PROTOCOL;
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 {
8020 /* valid lease state changes */
8021 err = STATUS_INVALID_DEVICE_STATE;
8022 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8023 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8024 lease_change_type = OPLOCK_WRITE_TO_NONE;
8025 else
8026 lease_change_type = OPLOCK_READ_TO_NONE;
8027 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8028 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8029 lease_change_type = OPLOCK_WRITE_TO_READ;
8030 else
8031 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8032 } else {
8033 lease_change_type = 0;
8034 }
8035 }
8036
8037 switch (lease_change_type) {
8038 case OPLOCK_WRITE_TO_READ:
8039 ret = opinfo_write_to_read(opinfo);
8040 break;
8041 case OPLOCK_READ_HANDLE_TO_READ:
8042 ret = opinfo_read_handle_to_read(opinfo);
8043 break;
8044 case OPLOCK_WRITE_TO_NONE:
8045 ret = opinfo_write_to_none(opinfo);
8046 break;
8047 case OPLOCK_READ_TO_NONE:
8048 ret = opinfo_read_to_none(opinfo);
8049 break;
8050 default:
8051 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8052 le32_to_cpu(lease->state),
8053 le32_to_cpu(req->LeaseState));
8054 }
8055
8056 lease_state = lease->state;
8057 opinfo->op_state = OPLOCK_STATE_NONE;
8058 wake_up_interruptible_all(&opinfo->oplock_q);
8059 atomic_dec(&opinfo->breaking_cnt);
8060 wake_up_interruptible_all(&opinfo->oplock_brk);
8061 opinfo_put(opinfo);
8062
8063 if (ret < 0) {
8064 rsp->hdr.Status = err;
8065 goto err_out;
8066 }
8067
8068 rsp->StructureSize = cpu_to_le16(36);
8069 rsp->Reserved = 0;
8070 rsp->Flags = 0;
8071 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8072 rsp->LeaseState = lease_state;
8073 rsp->LeaseDuration = 0;
8074 inc_rfc1001_len(rsp, 36);
8075 return;
8076
8077 err_out:
8078 opinfo->op_state = OPLOCK_STATE_NONE;
8079 wake_up_interruptible_all(&opinfo->oplock_q);
8080 atomic_dec(&opinfo->breaking_cnt);
8081 wake_up_interruptible_all(&opinfo->oplock_brk);
8082
8083 opinfo_put(opinfo);
8084 smb2_set_err_rsp(work);
8085 }
8086
8087 /**
8088 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8089 * @work: smb work containing oplock/lease break command buffer
8090 *
8091 * Return: 0
8092 */
8093 int smb2_oplock_break(struct ksmbd_work *work)
8094 {
8095 struct smb2_oplock_break *req = work->request_buf;
8096 struct smb2_oplock_break *rsp = work->response_buf;
8097
8098 switch (le16_to_cpu(req->StructureSize)) {
8099 case OP_BREAK_STRUCT_SIZE_20:
8100 smb20_oplock_break_ack(work);
8101 break;
8102 case OP_BREAK_STRUCT_SIZE_21:
8103 smb21_lease_break_ack(work);
8104 break;
8105 default:
8106 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8107 le16_to_cpu(req->StructureSize));
8108 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8109 smb2_set_err_rsp(work);
8110 }
8111
8112 return 0;
8113 }
8114
8115 /**
8116 * smb2_notify() - handler for smb2 notify request
8117 * @work: smb work containing notify command buffer
8118 *
8119 * Return: 0
8120 */
8121 int smb2_notify(struct ksmbd_work *work)
8122 {
8123 struct smb2_notify_req *req;
8124 struct smb2_notify_rsp *rsp;
8125
8126 WORK_BUFFERS(work, req, rsp);
8127
8128 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8129 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8130 smb2_set_err_rsp(work);
8131 return 0;
8132 }
8133
8134 smb2_set_err_rsp(work);
8135 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8136 return 0;
8137 }
8138
8139 /**
8140 * smb2_is_sign_req() - handler for checking packet signing status
8141 * @work: smb work containing notify command buffer
8142 * @command: SMB2 command id
8143 *
8144 * Return: true if packed is signed, false otherwise
8145 */
8146 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8147 {
8148 struct smb2_hdr *rcv_hdr2 = work->request_buf;
8149
8150 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8151 command != SMB2_NEGOTIATE_HE &&
8152 command != SMB2_SESSION_SETUP_HE &&
8153 command != SMB2_OPLOCK_BREAK_HE)
8154 return true;
8155
8156 return false;
8157 }
8158
8159 /**
8160 * smb2_check_sign_req() - handler for req packet sign processing
8161 * @work: smb work containing notify command buffer
8162 *
8163 * Return: 1 on success, 0 otherwise
8164 */
8165 int smb2_check_sign_req(struct ksmbd_work *work)
8166 {
8167 struct smb2_hdr *hdr, *hdr_org;
8168 char signature_req[SMB2_SIGNATURE_SIZE];
8169 char signature[SMB2_HMACSHA256_SIZE];
8170 struct kvec iov[1];
8171 size_t len;
8172
8173 hdr_org = hdr = work->request_buf;
8174 if (work->next_smb2_rcv_hdr_off)
8175 hdr = ksmbd_req_buf_next(work);
8176
8177 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8178 len = be32_to_cpu(hdr_org->smb2_buf_length);
8179 else if (hdr->NextCommand)
8180 len = le32_to_cpu(hdr->NextCommand);
8181 else
8182 len = be32_to_cpu(hdr_org->smb2_buf_length) -
8183 work->next_smb2_rcv_hdr_off;
8184
8185 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8186 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8187
8188 iov[0].iov_base = (char *)&hdr->ProtocolId;
8189 iov[0].iov_len = len;
8190
8191 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8192 signature))
8193 return 0;
8194
8195 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8196 pr_err("bad smb2 signature\n");
8197 return 0;
8198 }
8199
8200 return 1;
8201 }
8202
8203 /**
8204 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8205 * @work: smb work containing notify command buffer
8206 *
8207 */
8208 void smb2_set_sign_rsp(struct ksmbd_work *work)
8209 {
8210 struct smb2_hdr *hdr, *hdr_org;
8211 struct smb2_hdr *req_hdr;
8212 char signature[SMB2_HMACSHA256_SIZE];
8213 struct kvec iov[2];
8214 size_t len;
8215 int n_vec = 1;
8216
8217 hdr_org = hdr = work->response_buf;
8218 if (work->next_smb2_rsp_hdr_off)
8219 hdr = ksmbd_resp_buf_next(work);
8220
8221 req_hdr = ksmbd_req_buf_next(work);
8222
8223 if (!work->next_smb2_rsp_hdr_off) {
8224 len = get_rfc1002_len(hdr_org);
8225 if (req_hdr->NextCommand)
8226 len = ALIGN(len, 8);
8227 } else {
8228 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
8229 len = ALIGN(len, 8);
8230 }
8231
8232 if (req_hdr->NextCommand)
8233 hdr->NextCommand = cpu_to_le32(len);
8234
8235 hdr->Flags |= SMB2_FLAGS_SIGNED;
8236 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8237
8238 iov[0].iov_base = (char *)&hdr->ProtocolId;
8239 iov[0].iov_len = len;
8240
8241 if (work->aux_payload_sz) {
8242 iov[0].iov_len -= work->aux_payload_sz;
8243
8244 iov[1].iov_base = work->aux_payload_buf;
8245 iov[1].iov_len = work->aux_payload_sz;
8246 n_vec++;
8247 }
8248
8249 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8250 signature))
8251 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8252 }
8253
8254 /**
8255 * smb3_check_sign_req() - handler for req packet sign processing
8256 * @work: smb work containing notify command buffer
8257 *
8258 * Return: 1 on success, 0 otherwise
8259 */
8260 int smb3_check_sign_req(struct ksmbd_work *work)
8261 {
8262 struct ksmbd_conn *conn = work->conn;
8263 char *signing_key;
8264 struct smb2_hdr *hdr, *hdr_org;
8265 struct channel *chann;
8266 char signature_req[SMB2_SIGNATURE_SIZE];
8267 char signature[SMB2_CMACAES_SIZE];
8268 struct kvec iov[1];
8269 size_t len;
8270
8271 hdr_org = hdr = work->request_buf;
8272 if (work->next_smb2_rcv_hdr_off)
8273 hdr = ksmbd_req_buf_next(work);
8274
8275 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8276 len = be32_to_cpu(hdr_org->smb2_buf_length);
8277 else if (hdr->NextCommand)
8278 len = le32_to_cpu(hdr->NextCommand);
8279 else
8280 len = be32_to_cpu(hdr_org->smb2_buf_length) -
8281 work->next_smb2_rcv_hdr_off;
8282
8283 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8284 signing_key = work->sess->smb3signingkey;
8285 } else {
8286 chann = lookup_chann_list(work->sess, conn);
8287 if (!chann)
8288 return 0;
8289 signing_key = chann->smb3signingkey;
8290 }
8291
8292 if (!signing_key) {
8293 pr_err("SMB3 signing key is not generated\n");
8294 return 0;
8295 }
8296
8297 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8298 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8299 iov[0].iov_base = (char *)&hdr->ProtocolId;
8300 iov[0].iov_len = len;
8301
8302 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8303 return 0;
8304
8305 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8306 pr_err("bad smb2 signature\n");
8307 return 0;
8308 }
8309
8310 return 1;
8311 }
8312
8313 /**
8314 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8315 * @work: smb work containing notify command buffer
8316 *
8317 */
8318 void smb3_set_sign_rsp(struct ksmbd_work *work)
8319 {
8320 struct ksmbd_conn *conn = work->conn;
8321 struct smb2_hdr *req_hdr;
8322 struct smb2_hdr *hdr, *hdr_org;
8323 struct channel *chann;
8324 char signature[SMB2_CMACAES_SIZE];
8325 struct kvec iov[2];
8326 int n_vec = 1;
8327 size_t len;
8328 char *signing_key;
8329
8330 hdr_org = hdr = work->response_buf;
8331 if (work->next_smb2_rsp_hdr_off)
8332 hdr = ksmbd_resp_buf_next(work);
8333
8334 req_hdr = ksmbd_req_buf_next(work);
8335
8336 if (!work->next_smb2_rsp_hdr_off) {
8337 len = get_rfc1002_len(hdr_org);
8338 if (req_hdr->NextCommand)
8339 len = ALIGN(len, 8);
8340 } else {
8341 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
8342 len = ALIGN(len, 8);
8343 }
8344
8345 if (conn->binding == false &&
8346 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8347 signing_key = work->sess->smb3signingkey;
8348 } else {
8349 chann = lookup_chann_list(work->sess, work->conn);
8350 if (!chann)
8351 return;
8352 signing_key = chann->smb3signingkey;
8353 }
8354
8355 if (!signing_key)
8356 return;
8357
8358 if (req_hdr->NextCommand)
8359 hdr->NextCommand = cpu_to_le32(len);
8360
8361 hdr->Flags |= SMB2_FLAGS_SIGNED;
8362 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8363 iov[0].iov_base = (char *)&hdr->ProtocolId;
8364 iov[0].iov_len = len;
8365 if (work->aux_payload_sz) {
8366 iov[0].iov_len -= work->aux_payload_sz;
8367 iov[1].iov_base = work->aux_payload_buf;
8368 iov[1].iov_len = work->aux_payload_sz;
8369 n_vec++;
8370 }
8371
8372 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8373 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8374 }
8375
8376 /**
8377 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8378 * @work: smb work containing response buffer
8379 *
8380 */
8381 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8382 {
8383 struct ksmbd_conn *conn = work->conn;
8384 struct ksmbd_session *sess = work->sess;
8385 struct smb2_hdr *req, *rsp;
8386
8387 if (conn->dialect != SMB311_PROT_ID)
8388 return;
8389
8390 WORK_BUFFERS(work, req, rsp);
8391
8392 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8393 conn->preauth_info)
8394 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8395 conn->preauth_info->Preauth_HashValue);
8396
8397 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8398 __u8 *hash_value;
8399
8400 if (conn->binding) {
8401 struct preauth_session *preauth_sess;
8402
8403 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8404 if (!preauth_sess)
8405 return;
8406 hash_value = preauth_sess->Preauth_HashValue;
8407 } else {
8408 hash_value = sess->Preauth_HashValue;
8409 if (!hash_value)
8410 return;
8411 }
8412 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8413 hash_value);
8414 }
8415 }
8416
8417 static void fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, char *old_buf,
8418 __le16 cipher_type)
8419 {
8420 struct smb2_hdr *hdr = (struct smb2_hdr *)old_buf;
8421 unsigned int orig_len = get_rfc1002_len(old_buf);
8422
8423 memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
8424 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8425 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8426 tr_hdr->Flags = cpu_to_le16(0x01);
8427 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8428 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8429 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8430 else
8431 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8432 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8433 inc_rfc1001_len(tr_hdr, sizeof(struct smb2_transform_hdr) - 4);
8434 inc_rfc1001_len(tr_hdr, orig_len);
8435 }
8436
8437 int smb3_encrypt_resp(struct ksmbd_work *work)
8438 {
8439 char *buf = work->response_buf;
8440 struct smb2_transform_hdr *tr_hdr;
8441 struct kvec iov[3];
8442 int rc = -ENOMEM;
8443 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8444
8445 if (ARRAY_SIZE(iov) < rq_nvec)
8446 return -ENOMEM;
8447
8448 tr_hdr = kzalloc(sizeof(struct smb2_transform_hdr), GFP_KERNEL);
8449 if (!tr_hdr)
8450 return rc;
8451
8452 /* fill transform header */
8453 fill_transform_hdr(tr_hdr, buf, work->conn->cipher_type);
8454
8455 iov[0].iov_base = tr_hdr;
8456 iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8457 buf_size += iov[0].iov_len - 4;
8458
8459 iov[1].iov_base = buf + 4;
8460 iov[1].iov_len = get_rfc1002_len(buf);
8461 if (work->aux_payload_sz) {
8462 iov[1].iov_len = work->resp_hdr_sz - 4;
8463
8464 iov[2].iov_base = work->aux_payload_buf;
8465 iov[2].iov_len = work->aux_payload_sz;
8466 buf_size += iov[2].iov_len;
8467 }
8468 buf_size += iov[1].iov_len;
8469 work->resp_hdr_sz = iov[1].iov_len;
8470
8471 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8472 if (rc)
8473 return rc;
8474
8475 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8476 tr_hdr->smb2_buf_length = cpu_to_be32(buf_size);
8477 work->tr_buf = tr_hdr;
8478
8479 return rc;
8480 }
8481
8482 bool smb3_is_transform_hdr(void *buf)
8483 {
8484 struct smb2_transform_hdr *trhdr = buf;
8485
8486 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8487 }
8488
8489 int smb3_decrypt_req(struct ksmbd_work *work)
8490 {
8491 struct ksmbd_conn *conn = work->conn;
8492 struct ksmbd_session *sess;
8493 char *buf = work->request_buf;
8494 struct smb2_hdr *hdr;
8495 unsigned int pdu_length = get_rfc1002_len(buf);
8496 struct kvec iov[2];
8497 int buf_data_size = pdu_length + 4 -
8498 sizeof(struct smb2_transform_hdr);
8499 struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
8500 int rc = 0;
8501
8502 if (buf_data_size < sizeof(struct smb2_hdr)) {
8503 pr_err("Transform message is too small (%u)\n",
8504 pdu_length);
8505 return -ECONNABORTED;
8506 }
8507
8508 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8509 pr_err("Transform message is broken\n");
8510 return -ECONNABORTED;
8511 }
8512
8513 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8514 if (!sess) {
8515 pr_err("invalid session id(%llx) in transform header\n",
8516 le64_to_cpu(tr_hdr->SessionId));
8517 return -ECONNABORTED;
8518 }
8519
8520 iov[0].iov_base = buf;
8521 iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8522 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
8523 iov[1].iov_len = buf_data_size;
8524 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8525 if (rc)
8526 return rc;
8527
8528 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8529 hdr = (struct smb2_hdr *)buf;
8530 hdr->smb2_buf_length = cpu_to_be32(buf_data_size);
8531
8532 return rc;
8533 }
8534
8535 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8536 {
8537 struct ksmbd_conn *conn = work->conn;
8538 struct smb2_hdr *rsp = work->response_buf;
8539
8540 if (conn->dialect < SMB30_PROT_ID)
8541 return false;
8542
8543 if (work->next_smb2_rcv_hdr_off)
8544 rsp = ksmbd_resp_buf_next(work);
8545
8546 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8547 rsp->Status == STATUS_SUCCESS)
8548 return true;
8549 return false;
8550 }