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