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