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 <crypto/utils.h> 8 #include <linux/inetdevice.h> 9 #include <net/addrconf.h> 10 #include <linux/syscalls.h> 11 #include <linux/namei.h> 12 #include <linux/fs_struct.h> 13 #include <linux/statfs.h> 14 #include <linux/ethtool.h> 15 #include <linux/falloc.h> 16 #include <linux/mount.h> 17 #include <linux/filelock.h> 18 #include <linux/fileattr.h> 19 #include <linux/timekeeping.h> 20 #include <linux/unaligned.h> 21 22 #include "glob.h" 23 #include "../common/smbfsctl.h" 24 #include "oplock.h" 25 #include "smbacl.h" 26 27 #include "auth.h" 28 #include "asn1.h" 29 #include "connection.h" 30 #include "transport_ipc.h" 31 #include "transport_rdma.h" 32 #include "vfs.h" 33 #include "vfs_cache.h" 34 #include "misc.h" 35 36 #include "server.h" 37 #include "smb_common.h" 38 #include "../common/smb2status.h" 39 #include "ksmbd_work.h" 40 #include "mgmt/user_config.h" 41 #include "mgmt/share_config.h" 42 #include "mgmt/tree_connect.h" 43 #include "mgmt/user_session.h" 44 #include "mgmt/ksmbd_ida.h" 45 #include "ndr.h" 46 #include "stats.h" 47 #include "transport_tcp.h" 48 #include "compress.h" 49 50 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp) 51 { 52 if (work->next_smb2_rcv_hdr_off) { 53 *req = ksmbd_req_buf_next(work); 54 *rsp = ksmbd_resp_buf_next(work); 55 } else { 56 *req = smb_get_msg(work->request_buf); 57 *rsp = smb_get_msg(work->response_buf); 58 } 59 } 60 61 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv); 62 static void smb2_notify_cancel_fn(void **argv); 63 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work); 64 65 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs)) 66 67 #define SMB2_CREATE_FILE_ATTRIBUTE_MASK \ 68 (FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \ 69 FILE_ATTRIBUTE_NO_SCRUB_DATA)) 70 71 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */ 72 #define KSMBD_WRITE_TIME_RESOLUTION (15ULL * 10000) 73 74 /* MAXFILESIZE in [MS-FSA] 2.1.5.3 Server Requests a Write. */ 75 #define SMB2_MAX_FILE_SIZE 0xfffffff0000ULL 76 77 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn) 78 { 79 struct channel *chann; 80 81 down_read(&sess->chann_lock); 82 chann = xa_load(&sess->ksmbd_chann_list, (long)conn); 83 up_read(&sess->chann_lock); 84 85 return chann; 86 } 87 88 #define KSMBD_MAX_CHANNELS 32 89 90 static int register_session_channel(struct ksmbd_session *sess, 91 struct ksmbd_conn *conn, 92 const char *sess_key) 93 { 94 struct channel *chann, *old; 95 unsigned long index; 96 unsigned int count = 0; 97 int rc = 0; 98 99 down_write(&sess->chann_lock); 100 if (sess->tearing_down) { 101 rc = -ESHUTDOWN; 102 goto out; 103 } 104 105 if (xa_load(&sess->ksmbd_chann_list, (long)conn)) 106 goto out; 107 108 xa_for_each(&sess->ksmbd_chann_list, index, chann) 109 count++; 110 if (count >= KSMBD_MAX_CHANNELS) { 111 rc = -ENOSPC; 112 goto out; 113 } 114 115 chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP); 116 if (!chann) { 117 rc = -ENOMEM; 118 goto out; 119 } 120 121 chann->conn = conn; 122 memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key)); 123 old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann, 124 KSMBD_DEFAULT_GFP); 125 if (xa_is_err(old)) { 126 kfree_sensitive(chann); 127 rc = xa_err(old); 128 } 129 out: 130 up_write(&sess->chann_lock); 131 return rc; 132 } 133 134 /** 135 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id. 136 * @work: smb work 137 * 138 * Return: 0 if there is a tree connection matched or these are 139 * skipable commands, otherwise error 140 */ 141 int smb2_get_ksmbd_tcon(struct ksmbd_work *work) 142 { 143 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work); 144 unsigned int cmd = le16_to_cpu(req_hdr->Command); 145 unsigned int tree_id; 146 147 if (cmd == SMB2_TREE_CONNECT_HE || 148 cmd == SMB2_CANCEL_HE || 149 cmd == SMB2_LOGOFF_HE) { 150 ksmbd_debug(SMB, "skip to check tree connect request\n"); 151 return 0; 152 } 153 154 if (xa_empty(&work->sess->tree_conns)) { 155 ksmbd_debug(SMB, "NO tree connected\n"); 156 return -ENOENT; 157 } 158 159 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId); 160 161 /* 162 * If request is not the first in Compound request, 163 * Just validate tree id in header with work->tcon->id. 164 */ 165 if (work->next_smb2_rcv_hdr_off) { 166 if (!work->tcon) { 167 pr_err("The first operation in the compound does not have tcon\n"); 168 return -EINVAL; 169 } 170 if (work->tcon->t_state != TREE_CONNECTED) 171 return -ENOENT; 172 if (tree_id != UINT_MAX && work->tcon->id != tree_id) { 173 pr_err("tree id(%u) is different with id(%u) in first operation\n", 174 tree_id, work->tcon->id); 175 return -EINVAL; 176 } 177 return 1; 178 } 179 180 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id); 181 if (!work->tcon) { 182 pr_err("Invalid tid %d\n", tree_id); 183 return -ENOENT; 184 } 185 186 return 1; 187 } 188 189 /** 190 * smb2_set_err_rsp() - set error response code on smb response 191 * @work: smb work containing response buffer 192 */ 193 void smb2_set_err_rsp(struct ksmbd_work *work) 194 { 195 struct smb2_err_rsp *err_rsp; 196 197 if (work->next_smb2_rcv_hdr_off) 198 err_rsp = ksmbd_resp_buf_next(work); 199 else 200 err_rsp = smb_get_msg(work->response_buf); 201 202 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) { 203 int err; 204 205 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE; 206 err_rsp->ErrorContextCount = 0; 207 err_rsp->Reserved = 0; 208 err_rsp->ByteCount = 0; 209 err_rsp->ErrorData[0] = 0; 210 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp, 211 __SMB2_HEADER_STRUCTURE_SIZE + 212 SMB2_ERROR_STRUCTURE_SIZE2); 213 if (err) 214 work->send_no_response = 1; 215 } 216 } 217 218 /** 219 * is_smb2_neg_cmd() - is it smb2 negotiation command 220 * @work: smb work containing smb header 221 * 222 * Return: true if smb2 negotiation command, otherwise false 223 */ 224 bool is_smb2_neg_cmd(struct ksmbd_work *work) 225 { 226 struct smb2_hdr *hdr = smb_get_msg(work->request_buf); 227 228 /* is it SMB2 header ? */ 229 if (hdr->ProtocolId != SMB2_PROTO_NUMBER) 230 return false; 231 232 /* make sure it is request not response message */ 233 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR) 234 return false; 235 236 if (hdr->Command != SMB2_NEGOTIATE) 237 return false; 238 239 return true; 240 } 241 242 /** 243 * is_smb2_rsp() - is it smb2 response 244 * @work: smb work containing smb response buffer 245 * 246 * Return: true if smb2 response, otherwise false 247 */ 248 bool is_smb2_rsp(struct ksmbd_work *work) 249 { 250 struct smb2_hdr *hdr = smb_get_msg(work->response_buf); 251 252 /* is it SMB2 header ? */ 253 if (hdr->ProtocolId != SMB2_PROTO_NUMBER) 254 return false; 255 256 /* make sure it is response not request message */ 257 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)) 258 return false; 259 260 return true; 261 } 262 263 /** 264 * get_smb2_cmd_val() - get smb command code from smb header 265 * @work: smb work containing smb request buffer 266 * 267 * Return: smb2 request command value 268 */ 269 u16 get_smb2_cmd_val(struct ksmbd_work *work) 270 { 271 struct smb2_hdr *rcv_hdr; 272 273 if (work->next_smb2_rcv_hdr_off) 274 rcv_hdr = ksmbd_req_buf_next(work); 275 else 276 rcv_hdr = smb_get_msg(work->request_buf); 277 return le16_to_cpu(rcv_hdr->Command); 278 } 279 280 /** 281 * set_smb2_rsp_status() - set error response code on smb2 header 282 * @work: smb work containing response buffer 283 * @err: error response code 284 */ 285 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err) 286 { 287 struct smb2_hdr *rsp_hdr; 288 289 if (work->next_smb2_rcv_hdr_off) { 290 rsp_hdr = ksmbd_resp_buf_next(work); 291 rsp_hdr->Status = err; 292 smb2_set_err_rsp(work); 293 return; 294 } 295 296 rsp_hdr = smb_get_msg(work->response_buf); 297 rsp_hdr->Status = err; 298 299 work->iov_idx = 0; 300 work->iov_cnt = 0; 301 work->next_smb2_rcv_hdr_off = 0; 302 smb2_set_err_rsp(work); 303 } 304 305 /** 306 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command 307 * @work: smb work containing smb request buffer 308 * 309 * smb2 negotiate response is sent in reply of smb1 negotiate command for 310 * dialect auto-negotiation. 311 */ 312 int init_smb2_neg_rsp(struct ksmbd_work *work) 313 { 314 struct smb2_hdr *rsp_hdr; 315 struct smb2_negotiate_rsp *rsp; 316 struct ksmbd_conn *conn = work->conn; 317 int err; 318 319 rsp_hdr = smb_get_msg(work->response_buf); 320 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2); 321 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER; 322 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE; 323 rsp_hdr->CreditRequest = cpu_to_le16(2); 324 rsp_hdr->Command = SMB2_NEGOTIATE; 325 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR); 326 rsp_hdr->NextCommand = 0; 327 rsp_hdr->MessageId = 0; 328 rsp_hdr->Id.SyncId.ProcessId = 0; 329 rsp_hdr->Id.SyncId.TreeId = 0; 330 rsp_hdr->SessionId = 0; 331 memset(rsp_hdr->Signature, 0, 16); 332 333 rsp = smb_get_msg(work->response_buf); 334 335 WARN_ON(ksmbd_conn_good(conn)); 336 337 rsp->StructureSize = cpu_to_le16(65); 338 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect); 339 rsp->DialectRevision = cpu_to_le16(conn->dialect); 340 /* Not setting conn guid rsp->ServerGUID, as it 341 * not used by client for identifying connection 342 */ 343 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities); 344 /* Default Max Message Size till SMB2.0, 64K*/ 345 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size); 346 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size); 347 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size); 348 349 rsp->SystemTime = cpu_to_le64(ksmbd_systime()); 350 rsp->ServerStartTime = 0; 351 352 rsp->SecurityBufferOffset = cpu_to_le16(128); 353 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH); 354 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) + 355 le16_to_cpu(rsp->SecurityBufferOffset)); 356 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE; 357 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) 358 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE; 359 err = ksmbd_iov_pin_rsp(work, rsp, 360 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH); 361 if (err) 362 return err; 363 conn->use_spnego = true; 364 365 ksmbd_conn_set_need_negotiate(conn); 366 return 0; 367 } 368 369 /** 370 * smb2_set_rsp_credits() - set number of credits in response buffer 371 * @work: smb work containing smb response buffer 372 */ 373 int smb2_set_rsp_credits(struct ksmbd_work *work) 374 { 375 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work); 376 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work); 377 struct ksmbd_conn *conn = work->conn; 378 unsigned short credits_requested, aux_max; 379 unsigned short credit_charge, credits_granted = 0; 380 u64 window_room, i; 381 382 if (work->send_no_response) 383 return 0; 384 385 hdr->CreditCharge = req_hdr->CreditCharge; 386 387 if (conn->total_credits > conn->vals->max_credits) { 388 hdr->CreditRequest = 0; 389 pr_err("Total credits overflow: %d\n", conn->total_credits); 390 return -EINVAL; 391 } 392 393 credit_charge = max_t(unsigned short, 394 le16_to_cpu(req_hdr->CreditCharge), 1); 395 if (credit_charge > conn->total_credits) { 396 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n", 397 credit_charge, conn->total_credits); 398 return -EINVAL; 399 } 400 401 conn->total_credits -= credit_charge; 402 conn->outstanding_credits -= credit_charge; 403 work->credit_charge = 0; 404 credits_requested = max_t(unsigned short, 405 le16_to_cpu(req_hdr->CreditRequest), 1); 406 407 /* according to smb2.credits smbtorture, Windows server 408 * 2016 or later grant up to 8192 credits at once. 409 * 410 * TODO: Need to adjuct CreditRequest value according to 411 * current cpu load 412 */ 413 if (hdr->Command == SMB2_NEGOTIATE) 414 aux_max = 1; 415 else 416 aux_max = conn->vals->max_credits - conn->total_credits; 417 418 /* 419 * The command sequence window must not grow beyond 420 * KSMBD_CMD_SEQ_WINDOW sequence numbers ahead of the oldest one still 421 * outstanding. Cap the grant by the room left in the window so that 422 * credits are withheld until the client consumes the low end (and so 423 * that seq_bitmap stays usable as a ring). 424 */ 425 window_room = conn->seq_low + KSMBD_CMD_SEQ_WINDOW - conn->seq_high; 426 aux_max = min_t(unsigned short, aux_max, window_room); 427 credits_granted = min_t(unsigned short, credits_requested, aux_max); 428 429 conn->total_credits += credits_granted; 430 work->credits_granted += credits_granted; 431 432 /* Extend the sequence window to cover the newly granted credits. */ 433 for (i = conn->seq_high; i < conn->seq_high + credits_granted; i++) 434 __set_bit(i & (KSMBD_CMD_SEQ_WINDOW - 1), conn->seq_bitmap); 435 conn->seq_high += credits_granted; 436 437 if (!req_hdr->NextCommand) { 438 /* Update CreditRequest in last request */ 439 hdr->CreditRequest = cpu_to_le16(work->credits_granted); 440 } 441 ksmbd_debug(SMB, 442 "credits: requested[%d] granted[%d] total_granted[%d]\n", 443 credits_requested, credits_granted, 444 conn->total_credits); 445 return 0; 446 } 447 448 /** 449 * init_chained_smb2_rsp() - initialize smb2 chained response 450 * @work: smb work containing smb response buffer 451 */ 452 static void init_chained_smb2_rsp(struct ksmbd_work *work) 453 { 454 struct smb2_hdr *req = ksmbd_req_buf_next(work); 455 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work); 456 struct smb2_hdr *rsp_hdr; 457 struct smb2_hdr *rcv_hdr; 458 int next_hdr_offset = 0; 459 int len, new_len; 460 461 /* Len of this response = updated RFC len - offset of previous cmd 462 * in the compound rsp 463 */ 464 465 /* Storing the current local FID which may be needed by subsequent 466 * command in the compound request 467 */ 468 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) { 469 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId; 470 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId; 471 work->compound_sid = le64_to_cpu(rsp->SessionId); 472 work->compound_status = STATUS_SUCCESS; 473 } else if ((req->Command == SMB2_FLUSH || 474 req->Command == SMB2_READ || 475 req->Command == SMB2_WRITE) && 476 rsp->Status == STATUS_SUCCESS) { 477 u64 volatile_id = KSMBD_NO_FID; 478 u64 persistent_id = KSMBD_NO_FID; 479 480 if (req->Command == SMB2_FLUSH) { 481 struct smb2_flush_req *flush_req = 482 (struct smb2_flush_req *)req; 483 484 volatile_id = flush_req->VolatileFileId; 485 persistent_id = flush_req->PersistentFileId; 486 } else if (req->Command == SMB2_READ) { 487 struct smb2_read_req *read_req = 488 (struct smb2_read_req *)req; 489 490 volatile_id = read_req->VolatileFileId; 491 persistent_id = read_req->PersistentFileId; 492 } else { 493 struct smb2_write_req *write_req = 494 (struct smb2_write_req *)req; 495 496 volatile_id = write_req->VolatileFileId; 497 persistent_id = write_req->PersistentFileId; 498 } 499 500 if (has_file_id(volatile_id)) { 501 work->compound_fid = volatile_id; 502 work->compound_pfid = persistent_id; 503 work->compound_sid = le64_to_cpu(rsp->SessionId); 504 work->compound_status = STATUS_SUCCESS; 505 } 506 } else if (req->Command == SMB2_CREATE) { 507 work->compound_fid = KSMBD_NO_FID; 508 work->compound_pfid = KSMBD_NO_FID; 509 work->compound_sid = le64_to_cpu(rsp->SessionId); 510 work->compound_status = rsp->Status; 511 } else if (rsp->Status != STATUS_SUCCESS) { 512 work->compound_sid = le64_to_cpu(rsp->SessionId); 513 /* 514 * Only carry the failed status forward when the failing command 515 * was itself part of the related chain. An unrelated command 516 * that fails (e.g. a standalone request with a bad session id) 517 * must not seed the status for a following related command, 518 * which has to be evaluated on its own (and may legitimately 519 * fail with a different status such as INVALID_PARAMETER). The 520 * compound session id is still tracked so a following related 521 * command can validate it. 522 */ 523 if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS) 524 work->compound_status = rsp->Status; 525 } 526 527 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off; 528 next_hdr_offset = le32_to_cpu(req->NextCommand); 529 530 new_len = ALIGN(len, 8); 531 work->iov[work->iov_idx].iov_len += (new_len - len); 532 inc_rfc1001_len(work->response_buf, new_len - len); 533 rsp->NextCommand = cpu_to_le32(new_len); 534 535 work->next_smb2_rcv_hdr_off += next_hdr_offset; 536 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off; 537 work->next_smb2_rsp_hdr_off += new_len; 538 ksmbd_debug(SMB, 539 "Compound req new_len = %d rcv off = %d rsp off = %d\n", 540 new_len, work->next_smb2_rcv_hdr_off, 541 work->next_smb2_rsp_hdr_off); 542 543 rsp_hdr = ksmbd_resp_buf_next(work); 544 rcv_hdr = ksmbd_req_buf_next(work); 545 546 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) { 547 ksmbd_debug(SMB, "related flag should be set\n"); 548 work->compound_fid = KSMBD_NO_FID; 549 work->compound_pfid = KSMBD_NO_FID; 550 work->compound_status = STATUS_SUCCESS; 551 } 552 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2); 553 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER; 554 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE; 555 rsp_hdr->Command = rcv_hdr->Command; 556 557 /* 558 * Message is response. We don't grant oplock yet. 559 */ 560 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR | 561 SMB2_FLAGS_RELATED_OPERATIONS); 562 if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION) 563 rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION; 564 rsp_hdr->NextCommand = 0; 565 rsp_hdr->MessageId = rcv_hdr->MessageId; 566 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId; 567 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId; 568 rsp_hdr->SessionId = rcv_hdr->SessionId; 569 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16); 570 } 571 572 static bool smb2_compound_has_failed(struct ksmbd_work *work, 573 struct smb2_hdr *rsp) 574 { 575 if (!work->next_smb2_rcv_hdr_off || 576 has_file_id(work->compound_fid) || 577 work->compound_status == STATUS_SUCCESS) 578 return false; 579 580 rsp->Status = work->compound_status; 581 smb2_set_err_rsp(work); 582 return true; 583 } 584 585 /** 586 * is_chained_smb2_message() - check for chained command 587 * @work: smb work containing smb request buffer 588 * 589 * Return: true if chained request, otherwise false 590 */ 591 bool is_chained_smb2_message(struct ksmbd_work *work) 592 { 593 struct smb2_hdr *hdr = smb_get_msg(work->request_buf); 594 unsigned int len, next_cmd; 595 596 if (hdr->ProtocolId != SMB2_PROTO_NUMBER) 597 return false; 598 599 hdr = ksmbd_req_buf_next(work); 600 next_cmd = le32_to_cpu(hdr->NextCommand); 601 if (next_cmd > 0) { 602 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd + 603 __SMB2_HEADER_STRUCTURE_SIZE > 604 get_rfc1002_len(work->request_buf)) { 605 pr_err("next command(%u) offset exceeds smb msg size\n", 606 next_cmd); 607 return false; 608 } 609 610 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE > 611 work->response_sz) { 612 pr_err("next response offset exceeds response buffer size\n"); 613 return false; 614 } 615 616 ksmbd_debug(SMB, "got SMB2 chained command\n"); 617 init_chained_smb2_rsp(work); 618 return true; 619 } else if (work->next_smb2_rcv_hdr_off) { 620 /* 621 * This is last request in chained command, 622 * align response to 8 byte 623 */ 624 len = ALIGN(get_rfc1002_len(work->response_buf), 8); 625 len = len - get_rfc1002_len(work->response_buf); 626 if (len) { 627 ksmbd_debug(SMB, "padding len %u\n", len); 628 work->iov[work->iov_idx].iov_len += len; 629 inc_rfc1001_len(work->response_buf, len); 630 } 631 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off; 632 } 633 return false; 634 } 635 636 /** 637 * init_smb2_rsp_hdr() - initialize smb2 response 638 * @work: smb work containing smb request buffer 639 * 640 * Return: 0 641 */ 642 int init_smb2_rsp_hdr(struct ksmbd_work *work) 643 { 644 struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf); 645 struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf); 646 647 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2); 648 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId; 649 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE; 650 rsp_hdr->Command = rcv_hdr->Command; 651 652 /* 653 * Message is response. We don't grant oplock yet. 654 */ 655 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR); 656 if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION) 657 rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION; 658 rsp_hdr->NextCommand = 0; 659 rsp_hdr->MessageId = rcv_hdr->MessageId; 660 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId; 661 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId; 662 rsp_hdr->SessionId = rcv_hdr->SessionId; 663 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16); 664 665 return 0; 666 } 667 668 static __le16 smb3_hdr_channel_sequence(struct smb2_hdr *hdr) 669 { 670 return ((struct smb3_hdr_req *)hdr)->ChannelSequence; 671 } 672 673 static bool smb3_hdr_replay(struct smb2_hdr *hdr) 674 { 675 return hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION; 676 } 677 678 static int smb3_verify_channel_sequence(struct ksmbd_work *work, 679 struct ksmbd_file *fp, 680 struct smb2_hdr *hdr, 681 bool allow_stale) 682 { 683 __le16 chseq_le; 684 u16 chseq, old_chseq; 685 int ret = 0; 686 687 if (work->conn->dialect < SMB30_PROT_ID) 688 return 0; 689 690 chseq_le = smb3_hdr_channel_sequence(hdr); 691 chseq = le16_to_cpu(chseq_le); 692 693 spin_lock(&fp->f_lock); 694 old_chseq = le16_to_cpu(fp->channel_sequence); 695 if (smb3_hdr_replay(hdr)) { 696 if (chseq == old_chseq && fp->outstanding_pre_requests == 0) { 697 fp->outstanding_requests++; 698 } else if ((u16)(chseq - old_chseq) <= 0x7fff && 699 fp->outstanding_pre_requests == 0) { 700 fp->outstanding_pre_requests += fp->outstanding_requests; 701 fp->outstanding_requests = 1; 702 fp->channel_sequence = chseq_le; 703 } else if (allow_stale) { 704 fp->outstanding_pre_requests++; 705 } else { 706 ret = -EAGAIN; 707 } 708 } else { 709 if (chseq == old_chseq) { 710 fp->outstanding_requests++; 711 } else if ((u16)(chseq - old_chseq) <= 0x7fff) { 712 fp->outstanding_pre_requests += fp->outstanding_requests; 713 fp->outstanding_requests = 1; 714 fp->channel_sequence = chseq_le; 715 } else if (allow_stale) { 716 fp->outstanding_pre_requests++; 717 } else { 718 ret = -EAGAIN; 719 } 720 } 721 spin_unlock(&fp->f_lock); 722 723 return ret; 724 } 725 726 static void smb3_complete_channel_sequence(struct ksmbd_work *work, 727 struct ksmbd_file *fp, 728 __le16 chseq_le) 729 { 730 u16 chseq; 731 732 if (work->conn->dialect < SMB30_PROT_ID) 733 return; 734 735 chseq = le16_to_cpu(chseq_le); 736 737 spin_lock(&fp->f_lock); 738 if (chseq == le16_to_cpu(fp->channel_sequence)) { 739 if (fp->outstanding_requests) 740 fp->outstanding_requests--; 741 } else { 742 if (fp->outstanding_pre_requests) 743 fp->outstanding_pre_requests--; 744 } 745 spin_unlock(&fp->f_lock); 746 } 747 748 static int smb2_set_request_open(struct ksmbd_work *work, struct ksmbd_file *fp, 749 struct smb2_hdr *hdr, bool verify_chseq, 750 bool allow_stale_chseq) 751 { 752 struct ksmbd_file *open; 753 int ret; 754 755 smb2_complete_request_open(work); 756 757 open = ksmbd_file_get(fp); 758 if (!open) 759 return -ESTALE; 760 761 if (verify_chseq) { 762 ret = smb3_verify_channel_sequence(work, fp, hdr, 763 allow_stale_chseq); 764 if (ret) { 765 ksmbd_fd_put(work, open); 766 return ret; 767 } 768 work->request_open_chseq_tracked = true; 769 } 770 771 work->request_open = open; 772 work->request_open_chseq = smb3_hdr_channel_sequence(hdr); 773 return 0; 774 } 775 776 void smb2_complete_request_open(struct ksmbd_work *work) 777 { 778 struct ksmbd_file *open = work->request_open; 779 780 if (!open) 781 return; 782 783 if (work->request_open_chseq_tracked) 784 smb3_complete_channel_sequence(work, open, 785 work->request_open_chseq); 786 787 work->request_open = NULL; 788 work->request_open_chseq_tracked = false; 789 ksmbd_fd_put(work, open); 790 } 791 792 static bool smb2_lock_sequence_applicable(struct ksmbd_work *work, 793 struct ksmbd_file *fp) 794 { 795 return fp->is_resilient || fp->is_durable || fp->is_persistent || 796 (work->conn->dialect >= SMB30_PROT_ID && 797 (work->conn->vals->req_capabilities & 798 SMB2_GLOBAL_CAP_MULTI_CHANNEL)); 799 } 800 801 static bool smb2_verify_lock_sequence(struct ksmbd_work *work, 802 struct ksmbd_file *fp, 803 struct smb2_lock_req *req) 804 { 805 u32 val, index; 806 u8 sequence; 807 bool replay = false; 808 809 if (work->conn->dialect == SMB20_PROT_ID || 810 !smb2_lock_sequence_applicable(work, fp)) 811 return false; 812 813 val = le32_to_cpu(req->LockSequenceNumber); 814 sequence = val & 0xf; 815 index = val >> 4; 816 if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE) 817 return false; 818 819 spin_lock(&fp->f_lock); 820 if (fp->lock_seq[index - 1].valid) { 821 if (fp->lock_seq[index - 1].sequence == sequence) 822 replay = true; 823 else 824 fp->lock_seq[index - 1].valid = false; 825 } 826 spin_unlock(&fp->f_lock); 827 828 return replay; 829 } 830 831 static void smb2_update_lock_sequence(struct ksmbd_work *work, 832 struct ksmbd_file *fp, 833 struct smb2_lock_req *req) 834 { 835 u32 val, index; 836 u8 sequence; 837 838 if (work->conn->dialect == SMB20_PROT_ID || 839 !smb2_lock_sequence_applicable(work, fp)) 840 return; 841 842 val = le32_to_cpu(req->LockSequenceNumber); 843 sequence = val & 0xf; 844 index = val >> 4; 845 if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE) 846 return; 847 848 spin_lock(&fp->f_lock); 849 fp->lock_seq[index - 1].valid = true; 850 fp->lock_seq[index - 1].sequence = sequence; 851 spin_unlock(&fp->f_lock); 852 } 853 854 /** 855 * smb2_allocate_rsp_buf() - allocate smb2 response buffer 856 * @work: smb work containing smb request buffer 857 * 858 * Return: 0 on success, otherwise error 859 */ 860 int smb2_allocate_rsp_buf(struct ksmbd_work *work) 861 { 862 struct smb2_hdr *hdr = smb_get_msg(work->request_buf); 863 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE; 864 size_t large_sz = small_sz + work->conn->vals->max_trans_size; 865 size_t sz = small_sz; 866 int cmd = le16_to_cpu(hdr->Command); 867 868 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE) 869 sz = large_sz; 870 871 if (cmd == SMB2_QUERY_INFO_HE) { 872 struct smb2_query_info_req *req; 873 874 if (get_rfc1002_len(work->request_buf) < 875 offsetof(struct smb2_query_info_req, OutputBufferLength)) 876 return -EINVAL; 877 878 req = smb_get_msg(work->request_buf); 879 if ((req->InfoType == SMB2_O_INFO_FILE && 880 (req->FileInfoClass == FILE_FULL_EA_INFORMATION || 881 req->FileInfoClass == FILE_ALL_INFORMATION || 882 req->FileInfoClass == FILE_NORMALIZED_NAME_INFORMATION)) || 883 req->InfoType == SMB2_O_INFO_SECURITY) 884 sz = large_sz; 885 } 886 887 /* allocate large response buf for chained commands */ 888 if (le32_to_cpu(hdr->NextCommand) > 0) 889 sz = large_sz; 890 891 work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP); 892 if (!work->response_buf) 893 return -ENOMEM; 894 895 work->response_sz = sz; 896 return 0; 897 } 898 899 static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work, 900 unsigned int cmd) 901 { 902 struct smb2_lock_req *req; 903 unsigned int len, lock_count, i; 904 905 if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE || 906 cmd == SMB2_LOGOFF_HE) 907 return true; 908 if (cmd != SMB2_LOCK_HE) 909 return false; 910 911 req = ksmbd_req_buf_next(work); 912 if (req->hdr.NextCommand) 913 len = le32_to_cpu(req->hdr.NextCommand); 914 else { 915 len = get_rfc1002_len(work->request_buf); 916 if (len < work->next_smb2_rcv_hdr_off) 917 return false; 918 len -= work->next_smb2_rcv_hdr_off; 919 } 920 921 lock_count = le16_to_cpu(req->LockCount); 922 if (!lock_count || len < offsetof(struct smb2_lock_req, locks) || 923 lock_count > (len - offsetof(struct smb2_lock_req, locks)) / 924 sizeof(struct smb2_lock_element)) 925 return false; 926 927 for (i = 0; i < lock_count; i++) { 928 if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK) 929 return false; 930 } 931 return true; 932 } 933 934 static bool smb2_session_kerberos_expired(struct ksmbd_session *sess) 935 { 936 return sess->kerberos_expiry && 937 ktime_get_real_seconds() >= sess->kerberos_expiry; 938 } 939 940 /** 941 * smb2_check_user_session() - check for valid session for a user 942 * @work: smb work containing smb request buffer 943 * 944 * Return: 0 on success, otherwise error 945 */ 946 int smb2_check_user_session(struct ksmbd_work *work) 947 { 948 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work); 949 struct ksmbd_conn *conn = work->conn; 950 unsigned int cmd = le16_to_cpu(req_hdr->Command); 951 unsigned long long sess_id; 952 953 /* 954 * SMB2_NEGOTIATE and SMB2_SESSION_SETUP do not require a session id. 955 * SMB2_ECHO may omit it, but an echo carrying a session id still needs 956 * the session attached to work so that its signature can be checked and 957 * the response can be signed, including after Kerberos expiry. 958 */ 959 if (cmd == SMB2_NEGOTIATE_HE || cmd == SMB2_SESSION_SETUP_HE) 960 return 0; 961 962 sess_id = le64_to_cpu(req_hdr->SessionId); 963 if (cmd == SMB2_ECHO_HE) { 964 /* 965 * ECHO remains valid without a live session, including after 966 * LOGOFF. Attach an existing session only to authenticate a signed 967 * ECHO and sign its response; a stale SessionId is not an error. 968 */ 969 if (!work->next_smb2_rcv_hdr_off && sess_id) 970 work->sess = ksmbd_session_lookup_all_states(conn, sess_id); 971 if (work->sess) { 972 if (smb2_session_kerberos_expired(work->sess)) { 973 work->sess->state = SMB2_SESSION_EXPIRED; 974 } else if (work->sess->state != SMB2_SESSION_VALID) { 975 ksmbd_user_session_put(work->sess); 976 work->sess = NULL; 977 } 978 } 979 return 0; 980 } 981 982 if (!ksmbd_conn_good(conn)) 983 return -EIO; 984 985 /* 986 * If request is not the first in Compound request, 987 * Just validate session id in header with work->sess->id. 988 */ 989 if (work->next_smb2_rcv_hdr_off) { 990 if (!work->sess) { 991 pr_err("The first operation in the compound does not have sess\n"); 992 return -EINVAL; 993 } 994 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) { 995 pr_err("session id(%llu) is different with the first operation(%lld)\n", 996 sess_id, work->sess->id); 997 return -EINVAL; 998 } 999 if (smb2_session_kerberos_expired(work->sess)) 1000 work->sess->state = SMB2_SESSION_EXPIRED; 1001 if (work->sess->state != SMB2_SESSION_VALID) { 1002 pr_err("compound request on a non-valid session (state %d)\n", 1003 work->sess->state); 1004 if (smb2_session_kerberos_expired(work->sess) && 1005 smb2_session_expired_cmd_allowed(work, cmd)) 1006 return 1; 1007 return smb2_session_kerberos_expired(work->sess) ? 1008 -EKEYEXPIRED : -EINVAL; 1009 } 1010 return 1; 1011 } 1012 1013 /* Check for validity of user session */ 1014 work->sess = ksmbd_session_lookup_all_states(conn, sess_id); 1015 if (work->sess) { 1016 if (smb2_session_kerberos_expired(work->sess)) { 1017 work->sess->state = SMB2_SESSION_EXPIRED; 1018 return smb2_session_expired_cmd_allowed(work, cmd) ? 1019 1 : -EKEYEXPIRED; 1020 } 1021 if (work->sess->state != SMB2_SESSION_VALID) { 1022 /* 1023 * Keep the reference for an encrypted request so the caller can 1024 * return STATUS_USER_SESSION_DELETED encrypted with the old key. 1025 */ 1026 if (work->encrypted && 1027 work->sess->state == SMB2_SESSION_EXPIRED && 1028 work->sess->enc) 1029 return -ENOENT; 1030 ksmbd_user_session_put(work->sess); 1031 work->sess = NULL; 1032 return -ENOENT; 1033 } 1034 return 1; 1035 } 1036 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id); 1037 return -ENOENT; 1038 } 1039 1040 /** 1041 * smb2_get_name() - get filename string from on the wire smb format 1042 * @src: source buffer 1043 * @maxlen: maxlen of source string 1044 * @local_nls: nls_table pointer 1045 * 1046 * Return: matching converted filename on success, otherwise error ptr 1047 */ 1048 static char * 1049 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls) 1050 { 1051 char *name; 1052 1053 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls); 1054 if (IS_ERR(name)) { 1055 pr_err("failed to get name %ld\n", PTR_ERR(name)); 1056 return name; 1057 } 1058 1059 if (*name == '\0') { 1060 kfree(name); 1061 return ERR_PTR(-EINVAL); 1062 } 1063 1064 if (*name == '\\') { 1065 pr_err("not allow directory name included leading slash\n"); 1066 kfree(name); 1067 return ERR_PTR(-EINVAL); 1068 } 1069 1070 ksmbd_conv_path_to_unix(name); 1071 ksmbd_strip_last_slash(name); 1072 return name; 1073 } 1074 1075 /* Link a fully initialized async work item unless the connection is closing. */ 1076 static bool ksmbd_conn_link_async_request(struct ksmbd_conn *conn, 1077 struct ksmbd_work *work) 1078 { 1079 bool linked = false; 1080 1081 spin_lock(&conn->request_lock); 1082 if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) { 1083 if (list_empty(&work->async_request_entry)) 1084 list_add_tail(&work->async_request_entry, 1085 &conn->async_requests); 1086 linked = true; 1087 } 1088 spin_unlock(&conn->request_lock); 1089 1090 return linked; 1091 } 1092 1093 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg) 1094 { 1095 struct ksmbd_conn *conn = work->conn; 1096 int id; 1097 1098 id = ksmbd_acquire_async_msg_id(&conn->async_ida); 1099 if (id < 0) { 1100 pr_err("Failed to alloc async message id\n"); 1101 return id; 1102 } 1103 work->asynchronous = true; 1104 work->async_id = id; 1105 work->cancel_fn = fn; 1106 work->cancel_argv = arg; 1107 1108 if (!ksmbd_conn_link_async_request(conn, work)) { 1109 work->asynchronous = false; 1110 work->async_id = 0; 1111 work->cancel_fn = NULL; 1112 work->cancel_argv = NULL; 1113 ksmbd_release_id(&conn->async_ida, id); 1114 return -ESHUTDOWN; 1115 } 1116 1117 ksmbd_debug(SMB, 1118 "Send interim Response to inform async request id : %d\n", 1119 work->async_id); 1120 1121 return 0; 1122 } 1123 1124 void release_async_work(struct ksmbd_work *work) 1125 { 1126 struct ksmbd_conn *conn = work->conn; 1127 1128 spin_lock(&conn->request_lock); 1129 list_del_init(&work->async_request_entry); 1130 spin_unlock(&conn->request_lock); 1131 1132 work->asynchronous = 0; 1133 work->cancel_fn = NULL; 1134 kfree(work->cancel_argv); 1135 work->cancel_argv = NULL; 1136 if (work->async_id) { 1137 ksmbd_release_id(&conn->async_ida, work->async_id); 1138 work->async_id = 0; 1139 } 1140 } 1141 1142 static int smb2_send_interim_work(struct ksmbd_work *in_work, 1143 struct ksmbd_work *work, bool eor) 1144 { 1145 int err = 0; 1146 1147 in_work->encrypted = work->encrypted; 1148 if (work->encrypted && work->sess && work->sess->enc && 1149 work->conn->ops->encrypt_resp) { 1150 in_work->sess = work->sess; 1151 err = work->conn->ops->encrypt_resp(in_work); 1152 in_work->sess = NULL; 1153 } 1154 if (err) 1155 return err; 1156 1157 return eor ? ksmbd_conn_write_eor(in_work) : 1158 ksmbd_conn_write(in_work); 1159 } 1160 1161 static int smb2_send_interim_prefix_work(struct ksmbd_work *work) 1162 { 1163 struct ksmbd_work *in_work; 1164 unsigned int len, copied = 0; 1165 char *dst; 1166 int err = -ENOMEM; 1167 int i; 1168 1169 len = get_rfc1002_len(work->iov[0].iov_base); 1170 in_work = ksmbd_alloc_work_struct(); 1171 if (!in_work) 1172 return err; 1173 1174 in_work->response_buf = kvzalloc(len + 4, KSMBD_DEFAULT_GFP); 1175 if (!in_work->response_buf) 1176 goto out; 1177 in_work->response_sz = len + 4; 1178 in_work->conn = work->conn; 1179 dst = in_work->response_buf + 4; 1180 for (i = 1; i <= work->iov_idx; i++) { 1181 if (work->iov[i].iov_len > len - copied) { 1182 err = -EINVAL; 1183 goto out; 1184 } 1185 memcpy(dst + copied, work->iov[i].iov_base, 1186 work->iov[i].iov_len); 1187 copied += work->iov[i].iov_len; 1188 } 1189 if (copied != len) { 1190 err = -EINVAL; 1191 goto out; 1192 } 1193 1194 err = ksmbd_iov_pin_rsp(in_work, dst, len); 1195 if (!err) 1196 err = smb2_send_interim_work(in_work, work, true); 1197 out: 1198 ksmbd_free_work_struct(in_work); 1199 return err; 1200 } 1201 1202 static void smb2_send_interim_compound_prefix(struct ksmbd_work *work) 1203 { 1204 struct smb2_hdr *req_hdr; 1205 struct smb2_hdr *rsp_hdr; 1206 int err; 1207 1208 if (!work->next_smb2_rcv_hdr_off || 1209 !work->next_smb2_rsp_hdr_off || 1210 work->curr_smb2_rsp_hdr_off == work->next_smb2_rsp_hdr_off || 1211 !work->iov_idx) 1212 return; 1213 1214 req_hdr = ksmbd_req_buf_next(work); 1215 /* Detach only the final async command from the completed prefix. */ 1216 if (req_hdr->NextCommand) 1217 return; 1218 1219 /* 1220 * The responses before the async command are sent as a standalone 1221 * compound response. The last response in this prefix must terminate 1222 * the chain. 1223 */ 1224 rsp_hdr = ksmbd_resp_buf_curr(work); 1225 rsp_hdr->NextCommand = 0; 1226 if ((rsp_hdr->Flags & SMB2_FLAGS_SIGNED) && work->sess && 1227 work->conn->ops->set_sign_rsp) 1228 work->conn->ops->set_sign_rsp(work); 1229 1230 err = smb2_send_interim_prefix_work(work); 1231 if (err) 1232 ksmbd_debug(SMB, "failed to send compound interim prefix: %d\n", 1233 err); 1234 1235 work->iov_idx = 0; 1236 work->iov_cnt = 0; 1237 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off; 1238 *(__be32 *)work->response_buf = 0; 1239 1240 rsp_hdr = ksmbd_resp_buf_next(work); 1241 rsp_hdr->Flags &= ~SMB2_FLAGS_RELATED_OPERATIONS; 1242 } 1243 1244 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status) 1245 { 1246 struct smb2_hdr *rsp_hdr; 1247 struct ksmbd_work *in_work = ksmbd_alloc_work_struct(); 1248 1249 if (!in_work) 1250 return; 1251 1252 if (allocate_interim_rsp_buf(in_work)) { 1253 pr_err("smb_allocate_rsp_buf failed!\n"); 1254 ksmbd_free_work_struct(in_work); 1255 return; 1256 } 1257 1258 if (status == STATUS_PENDING) 1259 smb2_send_interim_compound_prefix(work); 1260 1261 in_work->conn = work->conn; 1262 memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work), 1263 __SMB2_HEADER_STRUCTURE_SIZE); 1264 1265 rsp_hdr = smb_get_msg(in_work->response_buf); 1266 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND; 1267 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id); 1268 smb2_set_err_rsp(in_work); 1269 rsp_hdr->Status = status; 1270 1271 if (smb2_send_interim_work(in_work, work, true)) 1272 ksmbd_debug(SMB, "failed to send interim response\n"); 1273 ksmbd_free_work_struct(in_work); 1274 } 1275 1276 static __le32 smb2_get_reparse_tag_special_file(umode_t mode) 1277 { 1278 if (S_ISDIR(mode) || S_ISREG(mode)) 1279 return 0; 1280 1281 if (S_ISLNK(mode)) 1282 return IO_REPARSE_TAG_LX_SYMLINK_LE; 1283 else if (S_ISFIFO(mode)) 1284 return IO_REPARSE_TAG_LX_FIFO_LE; 1285 else if (S_ISSOCK(mode)) 1286 return IO_REPARSE_TAG_AF_UNIX_LE; 1287 else if (S_ISCHR(mode)) 1288 return IO_REPARSE_TAG_LX_CHR_LE; 1289 else if (S_ISBLK(mode)) 1290 return IO_REPARSE_TAG_LX_BLK_LE; 1291 1292 return 0; 1293 } 1294 1295 /** 1296 * smb2_get_dos_mode() - get file mode in dos format from unix mode 1297 * @stat: kstat containing file mode 1298 * @attribute: attribute flags 1299 * 1300 * Return: converted dos mode 1301 */ 1302 static int smb2_get_dos_mode(struct kstat *stat, int attribute) 1303 { 1304 int attr = 0; 1305 1306 if (S_ISDIR(stat->mode)) { 1307 attr = FILE_ATTRIBUTE_DIRECTORY | 1308 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)); 1309 } else { 1310 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE; 1311 attr &= ~(FILE_ATTRIBUTE_DIRECTORY); 1312 1313 if (smb2_get_reparse_tag_special_file(stat->mode)) 1314 attr |= FILE_ATTRIBUTE_REPARSE_POINT; 1315 } 1316 1317 return attr; 1318 } 1319 1320 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt, 1321 __le16 hash_id) 1322 { 1323 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES; 1324 pneg_ctxt->DataLength = cpu_to_le16(38); 1325 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1); 1326 pneg_ctxt->Reserved = cpu_to_le32(0); 1327 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE); 1328 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE); 1329 pneg_ctxt->HashAlgorithms = hash_id; 1330 } 1331 1332 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt, 1333 __le16 cipher_type) 1334 { 1335 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES; 1336 pneg_ctxt->DataLength = cpu_to_le16(4); 1337 pneg_ctxt->Reserved = cpu_to_le32(0); 1338 pneg_ctxt->CipherCount = cpu_to_le16(1); 1339 pneg_ctxt->Ciphers[0] = cipher_type; 1340 } 1341 1342 static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt, 1343 __le16 compress_algorithm, bool compress_chained, 1344 bool compress_pattern) 1345 { 1346 /* 1347 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised 1348 * as a second ID when the client also enabled chained transforms. 1349 */ 1350 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES; 1351 pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10); 1352 pneg_ctxt->Reserved = cpu_to_le32(0); 1353 pneg_ctxt->CompressionAlgorithmCount = 1354 cpu_to_le16(compress_pattern ? 2 : 1); 1355 pneg_ctxt->Padding = cpu_to_le16(0); 1356 pneg_ctxt->Flags = compress_chained ? 1357 SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED : 1358 SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE; 1359 pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm; 1360 pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ? 1361 SMB3_COMPRESS_PATTERN : 0; 1362 pneg_ctxt->CompressionAlgorithms[2] = 0; 1363 pneg_ctxt->CompressionAlgorithms[3] = 0; 1364 } 1365 1366 /** 1367 * build_rdma_ctx() - build an RDMA transform negotiate response context 1368 * @ctxt: response context header to populate 1369 * @transform_ids: bitmap of transforms common to the client and server 1370 * 1371 * Return: encoded negotiate context length 1372 */ 1373 static int build_rdma_ctx(struct smb2_neg_context *ctxt, 1374 unsigned long transform_ids) 1375 { 1376 struct smb2_rdma_transform_capabilities_context *pneg_ctxt; 1377 int count = 0; 1378 1379 pneg_ctxt = (void *)ctxt; 1380 pneg_ctxt->ContextType = SMB2_RDMA_TRANSFORM_CAPABILITIES; 1381 pneg_ctxt->Reserved = 0; 1382 pneg_ctxt->Reserved1 = 0; 1383 pneg_ctxt->Reserved2 = 0; 1384 if (transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) 1385 pneg_ctxt->RDMATransformIds[count++] = 1386 cpu_to_le16(SMB2_RDMA_TRANSFORM_ENCRYPTION); 1387 if (!count) 1388 pneg_ctxt->RDMATransformIds[count++] = 1389 cpu_to_le16(SMB2_RDMA_TRANSFORM_NONE); 1390 1391 pneg_ctxt->TransformCount = cpu_to_le16(count); 1392 pneg_ctxt->DataLength = cpu_to_le16(8 + count * sizeof(__le16)); 1393 return sizeof(struct smb2_neg_context) + 1394 le16_to_cpu(pneg_ctxt->DataLength); 1395 } 1396 1397 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt, 1398 __le16 sign_algo) 1399 { 1400 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES; 1401 pneg_ctxt->DataLength = 1402 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2) 1403 - sizeof(struct smb2_neg_context)); 1404 pneg_ctxt->Reserved = cpu_to_le32(0); 1405 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1); 1406 pneg_ctxt->SigningAlgorithms[0] = sign_algo; 1407 } 1408 1409 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt) 1410 { 1411 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE; 1412 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN); 1413 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */ 1414 pneg_ctxt->Name[0] = 0x93; 1415 pneg_ctxt->Name[1] = 0xAD; 1416 pneg_ctxt->Name[2] = 0x25; 1417 pneg_ctxt->Name[3] = 0x50; 1418 pneg_ctxt->Name[4] = 0x9C; 1419 pneg_ctxt->Name[5] = 0xB4; 1420 pneg_ctxt->Name[6] = 0x11; 1421 pneg_ctxt->Name[7] = 0xE7; 1422 pneg_ctxt->Name[8] = 0xB4; 1423 pneg_ctxt->Name[9] = 0x23; 1424 pneg_ctxt->Name[10] = 0x83; 1425 pneg_ctxt->Name[11] = 0xDE; 1426 pneg_ctxt->Name[12] = 0x96; 1427 pneg_ctxt->Name[13] = 0x8B; 1428 pneg_ctxt->Name[14] = 0xCD; 1429 pneg_ctxt->Name[15] = 0x7C; 1430 } 1431 1432 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn, 1433 struct smb2_negotiate_rsp *rsp) 1434 { 1435 char * const pneg_ctxt = (char *)rsp + 1436 le32_to_cpu(rsp->NegotiateContextOffset); 1437 int neg_ctxt_cnt = 1; 1438 int ctxt_size; 1439 1440 ksmbd_debug(SMB, 1441 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n"); 1442 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt, 1443 conn->preauth_info->Preauth_HashId); 1444 ctxt_size = sizeof(struct smb2_preauth_neg_context); 1445 1446 if (conn->cipher_type) { 1447 /* Round to 8 byte boundary */ 1448 ctxt_size = round_up(ctxt_size, 8); 1449 ksmbd_debug(SMB, 1450 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n"); 1451 build_encrypt_ctxt((struct smb2_encryption_neg_context *) 1452 (pneg_ctxt + ctxt_size), 1453 conn->cipher_type); 1454 neg_ctxt_cnt++; 1455 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2; 1456 } 1457 1458 if (conn->compress_algorithm != SMB3_COMPRESS_NONE) { 1459 ctxt_size = round_up(ctxt_size, 8); 1460 ksmbd_debug(SMB, 1461 "assemble SMB2_COMPRESSION_CAPABILITIES context\n"); 1462 build_compress_ctxt((struct smb2_compression_capabilities_context *) 1463 (pneg_ctxt + ctxt_size), 1464 conn->compress_algorithm, 1465 conn->compress_chained, 1466 conn->compress_pattern); 1467 neg_ctxt_cnt++; 1468 ctxt_size += sizeof(struct smb2_neg_context) + 1469 (conn->compress_pattern ? 12 : 10); 1470 } 1471 1472 if (conn->rdma_transform_negotiated) { 1473 struct smb2_neg_context *rdma_ctxt; 1474 1475 ctxt_size = round_up(ctxt_size, 8); 1476 ksmbd_debug(SMB, 1477 "assemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n"); 1478 rdma_ctxt = (void *)(pneg_ctxt + ctxt_size); 1479 ctxt_size += build_rdma_ctx(rdma_ctxt, 1480 conn->rdma_transform_ids); 1481 neg_ctxt_cnt++; 1482 } 1483 1484 if (conn->posix_ext_supported) { 1485 ctxt_size = round_up(ctxt_size, 8); 1486 ksmbd_debug(SMB, 1487 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n"); 1488 build_posix_ctxt((struct smb2_posix_neg_context *) 1489 (pneg_ctxt + ctxt_size)); 1490 neg_ctxt_cnt++; 1491 ctxt_size += sizeof(struct smb2_posix_neg_context); 1492 } 1493 1494 if (conn->signing_negotiated) { 1495 ctxt_size = round_up(ctxt_size, 8); 1496 ksmbd_debug(SMB, 1497 "assemble SMB2_SIGNING_CAPABILITIES context\n"); 1498 build_sign_cap_ctxt((struct smb2_signing_capabilities *) 1499 (pneg_ctxt + ctxt_size), 1500 conn->signing_algorithm); 1501 neg_ctxt_cnt++; 1502 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2; 1503 } 1504 1505 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt); 1506 return ctxt_size + AUTH_GSS_PADDING; 1507 } 1508 1509 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn, 1510 struct smb2_preauth_neg_context *pneg_ctxt, 1511 int ctxt_len) 1512 { 1513 /* 1514 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt, 1515 * which may not be present. Only check for used HashAlgorithms[1]. 1516 */ 1517 if (ctxt_len < 1518 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN) 1519 return STATUS_INVALID_PARAMETER; 1520 1521 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512) 1522 return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP; 1523 1524 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512; 1525 return STATUS_SUCCESS; 1526 } 1527 1528 static void decode_encrypt_ctxt(struct ksmbd_conn *conn, 1529 struct smb2_encryption_neg_context *pneg_ctxt, 1530 int ctxt_len) 1531 { 1532 int cph_cnt; 1533 int i, cphs_size; 1534 1535 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) { 1536 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n"); 1537 return; 1538 } 1539 1540 conn->cipher_type = 0; 1541 1542 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount); 1543 cphs_size = cph_cnt * sizeof(__le16); 1544 1545 if (sizeof(struct smb2_encryption_neg_context) + cphs_size > 1546 ctxt_len) { 1547 pr_err("Invalid cipher count(%d)\n", cph_cnt); 1548 return; 1549 } 1550 1551 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF) 1552 return; 1553 1554 for (i = 0; i < cph_cnt; i++) { 1555 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM || 1556 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM || 1557 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM || 1558 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) { 1559 ksmbd_debug(SMB, "Cipher ID = 0x%x\n", 1560 pneg_ctxt->Ciphers[i]); 1561 conn->cipher_type = pneg_ctxt->Ciphers[i]; 1562 break; 1563 } 1564 } 1565 } 1566 1567 /** 1568 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption 1569 * @conn: smb connection 1570 * 1571 * Return: true if connection should be encrypted, else false 1572 */ 1573 bool smb3_encryption_negotiated(struct ksmbd_conn *conn) 1574 { 1575 if (!conn->ops->generate_encryptionkey) 1576 return false; 1577 1578 /* 1579 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag. 1580 * SMB 3.1.1 uses the cipher_type field. 1581 */ 1582 return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) || 1583 conn->cipher_type; 1584 } 1585 1586 static __le32 decode_compress_ctxt(struct ksmbd_conn *conn, 1587 struct smb2_compression_capabilities_context *pneg_ctxt, 1588 int ctxt_len) 1589 { 1590 int alg_cnt, algs_size, i; 1591 __le16 *algs; 1592 1593 if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) { 1594 pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n"); 1595 return STATUS_INVALID_PARAMETER; 1596 } 1597 1598 conn->compress_algorithm = SMB3_COMPRESS_NONE; 1599 conn->compress_chained = false; 1600 conn->compress_pattern = false; 1601 1602 alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount); 1603 if (!alg_cnt) 1604 return STATUS_INVALID_PARAMETER; 1605 1606 if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE && 1607 pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED) 1608 return STATUS_INVALID_PARAMETER; 1609 1610 algs_size = alg_cnt * sizeof(__le16); 1611 if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) { 1612 pr_err("Invalid compression algorithm count(%d)\n", alg_cnt); 1613 return STATUS_INVALID_PARAMETER; 1614 } 1615 1616 /* 1617 * CompressionAlgorithms[] is declared as a fixed 4-element array, but 1618 * the actual element count is variable (clients such as Windows may 1619 * advertise more). The on-wire length was validated above, so walk the 1620 * algorithms through a pointer to avoid a fixed-array bounds check. 1621 */ 1622 algs = pneg_ctxt->CompressionAlgorithms; 1623 for (i = 0; i < alg_cnt; i++) { 1624 __le16 alg = algs[i]; 1625 1626 /* 1627 * LZ77 is the required general-purpose codec. Pattern_V1 is an 1628 * optional chained payload type and cannot stand alone. 1629 */ 1630 if (alg == SMB3_COMPRESS_LZ77) { 1631 conn->compress_algorithm = alg; 1632 conn->compress_chained = 1633 pneg_ctxt->Flags == 1634 SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED; 1635 ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n", 1636 le16_to_cpu(alg)); 1637 } else if (alg == SMB3_COMPRESS_PATTERN) { 1638 conn->compress_pattern = true; 1639 } 1640 } 1641 1642 if (conn->compress_algorithm == SMB3_COMPRESS_NONE || 1643 !conn->compress_chained) 1644 conn->compress_pattern = false; 1645 1646 return STATUS_SUCCESS; 1647 } 1648 1649 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn, 1650 struct smb2_signing_capabilities *pneg_ctxt, 1651 int ctxt_len) 1652 { 1653 int sign_algo_cnt; 1654 int i, sign_alos_size; 1655 1656 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) { 1657 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n"); 1658 return; 1659 } 1660 1661 conn->signing_negotiated = false; 1662 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount); 1663 sign_alos_size = sign_algo_cnt * sizeof(__le16); 1664 1665 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size > 1666 ctxt_len) { 1667 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt); 1668 return; 1669 } 1670 1671 for (i = 0; i < sign_algo_cnt; i++) { 1672 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE || 1673 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) { 1674 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n", 1675 pneg_ctxt->SigningAlgorithms[i]); 1676 conn->signing_negotiated = true; 1677 conn->signing_algorithm = 1678 pneg_ctxt->SigningAlgorithms[i]; 1679 break; 1680 } 1681 } 1682 } 1683 1684 /** 1685 * decode_rdma_ctx() - decode an RDMA transform negotiate request context 1686 * @conn: connection being negotiated 1687 * @ctxt: request context header to decode 1688 * @ctxt_len: total context length, including the negotiate context header 1689 * 1690 * Record transforms supported by both peers only for SMB Direct connections. 1691 * 1692 * Return: NT status describing the decode result 1693 */ 1694 static __le32 decode_rdma_ctx(struct ksmbd_conn *conn, 1695 struct smb2_neg_context *ctxt, int ctxt_len) 1696 { 1697 struct smb2_rdma_transform_capabilities_context *pneg_ctxt; 1698 unsigned int count, i; 1699 1700 pneg_ctxt = (void *)ctxt; 1701 /* RDMA transforms are a node capability, not just a transport capability. */ 1702 if (!ksmbd_rdma_enabled()) 1703 return STATUS_SUCCESS; 1704 1705 if (ctxt_len < sizeof(*pneg_ctxt)) 1706 return STATUS_INVALID_PARAMETER; 1707 1708 count = le16_to_cpu(pneg_ctxt->TransformCount); 1709 if (!count || count > 1710 (ctxt_len - sizeof(*pneg_ctxt)) / sizeof(__le16)) 1711 return STATUS_INVALID_PARAMETER; 1712 1713 conn->rdma_transform_negotiated = true; 1714 conn->rdma_transform_ids = 0; 1715 for (i = 0; i < count; i++) { 1716 u16 id = le16_to_cpu(pneg_ctxt->RDMATransformIds[i]); 1717 1718 if (id == SMB2_RDMA_TRANSFORM_ENCRYPTION) 1719 conn->rdma_transform_ids |= BIT(id); 1720 } 1721 return STATUS_SUCCESS; 1722 } 1723 1724 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn, 1725 struct smb2_negotiate_req *req, 1726 unsigned int len_of_smb) 1727 { 1728 /* +4 is to account for the RFC1001 len field */ 1729 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req; 1730 int i = 0, len_of_ctxts; 1731 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset); 1732 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount); 1733 __le32 status = STATUS_INVALID_PARAMETER; 1734 int compress_ctxt_cnt = 0, rdma_transform_ctxt_cnt = 0; 1735 1736 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt); 1737 if (len_of_smb <= offset) { 1738 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n"); 1739 return status; 1740 } 1741 1742 len_of_ctxts = len_of_smb - offset; 1743 1744 while (i++ < neg_ctxt_cnt) { 1745 int clen, ctxt_len; 1746 1747 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context)) 1748 break; 1749 1750 pctx = (struct smb2_neg_context *)((char *)pctx + offset); 1751 clen = le16_to_cpu(pctx->DataLength); 1752 ctxt_len = clen + sizeof(struct smb2_neg_context); 1753 1754 if (ctxt_len > len_of_ctxts) 1755 break; 1756 1757 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) { 1758 ksmbd_debug(SMB, 1759 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n"); 1760 if (conn->preauth_info->Preauth_HashId) 1761 break; 1762 1763 status = decode_preauth_ctxt(conn, 1764 (struct smb2_preauth_neg_context *)pctx, 1765 ctxt_len); 1766 if (status != STATUS_SUCCESS) 1767 break; 1768 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) { 1769 ksmbd_debug(SMB, 1770 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n"); 1771 if (conn->cipher_type) 1772 break; 1773 1774 decode_encrypt_ctxt(conn, 1775 (struct smb2_encryption_neg_context *)pctx, 1776 ctxt_len); 1777 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) { 1778 ksmbd_debug(SMB, 1779 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n"); 1780 if (compress_ctxt_cnt++) { 1781 status = STATUS_INVALID_PARAMETER; 1782 break; 1783 } 1784 1785 status = decode_compress_ctxt(conn, 1786 (struct smb2_compression_capabilities_context *) 1787 pctx, ctxt_len); 1788 if (status != STATUS_SUCCESS) 1789 break; 1790 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) { 1791 ksmbd_debug(SMB, 1792 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n"); 1793 } else if (pctx->ContextType == SMB2_RDMA_TRANSFORM_CAPABILITIES) { 1794 ksmbd_debug(SMB, 1795 "deassemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n"); 1796 if (ksmbd_rdma_enabled() && 1797 rdma_transform_ctxt_cnt++) { 1798 status = STATUS_INVALID_PARAMETER; 1799 break; 1800 } 1801 status = decode_rdma_ctx(conn, pctx, ctxt_len); 1802 if (status != STATUS_SUCCESS) 1803 break; 1804 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) { 1805 ksmbd_debug(SMB, 1806 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n"); 1807 conn->posix_ext_supported = true; 1808 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) { 1809 ksmbd_debug(SMB, 1810 "deassemble SMB2_SIGNING_CAPABILITIES context\n"); 1811 1812 decode_sign_cap_ctxt(conn, 1813 (struct smb2_signing_capabilities *)pctx, 1814 ctxt_len); 1815 } 1816 1817 /* offsets must be 8 byte aligned */ 1818 offset = (ctxt_len + 7) & ~0x7; 1819 len_of_ctxts -= offset; 1820 } 1821 return status; 1822 } 1823 1824 /** 1825 * smb2_handle_negotiate() - handler for smb2 negotiate command 1826 * @work: smb work containing smb request buffer 1827 * 1828 * The caller holds conn->srv_mutex. 1829 * 1830 * Return: 0 1831 */ 1832 int smb2_handle_negotiate(struct ksmbd_work *work) 1833 { 1834 struct ksmbd_conn *conn = work->conn; 1835 struct smb2_negotiate_req *req = smb_get_msg(work->request_buf); 1836 struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf); 1837 int rc = 0; 1838 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0; 1839 __le32 status; 1840 1841 ksmbd_debug(SMB, "Received negotiate request\n"); 1842 conn->need_neg = false; 1843 smb2_buf_len = get_rfc1002_len(work->request_buf); 1844 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects); 1845 if (smb2_neg_size > smb2_buf_len) { 1846 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1847 rc = -EINVAL; 1848 goto err_out; 1849 } 1850 1851 if (req->DialectCount == 0) { 1852 pr_err("malformed packet\n"); 1853 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1854 rc = -EINVAL; 1855 goto err_out; 1856 } 1857 1858 if (conn->dialect == SMB311_PROT_ID) { 1859 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset); 1860 1861 if (smb2_buf_len < nego_ctxt_off) { 1862 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1863 rc = -EINVAL; 1864 goto err_out; 1865 } 1866 1867 if (smb2_neg_size > nego_ctxt_off) { 1868 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1869 rc = -EINVAL; 1870 goto err_out; 1871 } 1872 1873 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) > 1874 nego_ctxt_off) { 1875 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1876 rc = -EINVAL; 1877 goto err_out; 1878 } 1879 } else { 1880 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) > 1881 smb2_buf_len) { 1882 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1883 rc = -EINVAL; 1884 goto err_out; 1885 } 1886 } 1887 1888 conn->cli_cap = le32_to_cpu(req->Capabilities); 1889 switch (conn->dialect) { 1890 case SMB311_PROT_ID: 1891 conn->preauth_info = 1892 kzalloc_obj(struct preauth_integrity_info, 1893 KSMBD_DEFAULT_GFP); 1894 if (!conn->preauth_info) { 1895 rc = -ENOMEM; 1896 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 1897 goto err_out; 1898 } 1899 1900 status = deassemble_neg_contexts(conn, req, 1901 get_rfc1002_len(work->request_buf)); 1902 if (status != STATUS_SUCCESS) { 1903 pr_err("deassemble_neg_contexts error(0x%x)\n", 1904 status); 1905 rsp->hdr.Status = status; 1906 rc = -EINVAL; 1907 kfree(conn->preauth_info); 1908 conn->preauth_info = NULL; 1909 goto err_out; 1910 } 1911 if (!conn->cipher_type) 1912 conn->rdma_transform_ids &= 1913 ~BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION); 1914 ksmbd_debug(RDMA, 1915 "RDMA transform negotiation: transport=%s context=%s encryption=%s cipher=0x%04x\n", 1916 conn->transport->ops->rdma_read ? "rdma" : "tcp", 1917 conn->rdma_transform_negotiated ? "present" : "absent", 1918 conn->rdma_transform_ids & 1919 BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION) ? "enabled" : "disabled", 1920 le16_to_cpu(conn->cipher_type)); 1921 1922 rc = init_smb3_11_server(conn); 1923 if (rc < 0) { 1924 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 1925 kfree(conn->preauth_info); 1926 conn->preauth_info = NULL; 1927 goto err_out; 1928 } 1929 1930 ksmbd_gen_preauth_integrity_hash(conn, 1931 work->request_buf, 1932 conn->preauth_info->Preauth_HashValue); 1933 rsp->NegotiateContextOffset = 1934 cpu_to_le32(OFFSET_OF_NEG_CONTEXT); 1935 neg_ctxt_len = assemble_neg_contexts(conn, rsp); 1936 break; 1937 case SMB302_PROT_ID: 1938 init_smb3_02_server(conn); 1939 break; 1940 case SMB30_PROT_ID: 1941 init_smb3_0_server(conn); 1942 break; 1943 case SMB21_PROT_ID: 1944 init_smb2_1_server(conn); 1945 break; 1946 case SMB2X_PROT_ID: 1947 case BAD_PROT_ID: 1948 default: 1949 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n", 1950 conn->dialect); 1951 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 1952 rc = -EINVAL; 1953 goto err_out; 1954 } 1955 rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities); 1956 1957 /* For stats */ 1958 conn->connection_type = conn->dialect; 1959 1960 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size); 1961 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size); 1962 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size); 1963 1964 memcpy(conn->ClientGUID, req->ClientGUID, 1965 SMB2_CLIENT_GUID_SIZE); 1966 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode); 1967 1968 rsp->StructureSize = cpu_to_le16(65); 1969 rsp->DialectRevision = cpu_to_le16(conn->dialect); 1970 /* Not setting conn guid rsp->ServerGUID, as it 1971 * not used by client for identifying server 1972 */ 1973 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE); 1974 1975 rsp->SystemTime = cpu_to_le64(ksmbd_systime()); 1976 rsp->ServerStartTime = 0; 1977 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n", 1978 le32_to_cpu(rsp->NegotiateContextOffset), 1979 le16_to_cpu(rsp->NegotiateContextCount)); 1980 1981 rsp->SecurityBufferOffset = cpu_to_le16(128); 1982 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH); 1983 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) + 1984 le16_to_cpu(rsp->SecurityBufferOffset)); 1985 1986 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE; 1987 conn->use_spnego = true; 1988 1989 if (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE) 1990 conn->sign = true; 1991 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) { 1992 server_conf.enforced_signing = true; 1993 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE; 1994 conn->sign = true; 1995 } 1996 1997 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode); 1998 ksmbd_conn_set_need_setup(conn); 1999 2000 err_out: 2001 if (rc && rsp->hdr.Status == STATUS_SUCCESS) 2002 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 2003 2004 if (!rc) 2005 rc = ksmbd_iov_pin_rsp(work, rsp, 2006 sizeof(struct smb2_negotiate_rsp) + 2007 AUTH_GSS_LENGTH + neg_ctxt_len); 2008 if (rc < 0) 2009 smb2_set_err_rsp(work); 2010 return rc; 2011 } 2012 2013 static int alloc_preauth_hash(struct ksmbd_session *sess, 2014 struct ksmbd_conn *conn) 2015 { 2016 if (sess->Preauth_HashValue) 2017 return 0; 2018 2019 if (!conn->preauth_info) 2020 return -ENOMEM; 2021 2022 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue, 2023 PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP); 2024 if (!sess->Preauth_HashValue) 2025 return -ENOMEM; 2026 2027 return 0; 2028 } 2029 2030 static int generate_preauth_hash(struct ksmbd_work *work) 2031 { 2032 struct ksmbd_conn *conn = work->conn; 2033 struct ksmbd_session *sess = work->sess; 2034 u8 *preauth_hash; 2035 2036 if (conn->dialect != SMB311_PROT_ID) 2037 return 0; 2038 2039 if (conn->binding) { 2040 struct preauth_session *preauth_sess; 2041 2042 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id); 2043 if (!preauth_sess) { 2044 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id); 2045 if (!preauth_sess) 2046 return -ENOMEM; 2047 } 2048 2049 preauth_hash = preauth_sess->Preauth_HashValue; 2050 } else { 2051 if (!sess->Preauth_HashValue) 2052 if (alloc_preauth_hash(sess, conn)) 2053 return -ENOMEM; 2054 preauth_hash = sess->Preauth_HashValue; 2055 } 2056 2057 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash); 2058 return 0; 2059 } 2060 2061 static int decode_negotiation_token(struct ksmbd_conn *conn, 2062 struct negotiate_message *negblob, 2063 size_t sz) 2064 { 2065 if (!conn->use_spnego) 2066 return -EINVAL; 2067 2068 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) { 2069 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) { 2070 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP; 2071 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP; 2072 conn->use_spnego = false; 2073 } 2074 } 2075 return 0; 2076 } 2077 2078 static int ntlm_negotiate(struct ksmbd_work *work, 2079 struct negotiate_message *negblob, 2080 size_t negblob_len, struct smb2_sess_setup_rsp *rsp) 2081 { 2082 struct challenge_message *chgblob; 2083 unsigned char *spnego_blob = NULL; 2084 u16 spnego_blob_len; 2085 char *neg_blob; 2086 int sz, rc; 2087 2088 ksmbd_debug(SMB, "negotiate phase\n"); 2089 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn); 2090 if (rc) 2091 return rc; 2092 2093 sz = le16_to_cpu(rsp->SecurityBufferOffset); 2094 chgblob = (struct challenge_message *)rsp->Buffer; 2095 memset(chgblob, 0, sizeof(struct challenge_message)); 2096 2097 if (!work->conn->use_spnego) { 2098 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn); 2099 if (sz < 0) 2100 return -ENOMEM; 2101 2102 rsp->SecurityBufferLength = cpu_to_le16(sz); 2103 return 0; 2104 } 2105 2106 sz = sizeof(struct challenge_message); 2107 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6; 2108 2109 neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP); 2110 if (!neg_blob) 2111 return -ENOMEM; 2112 2113 chgblob = (struct challenge_message *)neg_blob; 2114 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn); 2115 if (sz < 0) { 2116 rc = -ENOMEM; 2117 goto out; 2118 } 2119 2120 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len, 2121 neg_blob, sz); 2122 if (rc) { 2123 rc = -ENOMEM; 2124 goto out; 2125 } 2126 2127 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len); 2128 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len); 2129 2130 out: 2131 kfree(spnego_blob); 2132 kfree(neg_blob); 2133 return rc; 2134 } 2135 2136 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn, 2137 struct smb2_sess_setup_req *req) 2138 { 2139 int sz; 2140 2141 if (conn->use_spnego && conn->mechToken) 2142 return (struct authenticate_message *)conn->mechToken; 2143 2144 sz = le16_to_cpu(req->SecurityBufferOffset); 2145 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId 2146 + sz); 2147 } 2148 2149 static struct ksmbd_user *session_user(struct ksmbd_conn *conn, 2150 struct smb2_sess_setup_req *req) 2151 { 2152 struct authenticate_message *authblob; 2153 struct ksmbd_user *user; 2154 char *name; 2155 unsigned int name_off, name_len, secbuf_len; 2156 2157 if (conn->use_spnego && conn->mechToken) 2158 secbuf_len = conn->mechTokenLen; 2159 else 2160 secbuf_len = le16_to_cpu(req->SecurityBufferLength); 2161 if (secbuf_len < sizeof(struct authenticate_message)) { 2162 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len); 2163 return NULL; 2164 } 2165 authblob = user_authblob(conn, req); 2166 name_off = le32_to_cpu(authblob->UserName.BufferOffset); 2167 name_len = le16_to_cpu(authblob->UserName.Length); 2168 2169 if (secbuf_len < (u64)name_off + name_len) 2170 return NULL; 2171 2172 name = smb_strndup_from_utf16((const char *)authblob + name_off, 2173 name_len, 2174 true, 2175 conn->local_nls); 2176 if (IS_ERR(name)) { 2177 pr_err("cannot allocate memory\n"); 2178 return NULL; 2179 } 2180 2181 ksmbd_debug(SMB, "session setup request for user %s\n", name); 2182 user = ksmbd_login_user(name); 2183 kfree(name); 2184 return user; 2185 } 2186 2187 static int ntlm_authenticate(struct ksmbd_work *work, 2188 struct smb2_sess_setup_req *req, 2189 struct smb2_sess_setup_rsp *rsp) 2190 { 2191 struct ksmbd_conn *conn = work->conn; 2192 struct ksmbd_session *sess = work->sess; 2193 struct ksmbd_user *user; 2194 char channel_key[CIFS_KEY_SIZE] = {}; 2195 char *auth_key = conn->binding ? channel_key : sess->sess_key; 2196 u64 prev_id; 2197 bool binding = conn->binding; 2198 int sz, rc; 2199 2200 ksmbd_debug(SMB, "authenticate phase\n"); 2201 if (conn->use_spnego) { 2202 unsigned char *spnego_blob; 2203 u16 spnego_blob_len; 2204 2205 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob, 2206 &spnego_blob_len, 2207 0); 2208 if (rc) 2209 return -ENOMEM; 2210 2211 memcpy(rsp->Buffer, spnego_blob, spnego_blob_len); 2212 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len); 2213 kfree(spnego_blob); 2214 } 2215 2216 user = session_user(conn, req); 2217 if (!user) { 2218 ksmbd_debug(SMB, "Unknown user name or an error\n"); 2219 return -EPERM; 2220 } 2221 2222 if (sess->state == SMB2_SESSION_VALID) { 2223 /* 2224 * Reuse session if anonymous try to connect 2225 * on reauthetication. 2226 */ 2227 if (conn->binding == false && ksmbd_anonymous_user(user)) { 2228 ksmbd_free_user(user); 2229 return 0; 2230 } 2231 2232 if (!ksmbd_compare_user(sess->user, user)) { 2233 ksmbd_free_user(user); 2234 return -EKEYREJECTED; 2235 } 2236 ksmbd_free_user(user); 2237 } else { 2238 sess->user = user; 2239 } 2240 2241 if (conn->binding == false && user_guest(sess->user)) { 2242 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE; 2243 } else { 2244 struct authenticate_message *authblob; 2245 2246 authblob = user_authblob(conn, req); 2247 if (conn->use_spnego && conn->mechToken) 2248 sz = conn->mechTokenLen; 2249 else 2250 sz = le16_to_cpu(req->SecurityBufferLength); 2251 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess, 2252 auth_key); 2253 if (rc) { 2254 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD); 2255 ksmbd_debug(SMB, "authentication failed\n"); 2256 rc = -EPERM; 2257 goto out; 2258 } 2259 } 2260 2261 prev_id = le64_to_cpu(req->PreviousSessionId); 2262 if (prev_id && prev_id != sess->id) 2263 destroy_previous_session(conn, sess->user, prev_id); 2264 2265 /* 2266 * If session state is SMB2_SESSION_VALID, We can assume 2267 * that it is reauthentication. And the user/password 2268 * has been verified, so return it here. 2269 */ 2270 if (sess->state == SMB2_SESSION_VALID) { 2271 if (conn->binding) 2272 goto binding_session; 2273 return 0; 2274 } 2275 2276 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE && 2277 (conn->sign || server_conf.enforced_signing)) || 2278 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED)) 2279 sess->sign = true; 2280 2281 if (smb3_encryption_negotiated(conn) && 2282 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) { 2283 conn->ops->generate_encryptionkey(conn, sess); 2284 sess->enc = true; 2285 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION) 2286 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE; 2287 /* 2288 * signing is disable if encryption is enable 2289 * on this session 2290 */ 2291 sess->sign = false; 2292 } 2293 2294 binding_session: 2295 if (conn->dialect >= SMB30_PROT_ID) { 2296 rc = register_session_channel(sess, conn, auth_key); 2297 if (rc) 2298 goto out; 2299 } 2300 2301 if (conn->ops->generate_signingkey) { 2302 rc = conn->ops->generate_signingkey(sess, conn); 2303 if (rc) { 2304 ksmbd_debug(SMB, "SMB3 signing key generation failed\n"); 2305 rc = -EINVAL; 2306 goto out; 2307 } 2308 } 2309 2310 if (!ksmbd_conn_lookup_dialect(conn)) { 2311 pr_err("fail to verify the dialect\n"); 2312 rc = -ENOENT; 2313 goto out; 2314 } 2315 rc = 0; 2316 out: 2317 if (binding) 2318 memzero_explicit(channel_key, sizeof(channel_key)); 2319 return rc; 2320 } 2321 2322 #ifdef CONFIG_SMB_SERVER_KERBEROS5 2323 static int krb5_authenticate(struct ksmbd_work *work, 2324 struct smb2_sess_setup_req *req, 2325 struct smb2_sess_setup_rsp *rsp) 2326 { 2327 struct ksmbd_conn *conn = work->conn; 2328 struct ksmbd_session *sess = work->sess; 2329 char *in_blob, *out_blob; 2330 char channel_key[CIFS_KEY_SIZE] = {}; 2331 char reauth_key[CIFS_KEY_SIZE] = {}; 2332 char *auth_key = conn->binding ? channel_key : 2333 (work->session_setup_reauth ? reauth_key : sess->sess_key); 2334 u64 prev_sess_id; 2335 bool binding = conn->binding; 2336 int in_len, out_len; 2337 int retval; 2338 2339 in_blob = (char *)&req->hdr.ProtocolId + 2340 le16_to_cpu(req->SecurityBufferOffset); 2341 in_len = le16_to_cpu(req->SecurityBufferLength); 2342 out_blob = (char *)&rsp->hdr.ProtocolId + 2343 le16_to_cpu(rsp->SecurityBufferOffset); 2344 out_len = work->response_sz - work->next_smb2_rsp_hdr_off - 2345 (le16_to_cpu(rsp->SecurityBufferOffset) + 4); 2346 2347 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len, 2348 out_blob, &out_len, auth_key); 2349 if (retval) { 2350 ksmbd_debug(SMB, "krb5 authentication failed\n"); 2351 if (retval != -EKEYREJECTED) 2352 retval = -EPERM; 2353 goto out; 2354 } 2355 2356 /* Check previous session */ 2357 prev_sess_id = le64_to_cpu(req->PreviousSessionId); 2358 if (prev_sess_id && prev_sess_id != sess->id) 2359 destroy_previous_session(conn, sess->user, prev_sess_id); 2360 2361 rsp->SecurityBufferLength = cpu_to_le16(out_len); 2362 2363 /* 2364 * If session state is SMB2_SESSION_VALID, We can assume 2365 * that it is reauthentication. And the user/password 2366 * has been verified, so return it here. 2367 */ 2368 if (sess->state == SMB2_SESSION_VALID && !work->session_setup_reauth) { 2369 if (conn->binding) 2370 goto binding_session; 2371 return 0; 2372 } 2373 2374 /* 2375 * Reauthentication verifies the new Kerberos credentials but keeps 2376 * the established SMB session keys. 2377 */ 2378 if (work->session_setup_reauth) { 2379 retval = 0; 2380 goto out; 2381 } 2382 2383 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE && 2384 (conn->sign || server_conf.enforced_signing)) || 2385 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED)) 2386 sess->sign = true; 2387 2388 if (smb3_encryption_negotiated(conn) && 2389 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) { 2390 conn->ops->generate_encryptionkey(conn, sess); 2391 sess->enc = true; 2392 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION) 2393 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE; 2394 sess->sign = false; 2395 } 2396 2397 binding_session: 2398 if (conn->dialect >= SMB30_PROT_ID) { 2399 retval = register_session_channel(sess, conn, auth_key); 2400 if (retval) 2401 goto out; 2402 } 2403 2404 if (conn->ops->generate_signingkey) { 2405 retval = conn->ops->generate_signingkey(sess, conn); 2406 if (retval) { 2407 ksmbd_debug(SMB, "SMB3 signing key generation failed\n"); 2408 retval = -EINVAL; 2409 goto out; 2410 } 2411 } 2412 2413 if (!ksmbd_conn_lookup_dialect(conn)) { 2414 pr_err("fail to verify the dialect\n"); 2415 retval = -ENOENT; 2416 goto out; 2417 } 2418 retval = 0; 2419 out: 2420 memzero_explicit(reauth_key, sizeof(reauth_key)); 2421 if (binding) 2422 memzero_explicit(channel_key, sizeof(channel_key)); 2423 return retval; 2424 } 2425 #else 2426 static int krb5_authenticate(struct ksmbd_work *work, 2427 struct smb2_sess_setup_req *req, 2428 struct smb2_sess_setup_rsp *rsp) 2429 { 2430 return -EOPNOTSUPP; 2431 } 2432 #endif 2433 2434 int smb2_sess_setup(struct ksmbd_work *work) 2435 { 2436 struct ksmbd_conn *conn = work->conn; 2437 struct smb2_sess_setup_req *req; 2438 struct smb2_sess_setup_rsp *rsp; 2439 struct ksmbd_session *sess; 2440 struct negotiate_message *negblob; 2441 unsigned int negblob_len, negblob_off; 2442 int rc = 0; 2443 2444 ksmbd_debug(SMB, "Received smb2 session setup request\n"); 2445 2446 if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) { 2447 work->send_no_response = 1; 2448 return rc; 2449 } 2450 2451 WORK_BUFFERS(work, req, rsp); 2452 2453 rsp->StructureSize = cpu_to_le16(9); 2454 rsp->SessionFlags = 0; 2455 rsp->SecurityBufferOffset = cpu_to_le16(72); 2456 rsp->SecurityBufferLength = 0; 2457 2458 ksmbd_conn_lock(conn); 2459 if (!req->hdr.SessionId) { 2460 sess = ksmbd_smb2_session_create(); 2461 if (!sess) { 2462 rc = -ENOMEM; 2463 goto out_err; 2464 } 2465 rsp->hdr.SessionId = cpu_to_le64(sess->id); 2466 rc = ksmbd_session_register(conn, sess); 2467 if (rc) 2468 goto out_err; 2469 2470 conn->binding = false; 2471 } else if (conn->dialect >= SMB30_PROT_ID && 2472 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) && 2473 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) { 2474 u64 sess_id = le64_to_cpu(req->hdr.SessionId); 2475 2476 sess = ksmbd_session_lookup_slowpath(sess_id); 2477 if (!sess) { 2478 rc = -ENOENT; 2479 goto out_err; 2480 } 2481 2482 if (conn->dialect != sess->dialect) { 2483 rc = -EINVAL; 2484 goto out_err; 2485 } 2486 2487 if (conn->dialect == SMB311_PROT_ID) { 2488 struct channel *chann; 2489 unsigned long index; 2490 2491 down_read(&sess->chann_lock); 2492 xa_for_each(&sess->ksmbd_chann_list, index, chann) { 2493 if (conn->cipher_type != chann->conn->cipher_type) 2494 rc = -EINVAL; 2495 break; 2496 } 2497 up_read(&sess->chann_lock); 2498 if (rc) 2499 goto out_err; 2500 } 2501 2502 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) { 2503 rc = -EINVAL; 2504 goto out_err; 2505 } 2506 2507 if (memcmp(conn->ClientGUID, sess->ClientGUID, 2508 SMB2_CLIENT_GUID_SIZE)) { 2509 rc = -ENOENT; 2510 goto out_err; 2511 } 2512 2513 if (sess->state == SMB2_SESSION_IN_PROGRESS) { 2514 rc = -EACCES; 2515 goto out_err; 2516 } 2517 2518 if (sess->state == SMB2_SESSION_EXPIRED) { 2519 rc = -EFAULT; 2520 goto out_err; 2521 } 2522 2523 if (ksmbd_conn_need_reconnect(conn)) { 2524 rc = -EFAULT; 2525 ksmbd_user_session_put(sess); 2526 sess = NULL; 2527 goto out_err; 2528 } 2529 2530 if (is_ksmbd_session_in_connection(conn, sess_id)) { 2531 rc = -EACCES; 2532 goto out_err; 2533 } 2534 2535 if (user_guest(sess->user)) { 2536 rc = -EOPNOTSUPP; 2537 goto out_err; 2538 } 2539 2540 conn->binding = true; 2541 } else if ((conn->dialect < SMB30_PROT_ID || 2542 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) && 2543 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) { 2544 sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId)); 2545 if (sess) { 2546 int sign_ret; 2547 2548 work->sess = sess; 2549 if (sess->dialect >= SMB30_PROT_ID) 2550 sign_ret = smb3_check_sign_req(work); 2551 else 2552 sign_ret = smb2_check_sign_req(work); 2553 if (sess->state != SMB2_SESSION_VALID || 2554 !(req->hdr.Flags & SMB2_FLAGS_SIGNED) || 2555 !sign_ret) { 2556 ksmbd_user_session_put(sess); 2557 work->sess = NULL; 2558 sess = NULL; 2559 } 2560 } 2561 rc = -EACCES; 2562 goto out_err; 2563 } else { 2564 sess = ksmbd_session_lookup(conn, 2565 le64_to_cpu(req->hdr.SessionId)); 2566 if (!sess) { 2567 sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId)); 2568 if (sess && !lookup_chann_list(sess, conn)) { 2569 ksmbd_user_session_put(sess); 2570 sess = NULL; 2571 } 2572 } 2573 if (!sess) { 2574 rc = -ENOENT; 2575 goto out_err; 2576 } 2577 2578 if (sess->state == SMB2_SESSION_EXPIRED) { 2579 if (sess->kerberos_expiry && 2580 ktime_get_real_seconds() >= sess->kerberos_expiry) { 2581 work->session_setup_reauth = true; 2582 } else { 2583 rc = -EFAULT; 2584 goto out_err; 2585 } 2586 } 2587 2588 if (ksmbd_conn_need_reconnect(conn)) { 2589 rc = -EFAULT; 2590 ksmbd_user_session_put(sess); 2591 sess = NULL; 2592 goto out_err; 2593 } 2594 2595 conn->binding = false; 2596 } 2597 work->sess = sess; 2598 2599 negblob_off = le16_to_cpu(req->SecurityBufferOffset); 2600 negblob_len = le16_to_cpu(req->SecurityBufferLength); 2601 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) { 2602 rc = -EINVAL; 2603 goto out_err; 2604 } 2605 2606 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId + 2607 negblob_off); 2608 2609 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) { 2610 if (conn->mechToken) { 2611 negblob = (struct negotiate_message *)conn->mechToken; 2612 negblob_len = conn->mechTokenLen; 2613 } 2614 } 2615 2616 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) { 2617 rc = -EINVAL; 2618 goto out_err; 2619 } 2620 2621 if (server_conf.auth_mechs & conn->auth_mechs) { 2622 rc = generate_preauth_hash(work); 2623 if (rc) 2624 goto out_err; 2625 2626 if (conn->preferred_auth_mech & 2627 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) { 2628 rc = krb5_authenticate(work, req, rsp); 2629 if (rc) 2630 goto out_err; 2631 2632 if (!ksmbd_conn_need_reconnect(conn)) { 2633 ksmbd_conn_set_good(conn); 2634 sess->state = SMB2_SESSION_VALID; 2635 } 2636 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) { 2637 if (negblob->MessageType == NtLmNegotiate) { 2638 rc = ntlm_negotiate(work, negblob, negblob_len, rsp); 2639 if (rc) 2640 goto out_err; 2641 rsp->hdr.Status = 2642 STATUS_MORE_PROCESSING_REQUIRED; 2643 } else if (negblob->MessageType == NtLmAuthenticate) { 2644 rc = ntlm_authenticate(work, req, rsp); 2645 if (rc) 2646 goto out_err; 2647 2648 if (!ksmbd_conn_need_reconnect(conn)) { 2649 ksmbd_conn_set_good(conn); 2650 sess->state = SMB2_SESSION_VALID; 2651 } 2652 if (conn->binding) { 2653 struct preauth_session *preauth_sess; 2654 2655 preauth_sess = 2656 ksmbd_preauth_session_lookup(conn, sess->id); 2657 if (preauth_sess) { 2658 list_del(&preauth_sess->preauth_entry); 2659 kfree_sensitive(preauth_sess); 2660 } 2661 } 2662 } else { 2663 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n", 2664 le32_to_cpu(negblob->MessageType)); 2665 rc = -EINVAL; 2666 } 2667 } else { 2668 /* TODO: need one more negotiation */ 2669 pr_err("Not support the preferred authentication\n"); 2670 rc = -EINVAL; 2671 } 2672 } else { 2673 pr_err("Not support authentication\n"); 2674 rc = -EINVAL; 2675 } 2676 2677 out_err: 2678 if (rc == -EINVAL) 2679 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 2680 else if (rc == -ENOENT) 2681 rsp->hdr.Status = STATUS_USER_SESSION_DELETED; 2682 else if (rc == -EACCES) 2683 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED; 2684 else if (rc == -EFAULT) 2685 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED; 2686 else if (rc == -ENOMEM || rc == -ENOSPC) 2687 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 2688 else if (rc == -EOPNOTSUPP) 2689 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 2690 else if (rc == -EKEYREJECTED) 2691 rsp->hdr.Status = STATUS_ACCESS_DENIED; 2692 else if (rc) 2693 rsp->hdr.Status = STATUS_LOGON_FAILURE; 2694 if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED || 2695 (rsp->hdr.Status == STATUS_INVALID_PARAMETER && 2696 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) && 2697 (req->hdr.Flags & SMB2_FLAGS_SIGNED)) 2698 rsp->hdr.Flags |= SMB2_FLAGS_SIGNED; 2699 2700 if (conn->mechToken) { 2701 kfree(conn->mechToken); 2702 conn->mechToken = NULL; 2703 } 2704 2705 if (rc < 0) { 2706 if (sess && conn->dialect == SMB311_PROT_ID && 2707 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) { 2708 struct preauth_session *preauth_sess; 2709 2710 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id); 2711 if (preauth_sess) { 2712 list_del(&preauth_sess->preauth_entry); 2713 kfree_sensitive(preauth_sess); 2714 } 2715 } 2716 2717 /* 2718 * SecurityBufferOffset should be set to zero 2719 * in session setup error response. 2720 */ 2721 rsp->SecurityBufferOffset = 0; 2722 2723 if (sess) { 2724 bool try_delay = false; 2725 2726 /* 2727 * To avoid dictionary attacks (repeated session setups rapidly sent) to 2728 * connect to server, ksmbd make a delay of a 5 seconds on session setup 2729 * failure to make it harder to send enough random connection requests 2730 * to break into a server. 2731 */ 2732 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION) 2733 try_delay = true; 2734 2735 /* 2736 * For binding requests, session belongs to another 2737 * connection. Do not expire it. 2738 */ 2739 if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) { 2740 sess->last_active = jiffies; 2741 sess->kerberos_expiry = 0; 2742 sess->state = SMB2_SESSION_EXPIRED; 2743 } 2744 /* 2745 * Keep the binding session reference until the response is 2746 * signed and sent. Error responses for a signed binding 2747 * request are signed with the existing session signing key. 2748 */ 2749 if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) || 2750 work->sess != sess) { 2751 ksmbd_user_session_put(sess); 2752 work->sess = NULL; 2753 } 2754 if (try_delay) { 2755 ksmbd_conn_set_need_reconnect(conn); 2756 ssleep(5); 2757 ksmbd_conn_set_need_setup(conn); 2758 } 2759 } 2760 smb2_set_err_rsp(work); 2761 conn->binding = false; 2762 } else { 2763 unsigned int iov_len; 2764 2765 if (rsp->SecurityBufferLength) 2766 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) + 2767 le16_to_cpu(rsp->SecurityBufferLength); 2768 else 2769 iov_len = sizeof(struct smb2_sess_setup_rsp); 2770 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len); 2771 if (rc) 2772 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 2773 } 2774 2775 ksmbd_conn_unlock(conn); 2776 return rc; 2777 } 2778 2779 /** 2780 * smb2_tree_connect() - handler for smb2 tree connect command 2781 * @work: smb work containing smb request buffer 2782 * 2783 * Return: 0 on success, otherwise error 2784 */ 2785 int smb2_tree_connect(struct ksmbd_work *work) 2786 { 2787 struct ksmbd_conn *conn = work->conn; 2788 struct smb2_tree_connect_req *req; 2789 struct smb2_tree_connect_rsp *rsp; 2790 struct ksmbd_session *sess = work->sess; 2791 char *treename = NULL, *name = NULL; 2792 struct ksmbd_tree_conn_status status; 2793 struct ksmbd_share_config *share = NULL; 2794 int rc = -EINVAL; 2795 2796 ksmbd_debug(SMB, "Received smb2 tree connect request\n"); 2797 2798 WORK_BUFFERS(work, req, rsp); 2799 2800 treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset), 2801 le16_to_cpu(req->PathLength), true, 2802 conn->local_nls); 2803 if (IS_ERR(treename)) { 2804 pr_err("treename is NULL\n"); 2805 status.ret = KSMBD_TREE_CONN_STATUS_ERROR; 2806 goto out_err1; 2807 } 2808 2809 name = ksmbd_extract_sharename(conn->um, treename); 2810 if (IS_ERR(name)) { 2811 status.ret = KSMBD_TREE_CONN_STATUS_ERROR; 2812 goto out_err1; 2813 } 2814 2815 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n", 2816 name, treename); 2817 2818 status = ksmbd_tree_conn_connect(work, name); 2819 if (status.ret == KSMBD_TREE_CONN_STATUS_OK) { 2820 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id); 2821 share = status.tree_conn->share_conf; 2822 2823 /* A share that requires encryption needs a negotiated SMB3 cipher. */ 2824 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_ENCRYPT_DATA) && 2825 !smb3_encryption_negotiated(conn)) { 2826 ksmbd_tree_conn_disconnect(sess, status.tree_conn); 2827 status.tree_conn = NULL; 2828 share = NULL; 2829 status.ret = KSMBD_TREE_CONN_STATUS_ERROR; 2830 goto out_err1; 2831 } 2832 } else 2833 goto out_err1; 2834 2835 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) { 2836 ksmbd_debug(SMB, "IPC share path request\n"); 2837 rsp->ShareType = SMB2_SHARE_TYPE_PIPE; 2838 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE | 2839 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE | 2840 FILE_DELETE_LE | FILE_READ_CONTROL_LE | 2841 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE | 2842 FILE_SYNCHRONIZE_LE; 2843 } else { 2844 rsp->ShareType = SMB2_SHARE_TYPE_DISK; 2845 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE | 2846 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE; 2847 if (test_tree_conn_flag(status.tree_conn, 2848 KSMBD_TREE_CONN_FLAG_WRITABLE)) { 2849 rsp->MaximalAccess |= FILE_WRITE_DATA_LE | 2850 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE | 2851 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE | 2852 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE | 2853 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE | 2854 FILE_SYNCHRONIZE_LE; 2855 } 2856 } 2857 2858 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess); 2859 if (conn->posix_ext_supported) 2860 status.tree_conn->posix_extensions = true; 2861 2862 down_write(&sess->tree_conns_lock); 2863 status.tree_conn->t_state = TREE_CONNECTED; 2864 up_write(&sess->tree_conns_lock); 2865 rsp->StructureSize = cpu_to_le16(16); 2866 out_err1: 2867 /* 2868 * A configured CA share is not continuously available until persistent 2869 * open recovery, ownership fencing, and failover are implemented. 2870 */ 2871 rsp->Capabilities = 0; 2872 rsp->Reserved = 0; 2873 /* default manual caching */ 2874 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING; 2875 /* Tell the client that READ requests may request compressed responses. */ 2876 if (conn->dialect == SMB311_PROT_ID && 2877 conn->compress_algorithm != SMB3_COMPRESS_NONE) 2878 rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA); 2879 if (share && test_share_config_flag(share, 2880 KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) 2881 rsp->ShareFlags |= 2882 cpu_to_le32(SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM); 2883 if (share && test_share_config_flag(share, 2884 KSMBD_SHARE_FLAG_ENCRYPT_DATA)) 2885 rsp->ShareFlags |= 2886 cpu_to_le32(SMB2_SHAREFLAG_ENCRYPT_DATA); 2887 2888 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp)); 2889 if (rc) { 2890 if (status.ret == KSMBD_TREE_CONN_STATUS_OK) { 2891 down_write(&sess->tree_conns_lock); 2892 status.tree_conn->t_state = TREE_DISCONNECTED; 2893 up_write(&sess->tree_conns_lock); 2894 ksmbd_tree_conn_disconnect(sess, status.tree_conn); 2895 status.tree_conn = NULL; 2896 } 2897 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM; 2898 } 2899 2900 if (!IS_ERR(treename)) 2901 kfree(treename); 2902 if (!IS_ERR(name)) 2903 kfree(name); 2904 2905 switch (status.ret) { 2906 case KSMBD_TREE_CONN_STATUS_OK: 2907 rsp->hdr.Status = STATUS_SUCCESS; 2908 rc = 0; 2909 break; 2910 case -ESTALE: 2911 case -ENOENT: 2912 case KSMBD_TREE_CONN_STATUS_NO_SHARE: 2913 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME; 2914 break; 2915 case -ENOMEM: 2916 case KSMBD_TREE_CONN_STATUS_NOMEM: 2917 rsp->hdr.Status = STATUS_NO_MEMORY; 2918 break; 2919 case KSMBD_TREE_CONN_STATUS_ERROR: 2920 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS: 2921 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS: 2922 rsp->hdr.Status = STATUS_ACCESS_DENIED; 2923 break; 2924 case -EINVAL: 2925 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 2926 break; 2927 default: 2928 rsp->hdr.Status = STATUS_ACCESS_DENIED; 2929 } 2930 2931 if (status.ret != KSMBD_TREE_CONN_STATUS_OK) 2932 smb2_set_err_rsp(work); 2933 2934 return rc; 2935 } 2936 2937 /** 2938 * smb2_create_open_flags() - convert smb open flags to unix open flags 2939 * @file_present: is file already present 2940 * @access: file access flags 2941 * @disposition: file disposition flags 2942 * @may_flags: set with MAY_ flags 2943 * @coptions: file creation options 2944 * @mode: file mode 2945 * 2946 * Return: file open flags 2947 */ 2948 static int smb2_create_open_flags(bool file_present, __le32 access, 2949 __le32 disposition, 2950 int *may_flags, 2951 __le32 coptions, 2952 umode_t mode) 2953 { 2954 int oflags = O_NONBLOCK | O_LARGEFILE; 2955 2956 if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) { 2957 access &= ~FILE_WRITE_DESIRE_ACCESS_LE; 2958 ksmbd_debug(SMB, "Discard write access to a directory\n"); 2959 } 2960 2961 if (access & FILE_READ_DESIRED_ACCESS_LE && 2962 access & FILE_WRITE_DESIRE_ACCESS_LE) { 2963 oflags |= O_RDWR; 2964 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE; 2965 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) { 2966 oflags |= O_WRONLY; 2967 *may_flags = MAY_OPEN | MAY_WRITE; 2968 } else { 2969 oflags |= O_RDONLY; 2970 *may_flags = MAY_OPEN | MAY_READ; 2971 } 2972 2973 if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode)) 2974 oflags |= O_PATH; 2975 2976 if (file_present) { 2977 switch (disposition & FILE_CREATE_MASK_LE) { 2978 case FILE_OPEN_LE: 2979 case FILE_CREATE_LE: 2980 break; 2981 case FILE_SUPERSEDE_LE: 2982 case FILE_OVERWRITE_LE: 2983 case FILE_OVERWRITE_IF_LE: 2984 oflags |= O_TRUNC; 2985 break; 2986 default: 2987 break; 2988 } 2989 } else { 2990 switch (disposition & FILE_CREATE_MASK_LE) { 2991 case FILE_SUPERSEDE_LE: 2992 case FILE_CREATE_LE: 2993 case FILE_OPEN_IF_LE: 2994 case FILE_OVERWRITE_IF_LE: 2995 oflags |= O_CREAT; 2996 break; 2997 case FILE_OPEN_LE: 2998 case FILE_OVERWRITE_LE: 2999 oflags &= ~O_CREAT; 3000 break; 3001 default: 3002 break; 3003 } 3004 } 3005 3006 return oflags; 3007 } 3008 3009 /** 3010 * smb2_tree_disconnect() - handler for smb tree connect request 3011 * @work: smb work containing request buffer 3012 * 3013 * Return: 0 on success, otherwise error 3014 */ 3015 int smb2_tree_disconnect(struct ksmbd_work *work) 3016 { 3017 struct smb2_tree_disconnect_rsp *rsp; 3018 struct smb2_tree_disconnect_req *req; 3019 struct ksmbd_session *sess = work->sess; 3020 struct ksmbd_tree_connect *tcon = work->tcon; 3021 int err; 3022 3023 ksmbd_debug(SMB, "Received smb2 tree disconnect request\n"); 3024 3025 WORK_BUFFERS(work, req, rsp); 3026 3027 if (!tcon) { 3028 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId); 3029 3030 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED; 3031 err = -ENOENT; 3032 goto err_out; 3033 } 3034 3035 ksmbd_close_tree_conn_fds(work); 3036 3037 down_write(&sess->tree_conns_lock); 3038 if (tcon->t_state == TREE_DISCONNECTED) { 3039 up_write(&sess->tree_conns_lock); 3040 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED; 3041 err = -ENOENT; 3042 goto err_out; 3043 } 3044 3045 tcon->t_state = TREE_DISCONNECTED; 3046 up_write(&sess->tree_conns_lock); 3047 3048 err = ksmbd_tree_conn_disconnect(sess, tcon); 3049 if (err) { 3050 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED; 3051 goto err_out; 3052 } 3053 3054 rsp->StructureSize = cpu_to_le16(4); 3055 err = ksmbd_iov_pin_rsp(work, rsp, 3056 sizeof(struct smb2_tree_disconnect_rsp)); 3057 if (err) { 3058 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 3059 goto err_out; 3060 } 3061 3062 return 0; 3063 3064 err_out: 3065 smb2_set_err_rsp(work); 3066 return err; 3067 3068 } 3069 3070 /** 3071 * smb2_session_logoff() - handler for session log off request 3072 * @work: smb work containing request buffer 3073 * 3074 * Return: 0 on success, otherwise error 3075 */ 3076 int smb2_session_logoff(struct ksmbd_work *work) 3077 { 3078 struct ksmbd_conn *conn = work->conn; 3079 struct ksmbd_session *sess = work->sess; 3080 struct smb2_logoff_req *req; 3081 struct smb2_logoff_rsp *rsp; 3082 int err; 3083 3084 WORK_BUFFERS(work, req, rsp); 3085 3086 ksmbd_debug(SMB, "Received smb2 session logoff request\n"); 3087 3088 ksmbd_conn_lock(conn); 3089 if (!ksmbd_conn_good(conn)) { 3090 ksmbd_conn_unlock(conn); 3091 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED; 3092 smb2_set_err_rsp(work); 3093 return -ENOENT; 3094 } 3095 3096 down_write(&sess->chann_lock); 3097 if (sess->tearing_down) { 3098 up_write(&sess->chann_lock); 3099 ksmbd_conn_unlock(conn); 3100 rsp->hdr.Status = STATUS_USER_SESSION_DELETED; 3101 smb2_set_err_rsp(work); 3102 return -ENOENT; 3103 } 3104 sess->tearing_down = true; 3105 up_write(&sess->chann_lock); 3106 3107 ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT); 3108 ksmbd_conn_unlock(conn); 3109 3110 err = ksmbd_conn_wait_idle_sess(conn, sess); 3111 if (err) { 3112 down_write(&sess->chann_lock); 3113 sess->tearing_down = false; 3114 up_write(&sess->chann_lock); 3115 ksmbd_all_conn_set_status(sess, KSMBD_SESS_GOOD); 3116 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 3117 smb2_set_err_rsp(work); 3118 return err; 3119 } 3120 3121 ksmbd_close_session_fds(work); 3122 3123 if (ksmbd_tree_conn_session_logoff(sess)) { 3124 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId); 3125 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED; 3126 smb2_set_err_rsp(work); 3127 err = -ENOENT; 3128 } else { 3129 err = 0; 3130 } 3131 3132 down_write(&conn->session_lock); 3133 sess->kerberos_expiry = 0; 3134 sess->state = SMB2_SESSION_EXPIRED; 3135 up_write(&conn->session_lock); 3136 3137 ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP); 3138 3139 if (err) 3140 return err; 3141 3142 rsp->StructureSize = cpu_to_le16(4); 3143 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp)); 3144 if (err) { 3145 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 3146 smb2_set_err_rsp(work); 3147 return err; 3148 } 3149 return 0; 3150 } 3151 3152 /** 3153 * create_smb2_pipe() - create IPC pipe 3154 * @work: smb work containing request buffer 3155 * 3156 * Return: 0 on success, otherwise error 3157 */ 3158 static noinline int create_smb2_pipe(struct ksmbd_work *work) 3159 { 3160 struct smb2_create_rsp *rsp; 3161 struct smb2_create_req *req; 3162 int id = -1; 3163 int err; 3164 char *name; 3165 3166 WORK_BUFFERS(work, req, rsp); 3167 3168 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength), 3169 1, work->conn->local_nls); 3170 if (IS_ERR(name)) { 3171 rsp->hdr.Status = STATUS_NO_MEMORY; 3172 err = PTR_ERR(name); 3173 goto out; 3174 } 3175 3176 id = ksmbd_session_rpc_open(work->sess, name); 3177 if (id < 0) { 3178 /* 3179 * mdssvc (Spotlight) is a routine, expected probe from macOS 3180 * that we deliberately don't support -- it's disabled at the 3181 * __rpc_method() level (mgmt/user_session.c), but this 3182 * generic failure log would otherwise still fire on every 3183 * single probe regardless. 3184 */ 3185 if (!(id == -ENOENT && (!strcmp(name, "\\mdssvc") || 3186 !strcmp(name, "mdssvc")))) 3187 pr_err("Unable to open RPC pipe: %d\n", id); 3188 err = id; 3189 goto out; 3190 } 3191 3192 rsp->hdr.Status = STATUS_SUCCESS; 3193 rsp->StructureSize = cpu_to_le16(89); 3194 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE; 3195 rsp->Flags = 0; 3196 rsp->CreateAction = cpu_to_le32(FILE_OPENED); 3197 3198 rsp->CreationTime = cpu_to_le64(0); 3199 rsp->LastAccessTime = cpu_to_le64(0); 3200 rsp->ChangeTime = cpu_to_le64(0); 3201 rsp->AllocationSize = cpu_to_le64(0); 3202 rsp->EndofFile = cpu_to_le64(0); 3203 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE; 3204 rsp->Reserved2 = 0; 3205 rsp->VolatileFileId = id; 3206 rsp->PersistentFileId = 0; 3207 rsp->CreateContextsOffset = 0; 3208 rsp->CreateContextsLength = 0; 3209 3210 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer)); 3211 if (err) 3212 goto out; 3213 3214 kfree(name); 3215 return 0; 3216 3217 out: 3218 switch (err) { 3219 case -EINVAL: 3220 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 3221 break; 3222 case -ENOENT: 3223 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND; 3224 break; 3225 case -ENOSPC: 3226 case -ENOMEM: 3227 rsp->hdr.Status = STATUS_NO_MEMORY; 3228 break; 3229 } 3230 3231 if (id >= 0) 3232 ksmbd_session_rpc_close(work->sess, id); 3233 3234 if (!IS_ERR(name)) 3235 kfree(name); 3236 3237 smb2_set_err_rsp(work); 3238 return err; 3239 } 3240 3241 static bool smb2_is_private_ea(const char *name, size_t name_len) 3242 { 3243 if (name_len == SD_PREFIX_LEN && 3244 !strncasecmp(name, SD_PREFIX, SD_PREFIX_LEN)) 3245 return true; 3246 if (name_len == DOS_ATTRIBUTE_PREFIX_LEN && 3247 !strncasecmp(name, DOS_ATTRIBUTE_PREFIX, 3248 DOS_ATTRIBUTE_PREFIX_LEN)) 3249 return true; 3250 if (name_len >= STREAM_PREFIX_LEN && 3251 !strncasecmp(name, STREAM_PREFIX, STREAM_PREFIX_LEN)) 3252 return true; 3253 3254 return false; 3255 } 3256 3257 /** 3258 * smb2_set_ea() - handler for setting extended attributes using set 3259 * info command 3260 * @eabuf: set info command buffer 3261 * @buf_len: set info command buffer length 3262 * @path: dentry path for get ea 3263 * @get_write: get write access to a mount 3264 * 3265 * Return: 0 on success, otherwise error 3266 */ 3267 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len, 3268 const struct path *path, bool get_write) 3269 { 3270 struct mnt_idmap *idmap = mnt_idmap(path->mnt); 3271 char *attr_name = NULL, *value; 3272 int rc = 0; 3273 unsigned int next = 0; 3274 3275 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 + 3276 le16_to_cpu(eabuf->EaValueLength)) 3277 return -EINVAL; 3278 3279 attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP); 3280 if (!attr_name) 3281 return -ENOMEM; 3282 3283 do { 3284 if (!eabuf->EaNameLength) 3285 goto next; 3286 3287 ksmbd_debug(SMB, 3288 "name : <%s>, name_len : %u, value_len : %u, next : %u\n", 3289 eabuf->name, eabuf->EaNameLength, 3290 le16_to_cpu(eabuf->EaValueLength), 3291 le32_to_cpu(eabuf->NextEntryOffset)); 3292 3293 if (eabuf->EaNameLength > 3294 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) { 3295 rc = -EINVAL; 3296 break; 3297 } 3298 if (smb2_is_private_ea(eabuf->name, eabuf->EaNameLength)) { 3299 rc = -EACCES; 3300 break; 3301 } 3302 3303 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN); 3304 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name, 3305 eabuf->EaNameLength); 3306 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0'; 3307 value = (char *)&eabuf->name + eabuf->EaNameLength + 1; 3308 3309 if (!eabuf->EaValueLength) { 3310 rc = ksmbd_vfs_casexattr_len(idmap, 3311 path->dentry, 3312 attr_name, 3313 XATTR_USER_PREFIX_LEN + 3314 eabuf->EaNameLength); 3315 3316 /* delete the EA only when it exits */ 3317 if (rc > 0) { 3318 rc = ksmbd_vfs_remove_xattr(idmap, 3319 path, 3320 attr_name, 3321 get_write); 3322 3323 if (rc < 0) { 3324 ksmbd_debug(SMB, 3325 "remove xattr failed(%d)\n", 3326 rc); 3327 break; 3328 } 3329 } 3330 3331 /* if the EA doesn't exist, just do nothing. */ 3332 rc = 0; 3333 } else { 3334 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value, 3335 le16_to_cpu(eabuf->EaValueLength), 3336 0, get_write); 3337 if (rc < 0) { 3338 ksmbd_debug(SMB, 3339 "ksmbd_vfs_setxattr is failed(%d)\n", 3340 rc); 3341 break; 3342 } 3343 } 3344 3345 next: 3346 next = le32_to_cpu(eabuf->NextEntryOffset); 3347 if (next == 0 || buf_len < next) 3348 break; 3349 buf_len -= next; 3350 eabuf = (struct smb2_ea_info *)((char *)eabuf + next); 3351 if (buf_len < sizeof(struct smb2_ea_info)) { 3352 rc = -EINVAL; 3353 break; 3354 } 3355 3356 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 + 3357 le16_to_cpu(eabuf->EaValueLength)) { 3358 rc = -EINVAL; 3359 break; 3360 } 3361 } while (next != 0); 3362 3363 kfree(attr_name); 3364 return rc; 3365 } 3366 3367 static noinline int smb2_set_stream_name_xattr(const struct path *path, 3368 struct ksmbd_file *fp, 3369 char *stream_name, int s_type) 3370 { 3371 struct mnt_idmap *idmap = mnt_idmap(path->mnt); 3372 size_t xattr_stream_size; 3373 char *xattr_stream_name; 3374 int rc; 3375 3376 rc = ksmbd_vfs_xattr_stream_name(stream_name, 3377 &xattr_stream_name, 3378 &xattr_stream_size, 3379 s_type); 3380 if (rc) 3381 return rc; 3382 3383 fp->stream.name = xattr_stream_name; 3384 fp->stream.size = xattr_stream_size; 3385 3386 /* Check if there is stream prefix in xattr space */ 3387 rc = ksmbd_vfs_casexattr_len(idmap, 3388 path->dentry, 3389 xattr_stream_name, 3390 xattr_stream_size); 3391 if (rc >= 0) 3392 return 0; 3393 3394 if (fp->cdoption == FILE_OPEN_LE) { 3395 if (!strcmp(stream_name, "AFP_AfpInfo") && 3396 test_share_config_flag(fp->tcon->share_conf, 3397 KSMBD_SHARE_FLAG_TIME_MACHINE)) { 3398 /* 3399 * Synthesize an empty AFP_AfpInfo xattr on first access. 3400 * type=0/creator=0 tells macOS to use the file extension 3401 * for icon and type detection. 3402 * 3403 * Scoped to TIME_MACHINE shares, matching the rest of 3404 * the AAPL series -- conn->is_aapl alone isn't a safe 3405 * gate here, since the pre-existing narrow UniqueId=0 3406 * path can also set it on ordinary, non-Time-Machine 3407 * shares whenever a Mac client happens to negotiate 3408 * AAPL there too. 3409 */ 3410 static const u8 afpinfo_empty[60] = { 3411 0x00, 0x05, 0x16, 0x07, /* magic 0x00051607 BE */ 3412 0x00, 0x02, 0x00, 0x00, /* version 0x00020000 BE */ 3413 }; 3414 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, 3415 (void *)afpinfo_empty, 3416 sizeof(afpinfo_empty), 0, false); 3417 return rc < 0 ? rc : 0; 3418 } 3419 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc); 3420 return -EBADF; 3421 } 3422 3423 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false); 3424 if (rc < 0) 3425 pr_err("Failed to store XATTR stream name :%d\n", rc); 3426 return 0; 3427 } 3428 3429 /* 3430 * fp->stream.size is the byte length of the mangled xattr *name* 3431 * (used as attr_name_len when looking the xattr up), not the size of 3432 * the xattr's value. Reporting it as EndOfFile/AllocationSize for a 3433 * stream handle is wrong -- query the xattr's actual value length 3434 * instead. 3435 */ 3436 static loff_t ksmbd_stream_eof(struct ksmbd_file *fp) 3437 { 3438 ssize_t slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp), 3439 fp->filp->f_path.dentry, 3440 fp->stream.name, 3441 fp->stream.size); 3442 return slen < 0 ? 0 : (loff_t)slen; 3443 } 3444 3445 static int smb2_remove_smb_xattrs(const struct path *path) 3446 { 3447 struct mnt_idmap *idmap = mnt_idmap(path->mnt); 3448 char *name, *xattr_list = NULL; 3449 ssize_t xattr_list_len; 3450 int err = 0; 3451 3452 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list); 3453 if (xattr_list_len < 0) { 3454 goto out; 3455 } else if (!xattr_list_len) { 3456 ksmbd_debug(SMB, "empty xattr in the file\n"); 3457 goto out; 3458 } 3459 3460 for (name = xattr_list; name - xattr_list < xattr_list_len; 3461 name += strlen(name) + 1) { 3462 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name)); 3463 3464 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) && 3465 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, 3466 STREAM_PREFIX_LEN)) { 3467 err = ksmbd_vfs_remove_xattr(idmap, path, 3468 name, true); 3469 if (err) 3470 ksmbd_debug(SMB, "remove xattr failed : %s\n", 3471 name); 3472 } 3473 } 3474 out: 3475 kvfree(xattr_list); 3476 return err; 3477 } 3478 3479 static int smb2_create_truncate(const struct path *path) 3480 { 3481 int rc = vfs_truncate(path, 0); 3482 3483 if (rc) { 3484 pr_err("vfs_truncate failed, rc %d\n", rc); 3485 return rc; 3486 } 3487 3488 rc = smb2_remove_smb_xattrs(path); 3489 if (rc == -EOPNOTSUPP) 3490 rc = 0; 3491 if (rc) 3492 ksmbd_debug(SMB, 3493 "ksmbd_truncate_stream_name_xattr failed, rc %d\n", 3494 rc); 3495 return rc; 3496 } 3497 3498 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path, 3499 struct ksmbd_file *fp) 3500 { 3501 struct xattr_dos_attrib da = {0}; 3502 int rc; 3503 3504 if (!test_share_config_flag(tcon->share_conf, 3505 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) 3506 return; 3507 3508 da.version = 4; 3509 da.attr = le32_to_cpu(fp->f_ci->m_fattr); 3510 da.itime = da.create_time = fp->create_time; 3511 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME | 3512 XATTR_DOSINFO_ITIME; 3513 3514 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true); 3515 if (rc) 3516 ksmbd_debug(SMB, "failed to store file attribute into xattr\n"); 3517 } 3518 3519 static bool smb2_parent_compressed(struct ksmbd_tree_connect *tcon, 3520 const struct path *path) 3521 { 3522 struct dentry *parent = dget_parent(path->dentry); 3523 struct file_kattr fa = { .flags_valid = true }; 3524 struct xattr_dos_attrib da; 3525 bool compressed = false; 3526 int rc; 3527 3528 rc = vfs_fileattr_get(parent, &fa); 3529 if (!rc && fa.flags & FS_COMPR_FL) { 3530 compressed = true; 3531 goto out; 3532 } 3533 3534 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), parent, &da); 3535 if (rc > 0 && da.attr & FILE_ATTRIBUTE_COMPRESSED) 3536 compressed = true; 3537 3538 out: 3539 dput(parent); 3540 return compressed; 3541 } 3542 3543 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon, 3544 const struct path *path, struct ksmbd_file *fp) 3545 { 3546 struct xattr_dos_attrib da = {}; 3547 bool store_dos_attrs = test_share_config_flag(tcon->share_conf, 3548 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS); 3549 int rc; 3550 3551 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE); 3552 3553 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */ 3554 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), 3555 path->dentry, &da); 3556 if (rc > 0) { 3557 if (store_dos_attrs) { 3558 fp->f_ci->m_fattr = cpu_to_le32(da.attr); 3559 fp->create_time = da.create_time; 3560 fp->itime = da.itime; 3561 } else { 3562 fp->f_ci->m_fattr &= 3563 ~(FILE_ATTRIBUTE_COMPRESSED_LE | 3564 FILE_ATTRIBUTE_SPARSE_FILE_LE); 3565 fp->f_ci->m_fattr |= 3566 cpu_to_le32(da.attr & 3567 (FILE_ATTRIBUTE_COMPRESSED | 3568 FILE_ATTRIBUTE_SPARSE_FILE)); 3569 } 3570 } 3571 } 3572 3573 static int smb2_creat(struct ksmbd_work *work, 3574 struct path *path, char *name, int open_flags, 3575 umode_t posix_mode, bool is_dir) 3576 { 3577 struct ksmbd_tree_connect *tcon = work->tcon; 3578 struct ksmbd_share_config *share = tcon->share_conf; 3579 umode_t mode; 3580 int rc; 3581 3582 if (!(open_flags & O_CREAT)) 3583 return -EBADF; 3584 3585 ksmbd_debug(SMB, "file does not exist, so creating\n"); 3586 if (is_dir == true) { 3587 ksmbd_debug(SMB, "creating directory\n"); 3588 3589 mode = share_config_directory_mode(share, posix_mode); 3590 rc = ksmbd_vfs_mkdir(work, name, mode); 3591 if (rc) 3592 return rc; 3593 } else { 3594 ksmbd_debug(SMB, "creating regular file\n"); 3595 3596 mode = share_config_create_mode(share, posix_mode); 3597 rc = ksmbd_vfs_create(work, name, mode); 3598 if (rc) 3599 return rc; 3600 } 3601 3602 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0); 3603 if (rc) { 3604 pr_err("cannot get linux path (%s), err = %d\n", 3605 name, rc); 3606 return rc; 3607 } 3608 return 0; 3609 } 3610 3611 static int smb2_create_sd_buffer(struct ksmbd_work *work, 3612 struct smb2_create_req *req, 3613 const struct path *path) 3614 { 3615 struct create_context *context; 3616 struct create_sd_buf_req *sd_buf; 3617 3618 if (!req->CreateContextsOffset) 3619 return -ENOENT; 3620 3621 /* Parse SD BUFFER create contexts */ 3622 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4); 3623 if (!context) 3624 return -ENOENT; 3625 else if (IS_ERR(context)) 3626 return PTR_ERR(context); 3627 3628 ksmbd_debug(SMB, 3629 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n"); 3630 sd_buf = (struct create_sd_buf_req *)context; 3631 if (le16_to_cpu(context->DataOffset) + 3632 le32_to_cpu(context->DataLength) < 3633 sizeof(struct create_sd_buf_req)) 3634 return -EINVAL; 3635 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd, 3636 le32_to_cpu(sd_buf->ccontext.DataLength), true, false); 3637 } 3638 3639 static void ksmbd_acls_fattr(struct smb_fattr *fattr, 3640 struct mnt_idmap *idmap, 3641 struct inode *inode) 3642 { 3643 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode); 3644 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode); 3645 3646 fattr->cf_uid = vfsuid_into_kuid(vfsuid); 3647 fattr->cf_gid = vfsgid_into_kgid(vfsgid); 3648 fattr->cf_mode = inode->i_mode; 3649 fattr->cf_acls = NULL; 3650 fattr->cf_dacls = NULL; 3651 3652 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) { 3653 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS); 3654 if (S_ISDIR(inode->i_mode)) 3655 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT); 3656 } 3657 } 3658 3659 enum { 3660 DURABLE_RECONN_V2 = 1, 3661 DURABLE_RECONN, 3662 DURABLE_REQ_V2, 3663 DURABLE_REQ, 3664 }; 3665 3666 struct durable_info { 3667 struct ksmbd_file *fp; 3668 unsigned short int type; 3669 bool persistent; 3670 bool reconnected; 3671 bool replay; 3672 bool replay_consumed; 3673 bool app_instance_id; 3674 bool app_instance_version_valid; 3675 unsigned int timeout; 3676 char *CreateGuid; 3677 char AppInstanceId[SMB2_CREATE_GUID_SIZE]; 3678 u64 app_instance_version_high; 3679 u64 app_instance_version_low; 3680 }; 3681 3682 static int smb2_check_durable_replay(struct ksmbd_work *work, 3683 struct ksmbd_file *fp, 3684 struct lease_ctx_info *lc, 3685 bool persistent) 3686 { 3687 struct oplock_info *opinfo; 3688 int ret = 0; 3689 3690 if (!fp->is_durable && !fp->is_persistent) 3691 return -EACCES; 3692 3693 if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false) 3694 return -EACCES; 3695 3696 if (fp->is_persistent && !persistent) 3697 return -EINVAL; 3698 3699 opinfo = opinfo_get(fp); 3700 if (!opinfo) 3701 return 0; 3702 3703 if (opinfo->sess && opinfo->sess->id != work->sess->id) { 3704 ret = -ENOEXEC; 3705 goto out; 3706 } 3707 3708 if (opinfo->is_lease) { 3709 if (!lc || 3710 memcmp(opinfo->o_lease->lease_key, lc->lease_key, 3711 SMB2_LEASE_KEY_SIZE)) { 3712 ret = -EACCES; 3713 goto out; 3714 } 3715 } else { 3716 if (lc) { 3717 ret = -EACCES; 3718 goto out; 3719 } 3720 3721 if (fp->is_durable && opinfo->level != SMB2_OPLOCK_LEVEL_BATCH) 3722 ret = -EACCES; 3723 } 3724 out: 3725 opinfo_put(opinfo); 3726 return ret; 3727 } 3728 3729 static bool smb2_durable_replay_consumed(struct ksmbd_file *fp) 3730 { 3731 bool consumed; 3732 3733 spin_lock(&fp->f_lock); 3734 consumed = fp->durable_replay_consumed; 3735 spin_unlock(&fp->f_lock); 3736 3737 return consumed; 3738 } 3739 3740 static void smb2_mark_durable_replay_consumed(struct ksmbd_file *fp) 3741 { 3742 spin_lock(&fp->f_lock); 3743 fp->durable_replay_consumed = true; 3744 spin_unlock(&fp->f_lock); 3745 } 3746 3747 static bool smb2_durable_replay_differs(struct ksmbd_file *fp, 3748 struct smb2_create_req *req) 3749 { 3750 return fp->cdoption != req->CreateDisposition || 3751 fp->create_file_attributes != req->FileAttributes; 3752 } 3753 3754 static int parse_durable_handle_context(struct ksmbd_work *work, 3755 struct smb2_create_req *req, 3756 struct lease_ctx_info *lc, 3757 struct durable_info *dh_info) 3758 { 3759 struct ksmbd_conn *conn = work->conn; 3760 struct create_context *context; 3761 int dh_idx, err = 0; 3762 u64 persistent_id = 0; 3763 int req_op_level; 3764 static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"}; 3765 3766 req_op_level = req->RequestedOplockLevel; 3767 for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr); 3768 dh_idx++) { 3769 context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4); 3770 if (IS_ERR(context)) { 3771 err = PTR_ERR(context); 3772 goto out; 3773 } 3774 if (!context) 3775 continue; 3776 3777 switch (dh_idx) { 3778 case DURABLE_RECONN_V2: 3779 { 3780 struct create_durable_handle_reconnect_v2 *recon_v2; 3781 u32 flags; 3782 3783 if (dh_info->type == DURABLE_RECONN || 3784 dh_info->type == DURABLE_REQ_V2) { 3785 err = -EINVAL; 3786 goto out; 3787 } 3788 3789 if (le32_to_cpu(context->DataLength) < 3790 sizeof(recon_v2->dcontext)) { 3791 err = -EINVAL; 3792 goto out; 3793 } 3794 3795 recon_v2 = (struct create_durable_handle_reconnect_v2 *)context; 3796 flags = le32_to_cpu(recon_v2->dcontext.Flags); 3797 if (flags & ~SMB2_DHANDLE_FLAG_PERSISTENT) { 3798 err = -EINVAL; 3799 goto out; 3800 } 3801 dh_info->persistent = flags & SMB2_DHANDLE_FLAG_PERSISTENT; 3802 persistent_id = recon_v2->dcontext.Fid.PersistentFileId; 3803 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id); 3804 if (!dh_info->fp) { 3805 ksmbd_debug(SMB, "Failed to get durable handle state\n"); 3806 err = -EBADF; 3807 goto out; 3808 } 3809 3810 /* A zero VolatileFileId means that the client did not specify it. */ 3811 if (recon_v2->dcontext.Fid.VolatileFileId && 3812 dh_info->fp->durable_volatile_id != 3813 recon_v2->dcontext.Fid.VolatileFileId) { 3814 err = -EBADF; 3815 ksmbd_put_durable_fd(dh_info->fp); 3816 goto out; 3817 } 3818 3819 if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid, 3820 SMB2_CREATE_GUID_SIZE)) { 3821 err = -EBADF; 3822 ksmbd_put_durable_fd(dh_info->fp); 3823 goto out; 3824 } 3825 3826 /* A persistent reconnect must match the original open type. */ 3827 if (dh_info->fp->is_persistent != dh_info->persistent) { 3828 err = dh_info->persistent ? -EINVAL : -EBADF; 3829 ksmbd_put_durable_fd(dh_info->fp); 3830 goto out; 3831 } 3832 3833 dh_info->type = dh_idx; 3834 dh_info->reconnected = true; 3835 ksmbd_debug(SMB, 3836 "reconnect v2 Persistent-id from reconnect = %llu\n", 3837 persistent_id); 3838 break; 3839 } 3840 case DURABLE_RECONN: 3841 { 3842 create_durable_reconn_t *recon; 3843 3844 if (dh_info->type == DURABLE_RECONN_V2 || 3845 dh_info->type == DURABLE_REQ_V2) { 3846 err = -EINVAL; 3847 goto out; 3848 } 3849 3850 if (le32_to_cpu(context->DataLength) < 3851 sizeof(recon->Data)) { 3852 err = -EINVAL; 3853 goto out; 3854 } 3855 3856 recon = (create_durable_reconn_t *)context; 3857 persistent_id = recon->Data.Fid.PersistentFileId; 3858 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id); 3859 if (!dh_info->fp) { 3860 ksmbd_debug(SMB, "Failed to get durable handle state\n"); 3861 err = -EBADF; 3862 goto out; 3863 } 3864 3865 /* A zero VolatileFileId means that the client did not specify it. */ 3866 if (recon->Data.Fid.VolatileFileId && 3867 dh_info->fp->durable_volatile_id != 3868 recon->Data.Fid.VolatileFileId) { 3869 err = -EBADF; 3870 ksmbd_put_durable_fd(dh_info->fp); 3871 goto out; 3872 } 3873 3874 dh_info->type = dh_idx; 3875 dh_info->reconnected = true; 3876 ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n", 3877 persistent_id); 3878 break; 3879 } 3880 case DURABLE_REQ_V2: 3881 { 3882 struct create_durable_req_v2 *durable_v2_blob; 3883 3884 if (dh_info->type == DURABLE_RECONN || 3885 dh_info->type == DURABLE_RECONN_V2) { 3886 err = -EINVAL; 3887 goto out; 3888 } 3889 3890 if (le32_to_cpu(context->DataLength) < 3891 sizeof(durable_v2_blob->dcontext)) { 3892 err = -EINVAL; 3893 goto out; 3894 } 3895 3896 durable_v2_blob = 3897 (struct create_durable_req_v2 *)context; 3898 if (le32_to_cpu(durable_v2_blob->dcontext.Flags) & 3899 ~SMB2_DHANDLE_FLAG_PERSISTENT) { 3900 err = -EINVAL; 3901 goto out; 3902 } 3903 ksmbd_debug(SMB, "Request for durable v2 open\n"); 3904 dh_info->CreateGuid = durable_v2_blob->dcontext.CreateGuid; 3905 dh_info->persistent = 3906 le32_to_cpu(durable_v2_blob->dcontext.Flags) & 3907 SMB2_DHANDLE_FLAG_PERSISTENT; 3908 dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid); 3909 if (dh_info->fp) { 3910 if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid, 3911 SMB2_CLIENT_GUID_SIZE)) { 3912 if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) { 3913 err = -ENOEXEC; 3914 ksmbd_put_durable_fd(dh_info->fp); 3915 goto out; 3916 } 3917 3918 if (dh_info->fp->f_state == FP_NEW) { 3919 /* Original CREATE is still pending. */ 3920 ksmbd_put_durable_fd(dh_info->fp); 3921 err = -EAGAIN; 3922 goto out; 3923 } 3924 3925 if (!dh_info->fp->is_durable && 3926 !dh_info->fp->is_persistent) { 3927 /* 3928 * A DurableHandleReqV2 CREATE can complete 3929 * without granting durability (for example, if 3930 * it requested no oplock). Its CreateGuid still 3931 * identifies a completed CREATE for replay. 3932 */ 3933 if (dh_info->fp->conn && 3934 ksmbd_vfs_compare_durable_owner( 3935 dh_info->fp, work->sess->user)) { 3936 if (smb2_durable_replay_consumed( 3937 dh_info->fp)) { 3938 ksmbd_put_durable_fd(dh_info->fp); 3939 dh_info->fp = NULL; 3940 dh_info->type = dh_idx; 3941 dh_info->replay_consumed = true; 3942 break; 3943 } 3944 if (smb2_durable_replay_differs( 3945 dh_info->fp, req)) 3946 smb2_mark_durable_replay_consumed( 3947 dh_info->fp); 3948 dh_info->replay = true; 3949 dh_info->type = dh_idx; 3950 goto out; 3951 } 3952 ksmbd_put_durable_fd(dh_info->fp); 3953 err = -EACCES; 3954 goto out; 3955 } 3956 3957 if (dh_info->fp->conn && 3958 smb2_durable_replay_consumed(dh_info->fp)) { 3959 ksmbd_put_durable_fd(dh_info->fp); 3960 dh_info->fp = NULL; 3961 dh_info->type = dh_idx; 3962 dh_info->replay_consumed = true; 3963 break; 3964 } 3965 3966 err = smb2_check_durable_replay(work, 3967 dh_info->fp, 3968 lc, 3969 dh_info->persistent); 3970 if (err) { 3971 ksmbd_put_durable_fd(dh_info->fp); 3972 goto out; 3973 } 3974 3975 if (dh_info->fp->conn) { 3976 if (smb2_durable_replay_differs(dh_info->fp, 3977 req)) 3978 smb2_mark_durable_replay_consumed( 3979 dh_info->fp); 3980 dh_info->replay = true; 3981 } else { 3982 dh_info->reconnected = true; 3983 } 3984 dh_info->type = dh_idx; 3985 goto out; 3986 } 3987 ksmbd_put_durable_fd(dh_info->fp); 3988 dh_info->fp = NULL; 3989 } 3990 3991 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) || 3992 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) { 3993 dh_info->timeout = 3994 le32_to_cpu(durable_v2_blob->dcontext.Timeout); 3995 dh_info->type = dh_idx; 3996 } 3997 break; 3998 } 3999 case DURABLE_REQ: 4000 if (dh_info->type == DURABLE_RECONN) 4001 goto out; 4002 if (dh_info->type == DURABLE_RECONN_V2 || 4003 dh_info->type == DURABLE_REQ_V2) { 4004 err = -EINVAL; 4005 goto out; 4006 } 4007 4008 if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) || 4009 req_op_level == SMB2_OPLOCK_LEVEL_BATCH) { 4010 ksmbd_debug(SMB, "Request for durable open\n"); 4011 dh_info->type = dh_idx; 4012 } 4013 } 4014 } 4015 4016 out: 4017 return err; 4018 } 4019 4020 static int parse_app_instance_id(struct smb2_create_req *req, 4021 struct durable_info *dh_info) 4022 { 4023 struct create_context *context; 4024 char *data; 4025 4026 context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID, 4027 SMB2_CREATE_GUID_SIZE); 4028 if (IS_ERR(context)) 4029 return PTR_ERR(context); 4030 if (!context) 4031 return 0; 4032 4033 if (le32_to_cpu(context->DataLength) < 20) 4034 return -EINVAL; 4035 4036 data = (char *)context + le16_to_cpu(context->DataOffset); 4037 if (data[0] != 20 || data[1]) 4038 return -EINVAL; 4039 4040 memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE); 4041 dh_info->app_instance_id = true; 4042 return 0; 4043 } 4044 4045 static int parse_app_instance_version(struct smb2_create_req *req, 4046 struct durable_info *dh_info) 4047 { 4048 struct create_context *context; 4049 char *data; 4050 4051 context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_VERSION, 4052 SMB2_CREATE_GUID_SIZE); 4053 if (IS_ERR(context)) 4054 return PTR_ERR(context); 4055 if (!context) 4056 return 0; 4057 4058 if (le32_to_cpu(context->DataLength) < 24) 4059 return -EINVAL; 4060 4061 data = (char *)context + le16_to_cpu(context->DataOffset); 4062 if (get_unaligned_le16(data) != 24 || 4063 get_unaligned_le16(data + 2) != 0) 4064 return -EINVAL; 4065 4066 dh_info->app_instance_version_high = get_unaligned_le64(data + 8); 4067 dh_info->app_instance_version_low = get_unaligned_le64(data + 16); 4068 dh_info->app_instance_version_valid = true; 4069 return 0; 4070 } 4071 4072 static int smb2_handle_app_instance_id(struct smb2_create_rsp *rsp, 4073 struct durable_info *dh_info) 4074 { 4075 struct ksmbd_file *old_fp; 4076 bool reject = false; 4077 4078 if (!dh_info->app_instance_id) 4079 return 0; 4080 4081 old_fp = ksmbd_lookup_fd_app_instance_id(dh_info->AppInstanceId); 4082 if (!old_fp) 4083 return 0; 4084 4085 if (dh_info->app_instance_version_valid) { 4086 if (old_fp->app_instance_version_valid && 4087 (dh_info->app_instance_version_high < 4088 old_fp->app_instance_version_high || 4089 (dh_info->app_instance_version_high == 4090 old_fp->app_instance_version_high && 4091 dh_info->app_instance_version_low <= 4092 old_fp->app_instance_version_low))) 4093 reject = true; 4094 } else if (old_fp->app_instance_version_valid) { 4095 reject = true; 4096 } 4097 4098 ksmbd_put_durable_fd(old_fp); 4099 if (reject) { 4100 rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED; 4101 return -EIO; 4102 } 4103 4104 return ksmbd_close_fd_app_instance_id(dh_info->AppInstanceId); 4105 } 4106 4107 /** 4108 * smb2_open() - handler for smb file open request 4109 * @work: smb work containing request buffer 4110 * 4111 * Return: 0 on success, otherwise error 4112 */ 4113 int smb2_open(struct ksmbd_work *work) 4114 { 4115 struct ksmbd_conn *conn = work->conn; 4116 struct ksmbd_session *sess = work->sess; 4117 struct ksmbd_tree_connect *tcon = work->tcon; 4118 struct smb2_create_req *req; 4119 struct smb2_create_rsp *rsp; 4120 struct path path; 4121 struct ksmbd_share_config *share = tcon->share_conf; 4122 struct ksmbd_file *fp = NULL; 4123 struct file *filp = NULL; 4124 struct mnt_idmap *idmap = NULL; 4125 struct kstat stat; 4126 struct create_context *context; 4127 struct lease_ctx_info *lc = NULL; 4128 struct create_ea_buf_req *ea_buf = NULL; 4129 struct oplock_info *opinfo; 4130 struct durable_info dh_info = {0}; 4131 __le32 *next_ptr = NULL; 4132 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0; 4133 int rc = 0; 4134 int contxt_cnt = 0, query_disk_id = 0; 4135 bool maximal_access_ctxt = false, posix_ctxt = false; 4136 bool aapl_ctxt = false; 4137 bool durable_rsp = true; 4138 __u64 aapl_req_bitmap = 0, aapl_client_caps = 0; 4139 int s_type = 0; 4140 int next_off = 0; 4141 char *name = NULL; 4142 char *stream_name = NULL; 4143 bool file_present = false, created = false, already_permitted = false; 4144 int share_ret, need_truncate = 0; 4145 u64 time, alloc_size = 0; 4146 umode_t posix_mode = 0; 4147 __le32 daccess, maximal_access = 0; 4148 u32 dos_attr; 4149 int iov_len = 0; 4150 4151 ksmbd_debug(SMB, "Received smb2 create request\n"); 4152 4153 WORK_BUFFERS(work, req, rsp); 4154 4155 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off && 4156 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) { 4157 ksmbd_debug(SMB, "invalid flag in chained command\n"); 4158 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 4159 smb2_set_err_rsp(work); 4160 return -EINVAL; 4161 } 4162 4163 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) { 4164 ksmbd_debug(SMB, "IPC pipe create request\n"); 4165 return create_smb2_pipe(work); 4166 } 4167 4168 if (req->CreateContextsOffset && tcon->posix_extensions) { 4169 context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16); 4170 if (IS_ERR(context)) { 4171 rc = PTR_ERR(context); 4172 goto err_out2; 4173 } else if (context) { 4174 struct create_posix *posix = (struct create_posix *)context; 4175 4176 if (le16_to_cpu(context->DataOffset) + 4177 le32_to_cpu(context->DataLength) < 4178 sizeof(struct create_posix) - 4) { 4179 rc = -EINVAL; 4180 goto err_out2; 4181 } 4182 ksmbd_debug(SMB, "get posix context\n"); 4183 4184 posix_mode = le32_to_cpu(posix->Mode); 4185 posix_ctxt = true; 4186 } 4187 } 4188 4189 if (req->NameLength) { 4190 name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset), 4191 le16_to_cpu(req->NameLength), 4192 work->conn->local_nls); 4193 if (IS_ERR(name)) { 4194 rc = PTR_ERR(name); 4195 name = NULL; 4196 goto err_out2; 4197 } 4198 4199 ksmbd_debug(SMB, "converted name = %s\n", name); 4200 4201 if (posix_ctxt == false) { 4202 if (strchr(name, ':')) { 4203 if (!test_share_config_flag(work->tcon->share_conf, 4204 KSMBD_SHARE_FLAG_STREAMS)) { 4205 rc = -EBADF; 4206 goto err_out2; 4207 } 4208 rc = parse_stream_name(name, &stream_name, &s_type); 4209 if (rc < 0) 4210 goto err_out2; 4211 } 4212 4213 rc = ksmbd_validate_filename(name); 4214 if (rc < 0) 4215 goto err_out2; 4216 } 4217 4218 if (ksmbd_share_veto_filename(share, name)) { 4219 rc = -ENOENT; 4220 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n", 4221 name); 4222 goto err_out2; 4223 } 4224 } else { 4225 name = kstrdup("", KSMBD_DEFAULT_GFP); 4226 if (!name) { 4227 rc = -ENOMEM; 4228 goto err_out2; 4229 } 4230 } 4231 4232 req_op_level = req->RequestedOplockLevel; 4233 4234 if (req->CreateContextsOffset) { 4235 rc = parse_app_instance_id(req, &dh_info); 4236 if (rc) 4237 goto err_out2; 4238 rc = parse_app_instance_version(req, &dh_info); 4239 if (rc) 4240 goto err_out2; 4241 } 4242 4243 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && 4244 req->CreateContextsOffset) { 4245 lc = parse_lease_state(req); 4246 if (IS_ERR(lc)) { 4247 rc = PTR_ERR(lc); 4248 lc = NULL; 4249 goto err_out2; 4250 } 4251 if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) { 4252 kfree(lc); 4253 lc = NULL; 4254 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) 4255 req_op_level = SMB2_OPLOCK_LEVEL_NONE; 4256 } 4257 rc = parse_durable_handle_context(work, req, lc, &dh_info); 4258 if (rc) { 4259 ksmbd_debug(SMB, "error parsing durable handle context\n"); 4260 goto err_out2; 4261 } 4262 4263 if (dh_info.replay == true) { 4264 fp = dh_info.fp; 4265 if (ksmbd_override_fsids(work)) { 4266 rc = -ENOMEM; 4267 goto err_out2; 4268 } 4269 4270 file_info = FILE_OPENED; 4271 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat); 4272 if (rc) 4273 goto err_out2; 4274 4275 goto reconnected_fp; 4276 } 4277 4278 if (dh_info.reconnected == true) { 4279 rc = smb2_check_durable_oplock(conn, share, dh_info.fp, 4280 lc, sess->user, name); 4281 if (rc) 4282 goto err_out2; 4283 4284 rc = ksmbd_reopen_durable_fd(work, dh_info.fp); 4285 if (rc) 4286 goto err_out2; 4287 4288 fp = dh_info.fp; 4289 4290 if (ksmbd_override_fsids(work)) { 4291 rc = -ENOMEM; 4292 goto err_out2; 4293 } 4294 4295 file_info = FILE_OPENED; 4296 4297 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat); 4298 if (rc) 4299 goto err_out2; 4300 4301 goto reconnected_fp; 4302 } 4303 4304 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) { 4305 lc = parse_lease_state(req); 4306 if (IS_ERR(lc)) { 4307 rc = PTR_ERR(lc); 4308 lc = NULL; 4309 goto err_out2; 4310 } 4311 if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) { 4312 kfree(lc); 4313 lc = NULL; 4314 req_op_level = SMB2_OPLOCK_LEVEL_NONE; 4315 } 4316 } 4317 4318 if (dh_info.app_instance_id && !dh_info.reconnected && 4319 !dh_info.replay) { 4320 rc = smb2_handle_app_instance_id(rsp, &dh_info); 4321 if (rc) 4322 goto err_out2; 4323 } 4324 4325 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) { 4326 pr_err("Invalid impersonationlevel : 0x%x\n", 4327 le32_to_cpu(req->ImpersonationLevel)); 4328 rc = -EIO; 4329 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL; 4330 goto err_out2; 4331 } 4332 4333 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) { 4334 pr_err("Invalid create options : 0x%x\n", 4335 le32_to_cpu(req->CreateOptions)); 4336 rc = -EINVAL; 4337 goto err_out2; 4338 } else { 4339 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE && 4340 req->CreateOptions & FILE_RANDOM_ACCESS_LE) 4341 req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE; 4342 4343 if (req->CreateOptions & 4344 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION | 4345 FILE_RESERVE_OPFILTER_LE)) { 4346 rc = -EOPNOTSUPP; 4347 goto err_out2; 4348 } 4349 4350 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) { 4351 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) { 4352 rc = -EINVAL; 4353 goto err_out2; 4354 } 4355 } 4356 } 4357 4358 if (le32_to_cpu(req->CreateDisposition) > 4359 le32_to_cpu(FILE_OVERWRITE_IF_LE)) { 4360 pr_err("Invalid create disposition : 0x%x\n", 4361 le32_to_cpu(req->CreateDisposition)); 4362 rc = -EINVAL; 4363 goto err_out2; 4364 } 4365 4366 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) { 4367 pr_err("Invalid desired access : 0x%x\n", 4368 le32_to_cpu(req->DesiredAccess)); 4369 rc = -EACCES; 4370 goto err_out2; 4371 } 4372 4373 if (req->DesiredAccess == FILE_SYNCHRONIZE_LE && 4374 req->CreateDisposition == FILE_OPEN_IF_LE && 4375 !req->FileAttributes) { 4376 rc = -EACCES; 4377 goto err_out2; 4378 } 4379 4380 if (req->FileAttributes && 4381 (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) { 4382 pr_err("Invalid file attribute : 0x%x\n", 4383 le32_to_cpu(req->FileAttributes)); 4384 rc = -EINVAL; 4385 goto err_out2; 4386 } 4387 4388 if (req->CreateContextsOffset) { 4389 /* Parse non-durable handle create contexts */ 4390 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4); 4391 if (IS_ERR(context)) { 4392 rc = PTR_ERR(context); 4393 goto err_out2; 4394 } else if (context) { 4395 ea_buf = (struct create_ea_buf_req *)context; 4396 if (le16_to_cpu(context->DataOffset) + 4397 le32_to_cpu(context->DataLength) < 4398 sizeof(struct create_ea_buf_req)) { 4399 rc = -EINVAL; 4400 goto err_out2; 4401 } 4402 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) { 4403 rsp->hdr.Status = STATUS_ACCESS_DENIED; 4404 rc = -EACCES; 4405 goto err_out2; 4406 } 4407 } 4408 4409 context = smb2_find_context_vals(req, 4410 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4); 4411 if (IS_ERR(context)) { 4412 rc = PTR_ERR(context); 4413 goto err_out2; 4414 } else if (context) { 4415 ksmbd_debug(SMB, 4416 "get query maximal access context\n"); 4417 maximal_access_ctxt = 1; 4418 } 4419 4420 context = smb2_find_context_vals(req, 4421 SMB2_CREATE_TIMEWARP_REQUEST, 4); 4422 if (IS_ERR(context)) { 4423 rc = PTR_ERR(context); 4424 goto err_out2; 4425 } else if (context) { 4426 ksmbd_debug(SMB, "get timewarp context\n"); 4427 rc = -EBADF; 4428 goto err_out2; 4429 } 4430 } 4431 4432 if (ksmbd_override_fsids(work)) { 4433 rc = -ENOMEM; 4434 goto err_out2; 4435 } 4436 4437 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, 4438 &path, 1); 4439 4440 /* 4441 * A durable handle opened with delete-on-close is preserved across a 4442 * disconnect so it can be reclaimed by a durable reconnect. When a new 4443 * delete-on-close open for the same name arrives instead, the 4444 * disconnected handle must give way: close it so its delete-on-close 4445 * removes the file, then re-resolve so this open can create a fresh one. 4446 */ 4447 if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) && 4448 (req->CreateDisposition == FILE_OVERWRITE_IF_LE || 4449 req->CreateDisposition == FILE_OPEN_IF_LE) && 4450 ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) { 4451 path_put(&path); 4452 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, 4453 &path, 1); 4454 } 4455 4456 if (!rc) { 4457 file_present = true; 4458 4459 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) { 4460 struct xattr_dos_attrib da; 4461 4462 /* 4463 * If file exists with under flags, return access 4464 * denied error. 4465 */ 4466 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE || 4467 req->CreateDisposition == FILE_OPEN_IF_LE) { 4468 rc = -EACCES; 4469 goto err_out; 4470 } 4471 4472 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 4473 ksmbd_debug(SMB, 4474 "User does not have write permission\n"); 4475 rc = -EACCES; 4476 goto err_out; 4477 } 4478 4479 if (test_share_config_flag(tcon->share_conf, 4480 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) && 4481 ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path.mnt), 4482 path.dentry, &da) > 0 && 4483 da.attr & FILE_ATTRIBUTE_READONLY) { 4484 rsp->hdr.Status = STATUS_CANNOT_DELETE; 4485 rc = -EACCES; 4486 goto err_out; 4487 } 4488 } else if (d_is_symlink(path.dentry)) { 4489 rc = -EACCES; 4490 goto err_out; 4491 } 4492 4493 idmap = mnt_idmap(path.mnt); 4494 } else { 4495 if (rc != -ENOENT) 4496 goto err_out; 4497 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n", 4498 name, rc); 4499 rc = 0; 4500 } 4501 4502 if (!file_present && req->CreateOptions & FILE_DELETE_ON_CLOSE_LE && 4503 req->FileAttributes & FILE_ATTRIBUTE_READONLY_LE) { 4504 rsp->hdr.Status = STATUS_CANNOT_DELETE; 4505 rc = -EACCES; 4506 goto err_out; 4507 } 4508 4509 /* 4510 * An explicit ::$DATA suffix names the unnamed data stream and is 4511 * canonicalized to a NULL stream name (base file), but the request 4512 * still has to be validated against the data-stream type, e.g. opening 4513 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with 4514 * STATUS_NOT_A_DIRECTORY. 4515 */ 4516 if (stream_name || s_type == DATA_STREAM) { 4517 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) { 4518 if (s_type == DATA_STREAM) { 4519 rc = -EIO; 4520 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY; 4521 } 4522 } else { 4523 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) && 4524 !stream_name && s_type == DATA_STREAM) { 4525 rc = -EIO; 4526 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY; 4527 } 4528 } 4529 4530 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE && 4531 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) { 4532 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY; 4533 rc = -EIO; 4534 } 4535 4536 if (rc < 0) 4537 goto err_out; 4538 } 4539 4540 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE && 4541 S_ISDIR(d_inode(path.dentry)->i_mode) && 4542 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) { 4543 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n", 4544 name, req->CreateOptions); 4545 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY; 4546 rc = -EIO; 4547 goto err_out; 4548 } 4549 4550 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) && 4551 !(req->CreateDisposition == FILE_CREATE_LE) && 4552 !S_ISDIR(d_inode(path.dentry)->i_mode)) { 4553 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY; 4554 rc = -EIO; 4555 goto err_out; 4556 } 4557 4558 if (!stream_name && file_present && 4559 req->CreateDisposition == FILE_CREATE_LE) { 4560 rc = -EEXIST; 4561 goto err_out; 4562 } 4563 4564 daccess = smb_map_generic_desired_access(req->DesiredAccess); 4565 4566 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) { 4567 rc = smb_check_perm_dacl(conn, &path, &daccess, 4568 req->DesiredAccess, 4569 sess->user->uid, false); 4570 if (rc) 4571 goto err_out; 4572 4573 if (maximal_access_ctxt) { 4574 maximal_access = FILE_MAXIMAL_ACCESS_LE; 4575 rc = smb_check_perm_dacl(conn, &path, &maximal_access, 4576 0, sess->user->uid, false); 4577 if (rc) 4578 goto err_out; 4579 4580 /* 4581 * smb_check_perm_dacl() returns success without 4582 * touching *pdaccess when the object has no stored 4583 * NT ACL, leaving maximal_access as the 4584 * FILE_MAXIMAL_ACCESS_LE request sentinel instead of 4585 * a real access mask. 4586 */ 4587 if (maximal_access == FILE_MAXIMAL_ACCESS_LE) 4588 ksmbd_vfs_query_maximal_access(idmap, path.dentry, 4589 &maximal_access); 4590 } 4591 } 4592 4593 if (daccess & FILE_MAXIMAL_ACCESS_LE) { 4594 if (!file_present) { 4595 daccess = cpu_to_le32(GENERIC_ALL_FLAGS); 4596 } else { 4597 ksmbd_vfs_query_maximal_access(idmap, 4598 path.dentry, 4599 &daccess); 4600 already_permitted = true; 4601 } 4602 maximal_access = daccess; 4603 } 4604 4605 open_flags = smb2_create_open_flags(file_present, daccess, 4606 req->CreateDisposition, 4607 &may_flags, 4608 req->CreateOptions, 4609 file_present ? d_inode(path.dentry)->i_mode : 0); 4610 4611 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 4612 if (open_flags & (O_CREAT | O_TRUNC)) { 4613 ksmbd_debug(SMB, 4614 "User does not have write permission\n"); 4615 rc = -EACCES; 4616 goto err_out; 4617 } 4618 } 4619 4620 /*create file if not present */ 4621 if (!file_present) { 4622 rc = smb2_creat(work, &path, name, open_flags, 4623 posix_mode, 4624 req->CreateOptions & FILE_DIRECTORY_FILE_LE); 4625 if (rc) { 4626 if (rc == -ENOENT) { 4627 rc = -EIO; 4628 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND; 4629 } 4630 goto err_out; 4631 } 4632 4633 created = true; 4634 idmap = mnt_idmap(path.mnt); 4635 if (ea_buf) { 4636 if (le32_to_cpu(ea_buf->ccontext.DataLength) < 4637 sizeof(struct smb2_ea_info)) { 4638 rc = -EINVAL; 4639 goto err_out; 4640 } 4641 4642 rc = smb2_set_ea(&ea_buf->ea, 4643 le32_to_cpu(ea_buf->ccontext.DataLength), 4644 &path, false); 4645 if (rc == -EOPNOTSUPP) 4646 rc = 0; 4647 else if (rc) 4648 goto err_out; 4649 } 4650 } else if (!already_permitted) { 4651 /* FILE_READ_ATTRIBUTE is allowed without inode_permission, 4652 * because execute(search) permission on a parent directory, 4653 * is already granted. 4654 */ 4655 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) { 4656 rc = inode_permission(idmap, 4657 d_inode(path.dentry), 4658 may_flags); 4659 if (rc) 4660 goto err_out; 4661 4662 if ((daccess & FILE_DELETE_LE) || 4663 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) { 4664 rc = inode_permission(idmap, 4665 d_inode(path.dentry->d_parent), 4666 MAY_EXEC | MAY_WRITE); 4667 if (rc) 4668 goto err_out; 4669 } 4670 } 4671 } 4672 4673 rc = ksmbd_query_inode_status(path.dentry->d_parent); 4674 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) { 4675 rc = -EBUSY; 4676 goto err_out; 4677 } 4678 4679 rc = 0; 4680 filp = dentry_open(&path, open_flags, current_cred()); 4681 if (IS_ERR(filp)) { 4682 rc = PTR_ERR(filp); 4683 pr_err("dentry open for dir failed, rc %d\n", rc); 4684 goto err_out; 4685 } 4686 4687 if (file_present) { 4688 if (!(open_flags & O_TRUNC)) 4689 file_info = FILE_OPENED; 4690 else 4691 file_info = FILE_OVERWRITTEN; 4692 4693 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) == 4694 FILE_SUPERSEDE_LE) 4695 file_info = FILE_SUPERSEDED; 4696 } else if (open_flags & O_CREAT) { 4697 file_info = FILE_CREATED; 4698 } 4699 4700 ksmbd_vfs_set_fadvise(filp, req->CreateOptions); 4701 4702 /* Obtain Volatile-ID */ 4703 fp = ksmbd_open_fd(work, filp); 4704 if (IS_ERR(fp)) { 4705 fput(filp); 4706 rc = PTR_ERR(fp); 4707 fp = NULL; 4708 goto err_out; 4709 } 4710 4711 /* Get Persistent-ID */ 4712 ksmbd_open_durable_fd(fp); 4713 if (!has_file_id(fp->persistent_id)) { 4714 rc = -ENOMEM; 4715 goto err_out; 4716 } 4717 4718 /* 4719 * Publish the client and create GUID before an oplock/lease break can 4720 * make this CREATE pending. A replay of that in-flight CREATE must find 4721 * this FP_NEW handle and fail with STATUS_FILE_NOT_AVAILABLE instead of 4722 * waiting on the same break again. 4723 */ 4724 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE); 4725 if (dh_info.app_instance_id) { 4726 memcpy(fp->app_instance_id, dh_info.AppInstanceId, 4727 SMB2_CREATE_GUID_SIZE); 4728 fp->has_app_instance_id = true; 4729 } 4730 if (dh_info.app_instance_version_valid) { 4731 fp->app_instance_version_high = 4732 dh_info.app_instance_version_high; 4733 fp->app_instance_version_low = dh_info.app_instance_version_low; 4734 fp->app_instance_version_valid = true; 4735 } 4736 if (dh_info.CreateGuid) { 4737 memcpy(fp->create_guid, dh_info.CreateGuid, SMB2_CREATE_GUID_SIZE); 4738 fp->durable_replay_consumed = dh_info.replay_consumed; 4739 rc = ksmbd_vfs_set_durable_owner(fp, sess->user); 4740 if (rc) 4741 goto err_out; 4742 } 4743 4744 fp->cdoption = req->CreateDisposition; 4745 fp->create_file_attributes = req->FileAttributes; 4746 fp->daccess = daccess; 4747 fp->saccess = req->ShareAccess; 4748 fp->coption = req->CreateOptions; 4749 4750 /* Set default windows and posix acls if creating new file */ 4751 if (created) { 4752 int posix_acl_rc; 4753 struct inode *inode = d_inode(path.dentry); 4754 4755 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap, 4756 &path, 4757 d_inode(path.dentry->d_parent)); 4758 if (posix_acl_rc) 4759 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc); 4760 4761 rc = smb2_create_sd_buffer(work, req, &path); 4762 if (rc && rc != -ENOENT) 4763 goto err_out; 4764 4765 if (rc == -ENOENT) { 4766 if (test_share_config_flag(work->tcon->share_conf, 4767 KSMBD_SHARE_FLAG_ACL_XATTR)) { 4768 rc = smb_inherit_dacl(conn, &path, sess->user->uid, 4769 sess->user->gid); 4770 } 4771 if (rc) { 4772 if (posix_acl_rc) 4773 ksmbd_vfs_set_init_posix_acl(idmap, 4774 &path); 4775 4776 if (test_share_config_flag(work->tcon->share_conf, 4777 KSMBD_SHARE_FLAG_ACL_XATTR)) { 4778 struct smb_fattr fattr; 4779 struct smb_ntsd *pntsd; 4780 int pntsd_size; 4781 size_t scratch_len; 4782 4783 ksmbd_acls_fattr(&fattr, idmap, inode); 4784 scratch_len = smb_acl_sec_desc_scratch_len(&fattr, 4785 NULL, 0, 4786 OWNER_SECINFO | GROUP_SECINFO | 4787 DACL_SECINFO); 4788 if (!scratch_len || scratch_len == SIZE_MAX) { 4789 rc = -EFBIG; 4790 posix_acl_release(fattr.cf_acls); 4791 posix_acl_release(fattr.cf_dacls); 4792 goto err_out; 4793 } 4794 4795 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP); 4796 if (!pntsd) { 4797 rc = -ENOMEM; 4798 posix_acl_release(fattr.cf_acls); 4799 posix_acl_release(fattr.cf_dacls); 4800 goto err_out; 4801 } 4802 4803 rc = build_sec_desc(idmap, 4804 pntsd, NULL, 0, 4805 OWNER_SECINFO | 4806 GROUP_SECINFO | 4807 DACL_SECINFO, 4808 &pntsd_size, &fattr); 4809 posix_acl_release(fattr.cf_acls); 4810 posix_acl_release(fattr.cf_dacls); 4811 if (rc) { 4812 kvfree(pntsd); 4813 goto err_out; 4814 } 4815 4816 rc = ksmbd_vfs_set_sd_xattr(conn, 4817 idmap, 4818 &path, 4819 pntsd, 4820 pntsd_size, 4821 false); 4822 kvfree(pntsd); 4823 if (rc) 4824 pr_err("failed to store ntacl in xattr : %d\n", 4825 rc); 4826 } 4827 } 4828 } 4829 rc = 0; 4830 } 4831 4832 if (stream_name) { 4833 rc = smb2_set_stream_name_xattr(&path, 4834 fp, 4835 stream_name, 4836 s_type); 4837 if (rc) 4838 goto err_out; 4839 file_info = FILE_CREATED; 4840 } 4841 4842 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE | 4843 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE)); 4844 4845 fp->is_posix_ctxt = posix_ctxt; 4846 4847 /* fp should be searchable through ksmbd_inode.m_fp_list 4848 * after daccess, saccess, attrib_only, and stream are 4849 * initialized. 4850 */ 4851 down_write(&fp->f_ci->m_lock); 4852 list_add(&fp->node, &fp->f_ci->m_fp_list); 4853 up_write(&fp->f_ci->m_lock); 4854 4855 /* Check delete pending among previous fp before oplock break */ 4856 if (ksmbd_inode_pending_delete(fp)) { 4857 rc = -EBUSY; 4858 goto err_out; 4859 } 4860 4861 if (!stream_name && daccess & FILE_DELETE_LE && 4862 ksmbd_has_stream_without_delete_share(fp)) { 4863 rc = -EPERM; 4864 goto err_out; 4865 } 4866 4867 if (file_present || created) 4868 path_put(&path); 4869 4870 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC && 4871 !fp->attrib_only && !stream_name) { 4872 smb_break_all_oplock(work, fp); 4873 need_truncate = 1; 4874 } 4875 4876 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp); 4877 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) || 4878 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && 4879 !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) { 4880 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) { 4881 rc = share_ret; 4882 goto err_out1; 4883 } 4884 } else { 4885 if (created && !lc) 4886 smb_send_parent_lease_break_noti(fp, NULL); 4887 4888 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) { 4889 if (S_ISDIR(file_inode(filp)->i_mode)) { 4890 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE; 4891 lc->is_dir = true; 4892 } 4893 4894 /* 4895 * Compare parent lease using parent key. If there is no 4896 * a lease that has same parent key, Send lease break 4897 * notification. 4898 */ 4899 smb_send_parent_lease_break_noti(fp, lc); 4900 4901 req_op_level = smb2_map_lease_to_oplock(lc->req_state); 4902 ksmbd_debug(SMB, 4903 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n", 4904 name, req_op_level, lc->req_state); 4905 rc = find_same_lease_key(conn, fp->f_ci, lc); 4906 if (rc) 4907 goto err_out1; 4908 } else if (open_flags == O_RDONLY && 4909 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH || 4910 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)) 4911 req_op_level = SMB2_OPLOCK_LEVEL_II; 4912 4913 rc = smb_grant_oplock(work, req_op_level, 4914 fp->persistent_id, fp, 4915 le32_to_cpu(req->hdr.Id.SyncId.TreeId), 4916 lc, share_ret, 4917 smb3_hdr_replay(&req->hdr)); 4918 if (rc < 0) 4919 goto err_out1; 4920 } 4921 4922 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) { 4923 smb_break_all_levII_oplock_for_delete(work, fp); 4924 ksmbd_fd_set_delete_on_close(fp, file_info); 4925 } 4926 4927 if (need_truncate) { 4928 rc = smb2_create_truncate(&fp->filp->f_path); 4929 if (rc) 4930 goto err_out1; 4931 } 4932 4933 if (req->CreateContextsOffset) { 4934 struct create_alloc_size_req *az_req; 4935 4936 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req, 4937 SMB2_CREATE_ALLOCATION_SIZE, 4); 4938 if (IS_ERR(az_req)) { 4939 rc = PTR_ERR(az_req); 4940 goto err_out1; 4941 } else if (az_req) { 4942 int err; 4943 4944 if (le16_to_cpu(az_req->ccontext.DataOffset) + 4945 le32_to_cpu(az_req->ccontext.DataLength) < 4946 sizeof(struct create_alloc_size_req)) { 4947 rc = -EINVAL; 4948 goto err_out1; 4949 } 4950 alloc_size = le64_to_cpu(az_req->AllocationSize); 4951 fp->allocation_size_set = true; 4952 ksmbd_debug(SMB, 4953 "request smb2 create allocate size : %llu\n", 4954 alloc_size); 4955 /* 4956 * fp->filp is the base file's data fork for a stream 4957 * handle (streams are xattr-backed on the same 4958 * underlying file) -- fallocate has no meaning for a 4959 * stream and would otherwise pre-allocate storage on 4960 * the base file's data instead. 4961 */ 4962 if (!ksmbd_stream_fd(fp)) { 4963 smb_break_all_levII_oplock(work, fp, 1); 4964 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, 4965 alloc_size); 4966 if (err < 0) 4967 ksmbd_debug(SMB, 4968 "vfs_fallocate is failed : %d\n", 4969 err); 4970 } 4971 } 4972 4973 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4); 4974 if (IS_ERR(context)) { 4975 rc = PTR_ERR(context); 4976 goto err_out1; 4977 } else if (context) { 4978 ksmbd_debug(SMB, "get query on disk id context\n"); 4979 query_disk_id = 1; 4980 } 4981 4982 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_TIME_MACHINE)) { 4983 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4); 4984 if (IS_ERR(context)) { 4985 rc = PTR_ERR(context); 4986 goto err_out1; 4987 } else if (context) { 4988 struct aapl_server_query_req *aapl_req; 4989 4990 if (le32_to_cpu(context->DataLength) < 4991 sizeof(struct aapl_server_query_req)) { 4992 rc = -EINVAL; 4993 goto err_out1; 4994 } 4995 4996 aapl_req = (struct aapl_server_query_req *) 4997 ((char *)context + 4998 le16_to_cpu(context->DataOffset)); 4999 if (le32_to_cpu(aapl_req->cmd) == 5000 SMB2_CRTCTX_AAPL_SERVER_QUERY) { 5001 conn->is_aapl = true; 5002 aapl_ctxt = true; 5003 aapl_req_bitmap = le64_to_cpu(aapl_req->req_bitmap); 5004 aapl_client_caps = le64_to_cpu(aapl_req->client_caps); 5005 } 5006 } 5007 } else if (conn->is_aapl == false) { 5008 context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4); 5009 if (IS_ERR(context)) { 5010 rc = PTR_ERR(context); 5011 goto err_out1; 5012 } else if (context) 5013 conn->is_aapl = true; 5014 } 5015 } 5016 5017 rc = ksmbd_vfs_getattr(&path, &stat); 5018 if (rc) 5019 goto err_out1; 5020 5021 if (stat.result_mask & STATX_BTIME) 5022 fp->create_time = ksmbd_UnixTimeToNT(stat.btime); 5023 else 5024 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime); 5025 fp->change_time = ksmbd_UnixTimeToNT(stat.ctime); 5026 fp->allocation_size = S_ISDIR(stat.mode) ? 0 : 5027 (alloc_size ?: stat.blocks << 9); 5028 if (created || fp->f_ci->m_fattr == 0) 5029 fp->f_ci->m_fattr = 5030 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes))); 5031 5032 if (!created) 5033 smb2_update_xattrs(tcon, &path, fp); 5034 if (need_truncate && req->FileAttributes) { 5035 dos_attr = le32_to_cpu(req->FileAttributes); 5036 fp->f_ci->m_fattr = 5037 cpu_to_le32(smb2_get_dos_mode(&stat, dos_attr)); 5038 smb2_new_xattrs(tcon, &path, fp); 5039 } 5040 5041 ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr); 5042 5043 if (created) { 5044 if (fp->coption & FILE_NO_COMPRESSION_LE) { 5045 rc = ksmbd_vfs_set_compression_create(work, fp, 5046 COMPRESSION_FORMAT_NONE); 5047 if (rc) 5048 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_COMPRESSED_LE; 5049 rc = 0; 5050 } else if (smb2_parent_compressed(tcon, &path)) { 5051 rc = ksmbd_vfs_set_compression_create(work, fp, 5052 COMPRESSION_FORMAT_LZNT1); 5053 if (rc) 5054 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_COMPRESSED_LE; 5055 rc = 0; 5056 } 5057 } 5058 5059 if (created) 5060 smb2_new_xattrs(tcon, &path, fp); 5061 5062 fp->create_action = cpu_to_le32(file_info); 5063 5064 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) { 5065 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent && 5066 test_share_config_flag(work->tcon->share_conf, 5067 KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY) && 5068 (conn->vals->req_capabilities & 5069 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)) { 5070 /* MS-SMB2 3.3.5.9.10: a persistent open is durable too. */ 5071 fp->is_durable = true; 5072 fp->is_persistent = true; 5073 } else { 5074 fp->is_durable = true; 5075 } 5076 if (dh_info.type == DURABLE_REQ_V2) { 5077 if (dh_info.app_instance_id) 5078 memcpy(fp->app_instance_id, 5079 dh_info.AppInstanceId, 5080 SMB2_CREATE_GUID_SIZE); 5081 if (dh_info.timeout) 5082 fp->durable_timeout = 5083 min_t(unsigned int, dh_info.timeout, 5084 DURABLE_HANDLE_MAX_TIMEOUT); 5085 else 5086 fp->durable_timeout = 60000; 5087 } 5088 } 5089 5090 /* 5091 * conn->is_aapl detection above (this function's create-context 5092 * parsing) is skipped on the reconnect path below, since a 5093 * reconnect always arrives on a fresh connection -- if the client 5094 * cares, it sends its own AAPL context on this same CREATE, which 5095 * this function's normal (non-reconnect) parsing already handles. 5096 */ 5097 reconnected_fp: 5098 if (dh_info.replay) 5099 file_info = le32_to_cpu(fp->create_action); 5100 rsp->StructureSize = cpu_to_le16(89); 5101 opinfo = opinfo_get(fp); 5102 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0; 5103 /* 5104 * A durable CREATE replay does not modify the existing open. When 5105 * replayed without an oplock, however, its response reflects that 5106 * request and cannot include a new durable-handle response context. 5107 */ 5108 if (dh_info.replay && !lc && 5109 req_op_level == SMB2_OPLOCK_LEVEL_NONE) { 5110 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE; 5111 durable_rsp = false; 5112 } 5113 rsp->Flags = 0; 5114 rsp->CreateAction = cpu_to_le32(file_info); 5115 rsp->CreationTime = cpu_to_le64(fp->create_time); 5116 time = ksmbd_UnixTimeToNT(stat.atime); 5117 rsp->LastAccessTime = cpu_to_le64(time); 5118 time = ksmbd_UnixTimeToNT(stat.mtime); 5119 fp->open_mtime = time; 5120 rsp->LastWriteTime = cpu_to_le64(time); 5121 rsp->ChangeTime = cpu_to_le64(fp->change_time); 5122 /* 5123 * The cached allocation size hides filesystem rounding for the 5124 * requested allocation, but it can go stale when the file grows past 5125 * it via writes (e.g. across a durable reconnect). Refresh it once the 5126 * file exceeds the cached value, rounding the end of file up to the 5127 * volume allocation unit (the filesystem block size, matching the 5128 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than 5129 * using the raw on-disk block count, which can include filesystem 5130 * preallocation and metadata rounding. 5131 */ 5132 if (ksmbd_stream_fd(fp)) { 5133 loff_t seof = ksmbd_stream_eof(fp); 5134 5135 rsp->AllocationSize = cpu_to_le64((u64)seof); 5136 rsp->EndofFile = cpu_to_le64((u64)seof); 5137 } else { 5138 if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size) 5139 fp->allocation_size = round_up(stat.size, stat.blksize); 5140 rsp->AllocationSize = cpu_to_le64(fp->allocation_size); 5141 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size); 5142 } 5143 rsp->FileAttributes = fp->f_ci->m_fattr; 5144 5145 rsp->Reserved2 = 0; 5146 5147 rsp->PersistentFileId = fp->persistent_id; 5148 rsp->VolatileFileId = fp->volatile_id; 5149 5150 rsp->CreateContextsOffset = 0; 5151 rsp->CreateContextsLength = 0; 5152 iov_len = offsetof(struct smb2_create_rsp, Buffer); 5153 5154 /* If lease is request send lease context response */ 5155 if (opinfo && opinfo->is_lease) { 5156 struct create_context *lease_ccontext; 5157 5158 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n", 5159 name, opinfo->o_lease->state); 5160 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE; 5161 5162 lease_ccontext = (struct create_context *)rsp->Buffer; 5163 contxt_cnt++; 5164 create_lease_buf(rsp->Buffer, opinfo->o_lease); 5165 le32_add_cpu(&rsp->CreateContextsLength, 5166 conn->vals->create_lease_size); 5167 iov_len += conn->vals->create_lease_size; 5168 next_ptr = &lease_ccontext->Next; 5169 next_off = conn->vals->create_lease_size; 5170 } 5171 opinfo_put(opinfo); 5172 5173 if (maximal_access_ctxt) { 5174 struct create_context *mxac_ccontext; 5175 5176 if (maximal_access == 0) 5177 ksmbd_vfs_query_maximal_access(idmap, 5178 path.dentry, 5179 &maximal_access); 5180 mxac_ccontext = (struct create_context *)(rsp->Buffer + 5181 le32_to_cpu(rsp->CreateContextsLength)); 5182 contxt_cnt++; 5183 create_mxac_rsp_buf(rsp->Buffer + 5184 le32_to_cpu(rsp->CreateContextsLength), 5185 le32_to_cpu(maximal_access)); 5186 le32_add_cpu(&rsp->CreateContextsLength, 5187 conn->vals->create_mxac_size); 5188 iov_len += conn->vals->create_mxac_size; 5189 if (next_ptr) 5190 *next_ptr = cpu_to_le32(next_off); 5191 next_ptr = &mxac_ccontext->Next; 5192 next_off = conn->vals->create_mxac_size; 5193 } 5194 5195 if (query_disk_id) { 5196 struct create_context *disk_id_ccontext; 5197 5198 disk_id_ccontext = (struct create_context *)(rsp->Buffer + 5199 le32_to_cpu(rsp->CreateContextsLength)); 5200 contxt_cnt++; 5201 create_disk_id_rsp_buf(rsp->Buffer + 5202 le32_to_cpu(rsp->CreateContextsLength), 5203 stat.ino, tcon->id); 5204 le32_add_cpu(&rsp->CreateContextsLength, 5205 conn->vals->create_disk_id_size); 5206 iov_len += conn->vals->create_disk_id_size; 5207 if (next_ptr) 5208 *next_ptr = cpu_to_le32(next_off); 5209 next_ptr = &disk_id_ccontext->Next; 5210 next_off = conn->vals->create_disk_id_size; 5211 } 5212 5213 if (durable_rsp && 5214 (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2)) { 5215 struct create_context *durable_ccontext; 5216 5217 durable_ccontext = (struct create_context *)(rsp->Buffer + 5218 le32_to_cpu(rsp->CreateContextsLength)); 5219 contxt_cnt++; 5220 if (dh_info.type == DURABLE_REQ) { 5221 create_durable_rsp_buf(rsp->Buffer + 5222 le32_to_cpu(rsp->CreateContextsLength)); 5223 le32_add_cpu(&rsp->CreateContextsLength, 5224 conn->vals->create_durable_size); 5225 iov_len += conn->vals->create_durable_size; 5226 } else { 5227 create_durable_v2_rsp_buf(rsp->Buffer + 5228 le32_to_cpu(rsp->CreateContextsLength), 5229 fp); 5230 le32_add_cpu(&rsp->CreateContextsLength, 5231 conn->vals->create_durable_v2_size); 5232 iov_len += conn->vals->create_durable_v2_size; 5233 } 5234 5235 if (next_ptr) 5236 *next_ptr = cpu_to_le32(next_off); 5237 next_ptr = &durable_ccontext->Next; 5238 next_off = dh_info.type == DURABLE_REQ ? 5239 conn->vals->create_durable_size : 5240 conn->vals->create_durable_v2_size; 5241 } 5242 5243 if (posix_ctxt) { 5244 struct create_context *posix_ccontext; 5245 5246 posix_ccontext = (struct create_context *)(rsp->Buffer + 5247 le32_to_cpu(rsp->CreateContextsLength)); 5248 contxt_cnt++; 5249 create_posix_rsp_buf(rsp->Buffer + 5250 le32_to_cpu(rsp->CreateContextsLength), 5251 fp); 5252 le32_add_cpu(&rsp->CreateContextsLength, 5253 conn->vals->create_posix_size); 5254 iov_len += conn->vals->create_posix_size; 5255 if (next_ptr) 5256 *next_ptr = cpu_to_le32(next_off); 5257 next_ptr = &posix_ccontext->Next; 5258 next_off = conn->vals->create_posix_size; 5259 } 5260 5261 /* 5262 * AAPL create context response: see smb2pdu.h for the capability 5263 * rationale. Scoped to TIME_MACHINE shares only. 5264 */ 5265 if (aapl_ctxt) { 5266 if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR) 5267 conn->aapl_readdir_attr = true; 5268 /* 5269 * V2 extends the same inline-FinderInfo mechanism (see 5270 * smb2pdu.h), so a V2-requesting client also gets 5271 * aapl_readdir_attr treatment -- the reply just advertises 5272 * the V2 bit instead of the V1 one (create_aapl_rsp_buf). 5273 */ 5274 if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2) { 5275 conn->aapl_readdir_attr = true; 5276 conn->aapl_readdir_attr_v2 = true; 5277 } 5278 5279 contxt_cnt++; 5280 create_aapl_rsp_buf(rsp->Buffer + 5281 le32_to_cpu(rsp->CreateContextsLength), 5282 SMB2_CRTCTX_AAPL_FULL_SYNC, 5283 aapl_req_bitmap, 5284 conn->aapl_readdir_attr_v2); 5285 le32_add_cpu(&rsp->CreateContextsLength, 5286 conn->vals->create_aapl_size); 5287 iov_len += conn->vals->create_aapl_size; 5288 if (next_ptr) 5289 *next_ptr = cpu_to_le32(next_off); 5290 /* AAPL is last; next_ptr need not be updated */ 5291 } 5292 5293 if (contxt_cnt > 0) { 5294 rsp->CreateContextsOffset = 5295 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer)); 5296 } 5297 5298 err_out: 5299 if (rc && (file_present || created)) 5300 path_put(&path); 5301 5302 err_out1: 5303 ksmbd_revert_fsids(work); 5304 5305 err_out2: 5306 if (!rc) { 5307 if (!dh_info.replay) 5308 rc = ksmbd_update_fstate(&work->sess->file_table, fp, 5309 FP_INITED); 5310 if (!rc) 5311 rc = smb2_set_request_open(work, fp, &req->hdr, false, false); 5312 if (!rc) 5313 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len); 5314 } 5315 if (rc) { 5316 if (rc == -EINVAL) 5317 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 5318 else if (rc == -EOPNOTSUPP) 5319 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 5320 else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) && 5321 !rsp->hdr.Status) { 5322 if (req->DesiredAccess & FILE_ACCESS_SYSTEM_SECURITY_LE) 5323 rsp->hdr.Status = STATUS_PRIVILEGE_NOT_HELD; 5324 else 5325 rsp->hdr.Status = STATUS_ACCESS_DENIED; 5326 } 5327 else if (rc == -ENOENT) 5328 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID; 5329 else if (rc == -EPERM) 5330 rsp->hdr.Status = STATUS_SHARING_VIOLATION; 5331 else if (rc == -EBUSY) 5332 rsp->hdr.Status = STATUS_DELETE_PENDING; 5333 else if (rc == -EBADF) 5334 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND; 5335 else if (rc == -ENOEXEC) 5336 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID; 5337 else if (rc == -ENXIO) 5338 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE; 5339 else if (rc == -EEXIST) 5340 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION; 5341 else if (rc == -EMFILE) 5342 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 5343 else if (rc == -EINPROGRESS) 5344 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE; 5345 else if (rc == -EAGAIN) 5346 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE; 5347 if (!rsp->hdr.Status) 5348 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 5349 5350 if (fp && !dh_info.replay) 5351 ksmbd_fd_put(work, fp); 5352 smb2_set_err_rsp(work); 5353 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status); 5354 } 5355 5356 if (dh_info.replay) 5357 ksmbd_put_durable_fd(dh_info.fp); 5358 5359 if (dh_info.reconnected) { 5360 /* 5361 * If reconnect succeeded, fp was republished in the 5362 * session file table. On a later error, ksmbd_fd_put() 5363 * above drops the session reference; drop the durable 5364 * lookup reference through the same session-aware path so 5365 * final close removes the volatile id before freeing fp. 5366 */ 5367 if (rc && fp == dh_info.fp) 5368 ksmbd_fd_put(work, dh_info.fp); 5369 else 5370 ksmbd_put_durable_fd(dh_info.fp); 5371 } 5372 5373 kfree(name); 5374 kfree(lc); 5375 5376 return rc; 5377 } 5378 5379 static int readdir_info_level_struct_sz(int info_level) 5380 { 5381 switch (info_level) { 5382 case FILE_FULL_DIRECTORY_INFORMATION: 5383 return sizeof(FILE_FULL_DIRECTORY_INFO); 5384 case FILE_BOTH_DIRECTORY_INFORMATION: 5385 return sizeof(FILE_BOTH_DIRECTORY_INFO); 5386 case FILE_DIRECTORY_INFORMATION: 5387 return sizeof(FILE_DIRECTORY_INFO); 5388 case FILE_NAMES_INFORMATION: 5389 return sizeof(struct file_names_info); 5390 case FILEID_FULL_DIRECTORY_INFORMATION: 5391 return sizeof(FILE_ID_FULL_DIR_INFO); 5392 case FILEID_BOTH_DIRECTORY_INFORMATION: 5393 return sizeof(struct file_id_both_directory_info); 5394 case SMB_FIND_FILE_POSIX_INFO: 5395 return sizeof(struct smb2_posix_info); 5396 default: 5397 return -EOPNOTSUPP; 5398 } 5399 } 5400 5401 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level) 5402 { 5403 switch (info_level) { 5404 case FILE_FULL_DIRECTORY_INFORMATION: 5405 { 5406 FILE_FULL_DIRECTORY_INFO *ffdinfo; 5407 5408 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr; 5409 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset); 5410 d_info->name = ffdinfo->FileName; 5411 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength); 5412 return 0; 5413 } 5414 case FILE_BOTH_DIRECTORY_INFORMATION: 5415 { 5416 FILE_BOTH_DIRECTORY_INFO *fbdinfo; 5417 5418 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr; 5419 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset); 5420 d_info->name = fbdinfo->FileName; 5421 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength); 5422 return 0; 5423 } 5424 case FILE_DIRECTORY_INFORMATION: 5425 { 5426 FILE_DIRECTORY_INFO *fdinfo; 5427 5428 fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr; 5429 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset); 5430 d_info->name = fdinfo->FileName; 5431 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength); 5432 return 0; 5433 } 5434 case FILE_NAMES_INFORMATION: 5435 { 5436 struct file_names_info *fninfo; 5437 5438 fninfo = (struct file_names_info *)d_info->rptr; 5439 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset); 5440 d_info->name = fninfo->FileName; 5441 d_info->name_len = le32_to_cpu(fninfo->FileNameLength); 5442 return 0; 5443 } 5444 case FILEID_FULL_DIRECTORY_INFORMATION: 5445 { 5446 FILE_ID_FULL_DIR_INFO *dinfo; 5447 5448 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr; 5449 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset); 5450 d_info->name = dinfo->FileName; 5451 d_info->name_len = le32_to_cpu(dinfo->FileNameLength); 5452 return 0; 5453 } 5454 case FILEID_BOTH_DIRECTORY_INFORMATION: 5455 { 5456 struct file_id_both_directory_info *fibdinfo; 5457 5458 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr; 5459 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset); 5460 d_info->name = fibdinfo->FileName; 5461 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength); 5462 return 0; 5463 } 5464 case SMB_FIND_FILE_POSIX_INFO: 5465 { 5466 struct smb2_posix_info *posix_info; 5467 5468 posix_info = (struct smb2_posix_info *)d_info->rptr; 5469 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset); 5470 d_info->name = posix_info->name; 5471 d_info->name_len = le32_to_cpu(posix_info->name_len); 5472 return 0; 5473 } 5474 default: 5475 return -EINVAL; 5476 } 5477 } 5478 5479 /** 5480 * smb2_populate_readdir_entry() - encode directory entry in smb2 response 5481 * buffer 5482 * @conn: connection instance 5483 * @info_level: smb information level 5484 * @d_info: structure included variables for query dir 5485 * @ksmbd_kstat: ksmbd wrapper of dirent stat information 5486 * 5487 * if directory has many entries, find first can't read it fully. 5488 * find next might be called multiple times to read remaining dir entries 5489 * 5490 * Return: 0 on success, otherwise error 5491 */ 5492 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level, 5493 struct ksmbd_dir_info *d_info, 5494 struct ksmbd_kstat *ksmbd_kstat) 5495 { 5496 int next_entry_offset = 0; 5497 char *conv_name; 5498 int conv_len; 5499 void *kstat; 5500 int struct_sz, rc = 0; 5501 5502 conv_name = ksmbd_convert_dir_info_name(d_info, 5503 conn->local_nls, 5504 &conv_len); 5505 if (!conv_name) 5506 return -ENOMEM; 5507 5508 /* Somehow the name has only terminating NULL bytes */ 5509 if (conv_len < 0) { 5510 rc = -EINVAL; 5511 goto free_conv_name; 5512 } 5513 5514 struct_sz = readdir_info_level_struct_sz(info_level); 5515 if (struct_sz == -EOPNOTSUPP) { 5516 rc = -EINVAL; 5517 goto free_conv_name; 5518 } 5519 5520 struct_sz += conv_len; 5521 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT); 5522 d_info->last_entry_off_align = next_entry_offset - struct_sz; 5523 5524 if (next_entry_offset > d_info->out_buf_len) { 5525 d_info->out_buf_len = 0; 5526 rc = -ENOSPC; 5527 goto free_conv_name; 5528 } 5529 5530 kstat = d_info->wptr; 5531 if (info_level != FILE_NAMES_INFORMATION) 5532 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat); 5533 5534 switch (info_level) { 5535 case FILE_FULL_DIRECTORY_INFORMATION: 5536 { 5537 FILE_FULL_DIRECTORY_INFO *ffdinfo; 5538 5539 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat; 5540 ffdinfo->FileNameLength = cpu_to_le32(conv_len); 5541 ffdinfo->EaSize = 5542 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode); 5543 if (ffdinfo->EaSize) 5544 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE; 5545 if (d_info->hide_dot_file && d_info->name[0] == '.') 5546 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5547 memcpy(ffdinfo->FileName, conv_name, conv_len); 5548 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5549 break; 5550 } 5551 case FILE_BOTH_DIRECTORY_INFORMATION: 5552 { 5553 FILE_BOTH_DIRECTORY_INFO *fbdinfo; 5554 5555 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat; 5556 fbdinfo->FileNameLength = cpu_to_le32(conv_len); 5557 fbdinfo->EaSize = 5558 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode); 5559 if (fbdinfo->EaSize) 5560 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE; 5561 fbdinfo->ShortNameLength = 0; 5562 fbdinfo->Reserved = 0; 5563 if (d_info->hide_dot_file && d_info->name[0] == '.') 5564 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5565 memcpy(fbdinfo->FileName, conv_name, conv_len); 5566 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5567 break; 5568 } 5569 case FILE_DIRECTORY_INFORMATION: 5570 { 5571 FILE_DIRECTORY_INFO *fdinfo; 5572 5573 fdinfo = (FILE_DIRECTORY_INFO *)kstat; 5574 fdinfo->FileNameLength = cpu_to_le32(conv_len); 5575 if (d_info->hide_dot_file && d_info->name[0] == '.') 5576 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5577 memcpy(fdinfo->FileName, conv_name, conv_len); 5578 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5579 break; 5580 } 5581 case FILE_NAMES_INFORMATION: 5582 { 5583 struct file_names_info *fninfo; 5584 5585 fninfo = (struct file_names_info *)kstat; 5586 fninfo->FileNameLength = cpu_to_le32(conv_len); 5587 memcpy(fninfo->FileName, conv_name, conv_len); 5588 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5589 break; 5590 } 5591 case FILEID_FULL_DIRECTORY_INFORMATION: 5592 { 5593 FILE_ID_FULL_DIR_INFO *dinfo; 5594 5595 dinfo = (FILE_ID_FULL_DIR_INFO *)kstat; 5596 dinfo->FileNameLength = cpu_to_le32(conv_len); 5597 dinfo->EaSize = 5598 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode); 5599 if (dinfo->EaSize) 5600 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE; 5601 dinfo->Reserved = 0; 5602 if (conn->is_aapl) 5603 dinfo->UniqueId = 0; 5604 else 5605 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino); 5606 if (d_info->hide_dot_file && d_info->name[0] == '.') 5607 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5608 memcpy(dinfo->FileName, conv_name, conv_len); 5609 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5610 break; 5611 } 5612 case FILEID_BOTH_DIRECTORY_INFORMATION: 5613 { 5614 struct file_id_both_directory_info *fibdinfo; 5615 5616 fibdinfo = (struct file_id_both_directory_info *)kstat; 5617 fibdinfo->FileNameLength = cpu_to_le32(conv_len); 5618 if (conn->is_aapl) 5619 fibdinfo->UniqueId = 0; 5620 else 5621 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino); 5622 fibdinfo->ShortNameLength = 0; 5623 fibdinfo->Reserved = 0; 5624 if (conn->aapl_readdir_attr) { 5625 /* 5626 * READDIR_ATTR wire format, confirmed against reference server's 5627 * reference implementation marshalling (reference implementation behavior): 5628 * EaSize = max_access (expanded specific 5629 * rights, simplified to "grant all") 5630 * ShortNameLength = 24 (fixed; not 0, despite the spec) 5631 * ShortName[0..7] = resource fork size (uint64 LE, 0 = no rfork) 5632 * ShortName[8..23] = compressed FinderInfo (type+creator+flags+ 5633 * ext_flags+date_added, 16 bytes LE; all 5634 * zeros means type=0/creator=0, i.e. use 5635 * the file extension for icon lookup) 5636 * Reserved2 = Unix mode bits (uint16 LE) 5637 * Reparse-point tag is indicated via ExtFileAttributes, not EaSize. 5638 * 5639 * V2 (conn->aapl_readdir_attr_v2): ShortNameLength+Reserved 5640 * are read as a single flags field instead of being ignored 5641 * -- see smb2pdu.h for the wire-format confirmation and 5642 * AAPL_READDIR_ATTR_V2_NO_XATTR's meaning. 5643 */ 5644 __le32 reparse_tag = 5645 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode); 5646 5647 if (reparse_tag) 5648 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE; 5649 /* 5650 * FILE_GENERIC_ALL_LE (0x10000000) is the raw 5651 * "generic all" meta-bit -- valid only in a 5652 * client's requested access mask, for the server 5653 * to expand. It has none of the specific FILE_* 5654 * rights bits set (FILE_LIST_DIRECTORY, FILE_TRAVERSE, 5655 * etc.), so reporting it here as max_access would make 5656 * macOS's bit-by-bit access checks fail on every 5657 * entry -> permanent "no entry" badges in Finder. 5658 * Report the actual expanded rights instead, same 5659 * as smb_map_generic_desired_access() does when 5660 * translating a client's GENERIC_ALL request. 5661 */ 5662 fibdinfo->EaSize = cpu_to_le32(GENERIC_ALL_FLAGS); 5663 /* 5664 * The spec says ShortNameLength should be 0 when 5665 * there's no short name; 24 here instead matches 5666 * reference implementation marshalling (reference 5667 * behavior) for server-to-server wire parity. 5668 * V2 repurposes it as a flags field that is 5669 * interpreted; V1 doesn't. Either value is safe 5670 * here, so keep 24 for parity. 5671 */ 5672 if (conn->aapl_readdir_attr_v2) { 5673 /* 5674 * V2 repurposes this field as flags (see comment 5675 * above) -- 24 is a V1-only convention that real 5676 * macOS clients ignore outright, so don't reuse it 5677 * here as a base value for a field V2 clients 5678 * actually interpret. 5679 */ 5680 fibdinfo->ShortNameLength = 0; 5681 if (!ksmbd_kstat->has_ads_stream) 5682 fibdinfo->ShortNameLength = AAPL_READDIR_ATTR_V2_NO_XATTR; 5683 } else { 5684 fibdinfo->ShortNameLength = 24; 5685 } 5686 memset(fibdinfo->ShortName, 0, sizeof(fibdinfo->ShortName)); 5687 fibdinfo->Reserved2 = cpu_to_le16(ksmbd_kstat->kstat->mode & 0xffff); 5688 } else { 5689 fibdinfo->EaSize = 5690 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode); 5691 if (fibdinfo->EaSize) 5692 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE; 5693 fibdinfo->Reserved2 = cpu_to_le16(0); 5694 } 5695 if (d_info->hide_dot_file && d_info->name[0] == '.') 5696 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5697 memcpy(fibdinfo->FileName, conv_name, conv_len); 5698 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5699 break; 5700 } 5701 case SMB_FIND_FILE_POSIX_INFO: 5702 { 5703 struct smb2_posix_info *posix_info; 5704 u64 time; 5705 5706 posix_info = (struct smb2_posix_info *)kstat; 5707 posix_info->Ignored = 0; 5708 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time); 5709 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime); 5710 posix_info->ChangeTime = cpu_to_le64(time); 5711 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime); 5712 posix_info->LastAccessTime = cpu_to_le64(time); 5713 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime); 5714 posix_info->LastWriteTime = cpu_to_le64(time); 5715 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size); 5716 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9); 5717 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev); 5718 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink); 5719 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777); 5720 switch (ksmbd_kstat->kstat->mode & S_IFMT) { 5721 case S_IFDIR: 5722 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT); 5723 break; 5724 case S_IFLNK: 5725 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT); 5726 break; 5727 case S_IFCHR: 5728 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT); 5729 break; 5730 case S_IFBLK: 5731 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT); 5732 break; 5733 case S_IFIFO: 5734 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT); 5735 break; 5736 case S_IFSOCK: 5737 posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT); 5738 } 5739 5740 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino); 5741 posix_info->DosAttributes = 5742 S_ISDIR(ksmbd_kstat->kstat->mode) ? 5743 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE; 5744 if (d_info->hide_dot_file && d_info->name[0] == '.') 5745 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE; 5746 /* 5747 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)). 5748 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) + 5749 * sub_auth(4 * 1(num_subauth)) + RID(4). 5750 */ 5751 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid), 5752 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]); 5753 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid), 5754 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]); 5755 memcpy(posix_info->name, conv_name, conv_len); 5756 posix_info->name_len = cpu_to_le32(conv_len); 5757 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset); 5758 break; 5759 } 5760 5761 } /* switch (info_level) */ 5762 5763 d_info->last_entry_offset = d_info->data_count; 5764 d_info->data_count += next_entry_offset; 5765 d_info->out_buf_len -= next_entry_offset; 5766 d_info->wptr += next_entry_offset; 5767 5768 ksmbd_debug(SMB, 5769 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n", 5770 info_level, d_info->out_buf_len, 5771 next_entry_offset, d_info->data_count); 5772 5773 free_conv_name: 5774 kfree(conv_name); 5775 return rc; 5776 } 5777 5778 struct smb2_query_dir_private { 5779 struct ksmbd_work *work; 5780 char *search_pattern; 5781 struct ksmbd_file *dir_fp; 5782 5783 struct ksmbd_dir_info *d_info; 5784 int info_level; 5785 }; 5786 5787 static int process_query_dir_entries(struct smb2_query_dir_private *priv) 5788 { 5789 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp); 5790 struct kstat kstat; 5791 struct ksmbd_kstat ksmbd_kstat; 5792 int rc; 5793 int i; 5794 5795 for (i = 0; i < priv->d_info->num_entry; i++) { 5796 struct dentry *dent; 5797 struct path path; 5798 5799 if (dentry_name(priv->d_info, priv->info_level)) 5800 return -EINVAL; 5801 5802 dent = lookup_one_unlocked(idmap, 5803 &QSTR_LEN(priv->d_info->name, 5804 priv->d_info->name_len), 5805 priv->dir_fp->filp->f_path.dentry); 5806 5807 if (IS_ERR(dent)) { 5808 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n", 5809 priv->d_info->name, 5810 PTR_ERR(dent)); 5811 continue; 5812 } 5813 if (unlikely(d_is_negative(dent))) { 5814 dput(dent); 5815 ksmbd_debug(SMB, "Negative dentry `%s'\n", 5816 priv->d_info->name); 5817 continue; 5818 } 5819 5820 if (test_share_config_flag(priv->work->tcon->share_conf, 5821 KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) { 5822 __le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE | 5823 FILE_READ_ATTRIBUTES_LE; 5824 5825 path.mnt = priv->dir_fp->filp->f_path.mnt; 5826 path.dentry = dent; 5827 rc = smb_check_perm_dacl(priv->work->conn, &path, 5828 &daccess, daccess, 5829 priv->work->sess->user->uid, 5830 true); 5831 if (rc) { 5832 dput(dent); 5833 continue; 5834 } 5835 } 5836 5837 ksmbd_kstat.kstat = &kstat; 5838 if (priv->info_level != FILE_NAMES_INFORMATION) { 5839 rc = ksmbd_vfs_fill_dentry_attrs(priv->work, 5840 idmap, 5841 dent, 5842 &ksmbd_kstat); 5843 if (rc) { 5844 dput(dent); 5845 continue; 5846 } 5847 } 5848 5849 rc = smb2_populate_readdir_entry(priv->work->conn, 5850 priv->info_level, 5851 priv->d_info, 5852 &ksmbd_kstat); 5853 dput(dent); 5854 if (rc) 5855 return rc; 5856 } 5857 return 0; 5858 } 5859 5860 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info, 5861 int info_level) 5862 { 5863 int struct_sz; 5864 int conv_len; 5865 int next_entry_offset; 5866 5867 struct_sz = readdir_info_level_struct_sz(info_level); 5868 if (struct_sz == -EOPNOTSUPP) 5869 return -EOPNOTSUPP; 5870 5871 conv_len = (d_info->name_len + 1) * 2; 5872 next_entry_offset = ALIGN(struct_sz + conv_len, 5873 KSMBD_DIR_INFO_ALIGNMENT); 5874 5875 if (next_entry_offset > d_info->out_buf_len) { 5876 d_info->out_buf_len = 0; 5877 return -ENOSPC; 5878 } 5879 5880 switch (info_level) { 5881 case FILE_FULL_DIRECTORY_INFORMATION: 5882 { 5883 FILE_FULL_DIRECTORY_INFO *ffdinfo; 5884 5885 ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr; 5886 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len); 5887 ffdinfo->FileName[d_info->name_len] = 0x00; 5888 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len); 5889 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5890 break; 5891 } 5892 case FILE_BOTH_DIRECTORY_INFORMATION: 5893 { 5894 FILE_BOTH_DIRECTORY_INFO *fbdinfo; 5895 5896 fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr; 5897 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len); 5898 fbdinfo->FileName[d_info->name_len] = 0x00; 5899 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len); 5900 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5901 break; 5902 } 5903 case FILE_DIRECTORY_INFORMATION: 5904 { 5905 FILE_DIRECTORY_INFO *fdinfo; 5906 5907 fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr; 5908 memcpy(fdinfo->FileName, d_info->name, d_info->name_len); 5909 fdinfo->FileName[d_info->name_len] = 0x00; 5910 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len); 5911 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5912 break; 5913 } 5914 case FILE_NAMES_INFORMATION: 5915 { 5916 struct file_names_info *fninfo; 5917 5918 fninfo = (struct file_names_info *)d_info->wptr; 5919 memcpy(fninfo->FileName, d_info->name, d_info->name_len); 5920 fninfo->FileName[d_info->name_len] = 0x00; 5921 fninfo->FileNameLength = cpu_to_le32(d_info->name_len); 5922 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5923 break; 5924 } 5925 case FILEID_FULL_DIRECTORY_INFORMATION: 5926 { 5927 FILE_ID_FULL_DIR_INFO *dinfo; 5928 5929 dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr; 5930 memcpy(dinfo->FileName, d_info->name, d_info->name_len); 5931 dinfo->FileName[d_info->name_len] = 0x00; 5932 dinfo->FileNameLength = cpu_to_le32(d_info->name_len); 5933 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5934 break; 5935 } 5936 case FILEID_BOTH_DIRECTORY_INFORMATION: 5937 { 5938 struct file_id_both_directory_info *fibdinfo; 5939 5940 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr; 5941 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len); 5942 fibdinfo->FileName[d_info->name_len] = 0x00; 5943 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len); 5944 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset); 5945 break; 5946 } 5947 case SMB_FIND_FILE_POSIX_INFO: 5948 { 5949 struct smb2_posix_info *posix_info; 5950 5951 posix_info = (struct smb2_posix_info *)d_info->wptr; 5952 memcpy(posix_info->name, d_info->name, d_info->name_len); 5953 posix_info->name[d_info->name_len] = 0x00; 5954 posix_info->name_len = cpu_to_le32(d_info->name_len); 5955 posix_info->NextEntryOffset = 5956 cpu_to_le32(next_entry_offset); 5957 break; 5958 } 5959 } /* switch (info_level) */ 5960 5961 d_info->num_entry++; 5962 d_info->out_buf_len -= next_entry_offset; 5963 d_info->wptr += next_entry_offset; 5964 return 0; 5965 } 5966 5967 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen, 5968 loff_t offset, u64 ino, unsigned int d_type) 5969 { 5970 struct ksmbd_readdir_data *buf; 5971 struct smb2_query_dir_private *priv; 5972 struct ksmbd_dir_info *d_info; 5973 int rc; 5974 5975 buf = container_of(ctx, struct ksmbd_readdir_data, ctx); 5976 priv = buf->private; 5977 d_info = priv->d_info; 5978 5979 /* dot and dotdot entries are already reserved */ 5980 if (!strcmp(".", name) || !strcmp("..", name)) 5981 return true; 5982 d_info->num_scan++; 5983 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name)) 5984 return true; 5985 if (!match_pattern(name, namlen, priv->search_pattern)) 5986 return true; 5987 5988 d_info->name = name; 5989 d_info->name_len = namlen; 5990 rc = reserve_populate_dentry(d_info, priv->info_level); 5991 if (rc) 5992 return false; 5993 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) 5994 d_info->out_buf_len = 0; 5995 return true; 5996 } 5997 5998 static int verify_info_level(int info_level) 5999 { 6000 switch (info_level) { 6001 case FILE_FULL_DIRECTORY_INFORMATION: 6002 case FILE_BOTH_DIRECTORY_INFORMATION: 6003 case FILE_DIRECTORY_INFORMATION: 6004 case FILE_NAMES_INFORMATION: 6005 case FILEID_FULL_DIRECTORY_INFORMATION: 6006 case FILEID_BOTH_DIRECTORY_INFORMATION: 6007 case SMB_FIND_FILE_POSIX_INFO: 6008 break; 6009 default: 6010 return -EOPNOTSUPP; 6011 } 6012 6013 return 0; 6014 } 6015 6016 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len) 6017 { 6018 int free_len; 6019 6020 free_len = (int)(work->response_sz - 6021 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len; 6022 return free_len; 6023 } 6024 6025 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work, 6026 unsigned short hdr2_len, 6027 unsigned int out_buf_len) 6028 { 6029 int free_len; 6030 6031 if (out_buf_len > work->conn->vals->max_trans_size) 6032 return -EINVAL; 6033 6034 free_len = smb2_resp_buf_len(work, hdr2_len); 6035 if (free_len < 0) 6036 return -EINVAL; 6037 6038 return min_t(int, out_buf_len, free_len); 6039 } 6040 6041 int smb2_query_dir(struct ksmbd_work *work) 6042 { 6043 struct ksmbd_conn *conn = work->conn; 6044 struct smb2_query_directory_req *req; 6045 struct smb2_query_directory_rsp *rsp; 6046 struct ksmbd_share_config *share = work->tcon->share_conf; 6047 struct ksmbd_file *dir_fp = NULL; 6048 struct ksmbd_dir_info d_info; 6049 int rc = 0; 6050 char *srch_ptr = NULL; 6051 unsigned char srch_flag; 6052 int buffer_sz; 6053 struct smb2_query_dir_private query_dir_private = {NULL, }; 6054 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 6055 6056 ksmbd_debug(SMB, "Received smb2 query directory request\n"); 6057 6058 WORK_BUFFERS(work, req, rsp); 6059 6060 if (smb2_compound_has_failed(work, &rsp->hdr)) 6061 return -EACCES; 6062 6063 if (work->next_smb2_rcv_hdr_off && 6064 !has_file_id(req->VolatileFileId)) { 6065 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 6066 work->compound_fid); 6067 id = work->compound_fid; 6068 pid = work->compound_pfid; 6069 } 6070 6071 if (!has_file_id(id)) { 6072 id = req->VolatileFileId; 6073 pid = req->PersistentFileId; 6074 } 6075 6076 if (ksmbd_override_fsids(work)) { 6077 rsp->hdr.Status = STATUS_NO_MEMORY; 6078 smb2_set_err_rsp(work); 6079 return -ENOMEM; 6080 } 6081 6082 rc = verify_info_level(req->FileInformationClass); 6083 if (rc) { 6084 rc = -EFAULT; 6085 goto err_out2; 6086 } 6087 6088 dir_fp = ksmbd_lookup_fd_slow(work, id, pid); 6089 if (!dir_fp) { 6090 rc = -EBADF; 6091 goto err_out2; 6092 } 6093 6094 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) || 6095 inode_permission(file_mnt_idmap(dir_fp->filp), 6096 file_inode(dir_fp->filp), 6097 MAY_READ | MAY_EXEC)) { 6098 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp); 6099 rc = -EACCES; 6100 goto err_out2; 6101 } 6102 6103 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) { 6104 pr_err("can't do query dir for a file\n"); 6105 rc = -EINVAL; 6106 goto err_out2; 6107 } 6108 6109 srch_flag = req->Flags; 6110 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset), 6111 le16_to_cpu(req->FileNameLength), 1, 6112 conn->local_nls); 6113 if (IS_ERR(srch_ptr)) { 6114 ksmbd_debug(SMB, "Search Pattern not found\n"); 6115 rc = -EINVAL; 6116 goto err_out2; 6117 } else { 6118 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr); 6119 } 6120 6121 mutex_lock(&dir_fp->readdir_lock); 6122 6123 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) { 6124 ksmbd_debug(SMB, "Restart directory scan\n"); 6125 generic_file_llseek(dir_fp->filp, 0, SEEK_SET); 6126 } 6127 6128 memset(&d_info, 0, sizeof(struct ksmbd_dir_info)); 6129 d_info.wptr = (char *)rsp->Buffer; 6130 d_info.rptr = (char *)rsp->Buffer; 6131 d_info.out_buf_len = 6132 smb2_calc_max_out_buf_len(work, 6133 offsetof(struct smb2_query_directory_rsp, Buffer), 6134 le32_to_cpu(req->OutputBufferLength)); 6135 if (d_info.out_buf_len < 0) { 6136 rc = -EINVAL; 6137 goto err_out; 6138 } 6139 d_info.flags = srch_flag; 6140 6141 /* 6142 * reserve dot and dotdot entries in head of buffer 6143 * in first response 6144 */ 6145 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass, 6146 dir_fp, &d_info, srch_ptr, 6147 smb2_populate_readdir_entry); 6148 if (rc == -ENOSPC) 6149 rc = 0; 6150 else if (rc) 6151 goto err_out; 6152 6153 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES)) 6154 d_info.hide_dot_file = true; 6155 6156 buffer_sz = d_info.out_buf_len; 6157 d_info.rptr = d_info.wptr; 6158 query_dir_private.work = work; 6159 query_dir_private.search_pattern = srch_ptr; 6160 query_dir_private.dir_fp = dir_fp; 6161 query_dir_private.d_info = &d_info; 6162 query_dir_private.info_level = req->FileInformationClass; 6163 dir_fp->readdir_data.private = &query_dir_private; 6164 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir); 6165 again: 6166 d_info.num_scan = 0; 6167 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx); 6168 /* 6169 * num_entry can be 0 if the directory iteration stops before reaching 6170 * the end of the directory and no file is matched with the search 6171 * pattern. 6172 */ 6173 if (rc >= 0 && !d_info.num_entry && d_info.num_scan && 6174 d_info.out_buf_len > 0) 6175 goto again; 6176 /* 6177 * req->OutputBufferLength is too small to contain even one entry. 6178 * In this case, it immediately returns OutputBufferLength 0 to client. 6179 */ 6180 if (!d_info.out_buf_len && !d_info.num_entry) 6181 goto no_buf_len; 6182 if (rc > 0 || rc == -ENOSPC) 6183 rc = 0; 6184 else if (rc) 6185 goto err_out; 6186 6187 d_info.wptr = d_info.rptr; 6188 d_info.out_buf_len = buffer_sz; 6189 rc = process_query_dir_entries(&query_dir_private); 6190 if (rc) 6191 goto err_out; 6192 6193 if (!d_info.data_count && d_info.out_buf_len >= 0) { 6194 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) { 6195 rsp->hdr.Status = STATUS_NO_SUCH_FILE; 6196 } else { 6197 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0; 6198 rsp->hdr.Status = STATUS_NO_MORE_FILES; 6199 } 6200 rsp->StructureSize = cpu_to_le16(9); 6201 rsp->OutputBufferOffset = cpu_to_le16(0); 6202 rsp->OutputBufferLength = cpu_to_le32(0); 6203 rsp->Buffer[0] = 0; 6204 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, 6205 offsetof(struct smb2_query_directory_rsp, Buffer) 6206 + 1); 6207 if (rc) 6208 goto err_out; 6209 } else { 6210 no_buf_len: 6211 ((FILE_DIRECTORY_INFO *) 6212 ((char *)rsp->Buffer + d_info.last_entry_offset)) 6213 ->NextEntryOffset = 0; 6214 if (d_info.data_count >= d_info.last_entry_off_align) 6215 d_info.data_count -= d_info.last_entry_off_align; 6216 6217 rsp->StructureSize = cpu_to_le16(9); 6218 rsp->OutputBufferOffset = cpu_to_le16(72); 6219 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count); 6220 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, 6221 offsetof(struct smb2_query_directory_rsp, Buffer) + 6222 d_info.data_count); 6223 if (rc) 6224 goto err_out; 6225 } 6226 6227 mutex_unlock(&dir_fp->readdir_lock); 6228 kfree(srch_ptr); 6229 ksmbd_fd_put(work, dir_fp); 6230 ksmbd_revert_fsids(work); 6231 return 0; 6232 6233 err_out: 6234 pr_err("error while processing smb2 query dir rc = %d\n", rc); 6235 mutex_unlock(&dir_fp->readdir_lock); 6236 kfree(srch_ptr); 6237 6238 err_out2: 6239 if (rc == -EINVAL) 6240 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 6241 else if (rc == -EACCES) 6242 rsp->hdr.Status = STATUS_ACCESS_DENIED; 6243 else if (rc == -ENOENT) 6244 rsp->hdr.Status = STATUS_NO_SUCH_FILE; 6245 else if (rc == -EBADF) 6246 rsp->hdr.Status = STATUS_FILE_CLOSED; 6247 else if (rc == -ENOMEM) 6248 rsp->hdr.Status = STATUS_NO_MEMORY; 6249 else if (rc == -EFAULT) 6250 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS; 6251 else if (rc == -EIO) 6252 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR; 6253 if (!rsp->hdr.Status) 6254 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 6255 6256 smb2_set_err_rsp(work); 6257 ksmbd_fd_put(work, dir_fp); 6258 ksmbd_revert_fsids(work); 6259 return rc; 6260 } 6261 6262 /** 6263 * buffer_check_err() - helper function to check buffer errors 6264 * @reqOutputBufferLength: max buffer length expected in command response 6265 * @fixed_len: minimum fixed response length 6266 * @rsp: query info response buffer contains output buffer length 6267 * @rsp_org: base response buffer pointer in case of chained response 6268 * 6269 * Return: 0 on success, otherwise error 6270 */ 6271 static int buffer_check_err(int reqOutputBufferLength, 6272 unsigned int fixed_len, 6273 struct smb2_query_info_rsp *rsp, 6274 void *rsp_org) 6275 { 6276 unsigned int output_len = le32_to_cpu(rsp->OutputBufferLength); 6277 6278 if (reqOutputBufferLength < fixed_len) { 6279 pr_err("Invalid Buffer Size Requested\n"); 6280 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH; 6281 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr)); 6282 return -EINVAL; 6283 } 6284 6285 if (reqOutputBufferLength < output_len) { 6286 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; 6287 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength); 6288 } 6289 return 0; 6290 } 6291 6292 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp, 6293 void *rsp_org) 6294 { 6295 struct smb2_file_standard_info *sinfo; 6296 6297 sinfo = (struct smb2_file_standard_info *)rsp->Buffer; 6298 6299 sinfo->AllocationSize = cpu_to_le64(4096); 6300 sinfo->EndOfFile = cpu_to_le64(0); 6301 sinfo->NumberOfLinks = cpu_to_le32(1); 6302 sinfo->DeletePending = 1; 6303 sinfo->Directory = 0; 6304 rsp->OutputBufferLength = 6305 cpu_to_le32(sizeof(struct smb2_file_standard_info)); 6306 } 6307 6308 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num, 6309 void *rsp_org) 6310 { 6311 struct smb2_file_internal_info *file_info; 6312 6313 file_info = (struct smb2_file_internal_info *)rsp->Buffer; 6314 6315 /* any unique number */ 6316 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63)); 6317 rsp->OutputBufferLength = 6318 cpu_to_le32(sizeof(struct smb2_file_internal_info)); 6319 } 6320 6321 static int smb2_get_info_file_pipe(struct ksmbd_session *sess, 6322 struct smb2_query_info_req *req, 6323 struct smb2_query_info_rsp *rsp, 6324 void *rsp_org) 6325 { 6326 u64 id; 6327 int rc; 6328 6329 /* 6330 * Windows can sometime send query file info request on 6331 * pipe without opening it, checking error condition here 6332 */ 6333 id = req->VolatileFileId; 6334 6335 lockdep_assert_not_held(&sess->rpc_lock); 6336 6337 down_read(&sess->rpc_lock); 6338 if (!ksmbd_session_rpc_method(sess, id)) { 6339 up_read(&sess->rpc_lock); 6340 return -ENOENT; 6341 } 6342 up_read(&sess->rpc_lock); 6343 6344 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n", 6345 req->FileInfoClass, req->VolatileFileId); 6346 6347 switch (req->FileInfoClass) { 6348 case FILE_STANDARD_INFORMATION: 6349 get_standard_info_pipe(rsp, rsp_org); 6350 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength), 6351 le32_to_cpu(rsp->OutputBufferLength), 6352 rsp, rsp_org); 6353 break; 6354 case FILE_INTERNAL_INFORMATION: 6355 get_internal_info_pipe(rsp, id, rsp_org); 6356 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength), 6357 le32_to_cpu(rsp->OutputBufferLength), 6358 rsp, rsp_org); 6359 break; 6360 default: 6361 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n", 6362 req->FileInfoClass); 6363 rc = -EOPNOTSUPP; 6364 } 6365 return rc; 6366 } 6367 6368 /** 6369 * smb2_get_ea() - handler for smb2 get extended attribute command 6370 * @work: smb work containing query info command buffer 6371 * @fp: ksmbd_file pointer 6372 * @req: get extended attribute request 6373 * @rsp: response buffer pointer 6374 * @rsp_org: base response buffer pointer in case of chained response 6375 * 6376 * Return: 0 on success, otherwise error 6377 */ 6378 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp, 6379 struct smb2_query_info_req *req, 6380 struct smb2_query_info_rsp *rsp, void *rsp_org) 6381 { 6382 struct smb2_ea_info *eainfo, *prev_eainfo; 6383 char *name, *ptr, *xattr_list = NULL, *buf; 6384 int rc, name_len, value_len, xattr_list_len, idx; 6385 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0; 6386 struct smb2_ea_info_req *ea_req = NULL; 6387 const struct path *path; 6388 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp); 6389 6390 if (!(fp->daccess & FILE_READ_EA_LE)) { 6391 pr_err("Not permitted to read ext attr : 0x%x\n", 6392 fp->daccess); 6393 return -EACCES; 6394 } 6395 6396 path = &fp->filp->f_path; 6397 /* single EA entry is requested with given user.* name */ 6398 if (req->InputBufferLength) { 6399 if (le32_to_cpu(req->InputBufferLength) <= 6400 sizeof(struct smb2_ea_info_req)) 6401 return -EINVAL; 6402 6403 ea_req = (struct smb2_ea_info_req *)((char *)req + 6404 le16_to_cpu(req->InputBufferOffset)); 6405 6406 if (le32_to_cpu(req->InputBufferLength) < 6407 offsetof(struct smb2_ea_info_req, name) + 6408 ea_req->EaNameLength) 6409 return -EINVAL; 6410 } else { 6411 /* need to send all EAs, if no specific EA is requested*/ 6412 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY) 6413 ksmbd_debug(SMB, 6414 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n", 6415 le32_to_cpu(req->Flags)); 6416 } 6417 6418 buf_free_len = 6419 smb2_calc_max_out_buf_len(work, 6420 offsetof(struct smb2_query_info_rsp, Buffer), 6421 le32_to_cpu(req->OutputBufferLength)); 6422 if (buf_free_len < 0) 6423 return -EINVAL; 6424 6425 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list); 6426 if (rc < 0) { 6427 rsp->hdr.Status = STATUS_INVALID_HANDLE; 6428 goto out; 6429 } else if (!rc) { /* there is no EA in the file */ 6430 ksmbd_debug(SMB, "no ea data in the file\n"); 6431 goto done; 6432 } 6433 xattr_list_len = rc; 6434 6435 ptr = (char *)rsp->Buffer; 6436 eainfo = (struct smb2_ea_info *)ptr; 6437 prev_eainfo = eainfo; 6438 idx = 0; 6439 6440 while (idx < xattr_list_len) { 6441 name = xattr_list + idx; 6442 name_len = strlen(name); 6443 6444 ksmbd_debug(SMB, "%s, len %d\n", name, name_len); 6445 idx += name_len + 1; 6446 6447 /* 6448 * CIFS does not support EA other than user.* namespace, 6449 * still keep the framework generic, to list other attrs 6450 * in future. 6451 */ 6452 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)) 6453 continue; 6454 6455 if (req->InputBufferLength && 6456 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name, 6457 ea_req->EaNameLength)) 6458 continue; 6459 6460 if (smb2_is_private_ea(&name[XATTR_USER_PREFIX_LEN], 6461 name_len - XATTR_USER_PREFIX_LEN)) 6462 continue; 6463 6464 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)) 6465 name_len -= XATTR_USER_PREFIX_LEN; 6466 6467 ptr = eainfo->name + name_len + 1; 6468 buf_free_len -= (offsetof(struct smb2_ea_info, name) + 6469 name_len + 1); 6470 /* bailout if xattr can't fit in buf_free_len */ 6471 value_len = ksmbd_vfs_getxattr(idmap, path->dentry, 6472 name, &buf); 6473 if (value_len <= 0) { 6474 rc = -ENOENT; 6475 rsp->hdr.Status = STATUS_INVALID_HANDLE; 6476 goto out; 6477 } 6478 6479 buf_free_len -= value_len; 6480 if (buf_free_len < 0) { 6481 kfree(buf); 6482 break; 6483 } 6484 6485 memcpy(ptr, buf, value_len); 6486 kfree(buf); 6487 6488 ptr += value_len; 6489 eainfo->Flags = 0; 6490 eainfo->EaNameLength = name_len; 6491 6492 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)) 6493 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN], 6494 name_len); 6495 else 6496 memcpy(eainfo->name, name, name_len); 6497 6498 eainfo->name[name_len] = '\0'; 6499 eainfo->EaValueLength = cpu_to_le16(value_len); 6500 next_offset = offsetof(struct smb2_ea_info, name) + 6501 name_len + 1 + value_len; 6502 6503 /* align next xattr entry at 4 byte bundary */ 6504 alignment_bytes = ((next_offset + 3) & ~3) - next_offset; 6505 if (alignment_bytes) { 6506 if (buf_free_len < alignment_bytes) 6507 break; 6508 memset(ptr, '\0', alignment_bytes); 6509 ptr += alignment_bytes; 6510 next_offset += alignment_bytes; 6511 buf_free_len -= alignment_bytes; 6512 } 6513 eainfo->NextEntryOffset = cpu_to_le32(next_offset); 6514 prev_eainfo = eainfo; 6515 eainfo = (struct smb2_ea_info *)ptr; 6516 rsp_data_cnt += next_offset; 6517 6518 if (req->InputBufferLength) { 6519 ksmbd_debug(SMB, "single entry requested\n"); 6520 break; 6521 } 6522 } 6523 6524 /* no more ea entries */ 6525 prev_eainfo->NextEntryOffset = 0; 6526 done: 6527 rc = 0; 6528 if (rsp_data_cnt == 0) 6529 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE; 6530 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt); 6531 out: 6532 kvfree(xattr_list); 6533 return rc; 6534 } 6535 6536 static void get_file_access_info(struct smb2_query_info_rsp *rsp, 6537 struct ksmbd_file *fp, void *rsp_org) 6538 { 6539 struct smb2_file_access_info *file_info; 6540 6541 file_info = (struct smb2_file_access_info *)rsp->Buffer; 6542 file_info->AccessFlags = fp->daccess; 6543 rsp->OutputBufferLength = 6544 cpu_to_le32(sizeof(struct smb2_file_access_info)); 6545 } 6546 6547 static int get_file_basic_info(struct smb2_query_info_rsp *rsp, 6548 struct ksmbd_file *fp, void *rsp_org) 6549 { 6550 struct file_basic_info *basic_info; 6551 struct kstat stat; 6552 u64 time; 6553 int ret; 6554 6555 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) { 6556 pr_err("no right to read the attributes : 0x%x\n", 6557 fp->daccess); 6558 return -EACCES; 6559 } 6560 6561 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 6562 AT_STATX_SYNC_AS_STAT); 6563 if (ret) 6564 return ret; 6565 6566 basic_info = (struct file_basic_info *)rsp->Buffer; 6567 basic_info->CreationTime = cpu_to_le64(fp->create_time); 6568 time = ksmbd_UnixTimeToNT(stat.atime); 6569 basic_info->LastAccessTime = cpu_to_le64(time); 6570 time = ksmbd_UnixTimeToNT(stat.mtime); 6571 basic_info->LastWriteTime = cpu_to_le64(time); 6572 basic_info->ChangeTime = cpu_to_le64(fp->change_time); 6573 basic_info->Attributes = fp->f_ci->m_fattr; 6574 basic_info->Pad = 0; 6575 rsp->OutputBufferLength = 6576 cpu_to_le32(sizeof(struct file_basic_info)); 6577 return 0; 6578 } 6579 6580 static int get_file_allocation_stat(struct ksmbd_file *fp, struct kstat *stat) 6581 { 6582 int ret; 6583 6584 /* 6585 * Buffered writes can leave delayed allocation in a state where two 6586 * consecutive queries report different block counts even when the 6587 * second write only overwrites the first one. Complete writeback before 6588 * reporting the filesystem allocation for an ordinary open. 6589 */ 6590 if (!fp->allocation_size_set) { 6591 ret = file_write_and_wait(fp->filp); 6592 if (ret) 6593 return ret; 6594 } 6595 6596 ret = vfs_getattr(&fp->filp->f_path, stat, STATX_BASIC_STATS, 6597 AT_STATX_SYNC_AS_STAT); 6598 if (!ret && !fp->allocation_size_set) 6599 fp->allocation_size = S_ISDIR(stat->mode) ? 0 : stat->blocks << 9; 6600 6601 return ret; 6602 } 6603 6604 static int get_file_standard_info(struct smb2_query_info_rsp *rsp, 6605 struct ksmbd_file *fp, void *rsp_org) 6606 { 6607 struct smb2_file_standard_info *sinfo; 6608 unsigned int delete_pending; 6609 struct kstat stat; 6610 int ret; 6611 6612 ret = get_file_allocation_stat(fp, &stat); 6613 if (ret) 6614 return ret; 6615 6616 sinfo = (struct smb2_file_standard_info *)rsp->Buffer; 6617 delete_pending = ksmbd_inode_pending_delete(fp); 6618 6619 if (ksmbd_stream_fd(fp) == false) { 6620 sinfo->AllocationSize = cpu_to_le64(fp->allocation_size); 6621 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size); 6622 } else { 6623 loff_t seof = ksmbd_stream_eof(fp); 6624 6625 sinfo->AllocationSize = cpu_to_le64((u64)seof); 6626 sinfo->EndOfFile = cpu_to_le64((u64)seof); 6627 } 6628 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending); 6629 sinfo->DeletePending = delete_pending; 6630 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0; 6631 rsp->OutputBufferLength = 6632 cpu_to_le32(sizeof(struct smb2_file_standard_info)); 6633 6634 return 0; 6635 } 6636 6637 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp, 6638 void *rsp_org) 6639 { 6640 struct smb2_file_alignment_info *file_info; 6641 6642 file_info = (struct smb2_file_alignment_info *)rsp->Buffer; 6643 file_info->AlignmentRequirement = 0; 6644 rsp->OutputBufferLength = 6645 cpu_to_le32(sizeof(struct smb2_file_alignment_info)); 6646 } 6647 6648 static int get_file_all_info(struct ksmbd_work *work, 6649 struct smb2_query_info_rsp *rsp, 6650 struct ksmbd_file *fp, 6651 void *rsp_org) 6652 { 6653 struct ksmbd_conn *conn = work->conn; 6654 struct smb2_file_all_info *file_info; 6655 unsigned int delete_pending; 6656 struct kstat stat; 6657 int conv_len; 6658 char *filename; 6659 u64 time; 6660 int ret, buf_free_len, filename_len; 6661 6662 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) { 6663 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n", 6664 fp->daccess); 6665 return -EACCES; 6666 } 6667 6668 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path); 6669 if (IS_ERR(filename)) 6670 return PTR_ERR(filename); 6671 6672 filename_len = strlen(filename); 6673 buf_free_len = smb2_resp_buf_len(work, 6674 offsetof(struct smb2_query_info_rsp, Buffer) + 6675 offsetof(struct smb2_file_all_info, FileName)); 6676 if (buf_free_len < (filename_len + 1) * 2) { 6677 kfree(filename); 6678 return -EINVAL; 6679 } 6680 6681 ret = get_file_allocation_stat(fp, &stat); 6682 if (ret) { 6683 kfree(filename); 6684 return ret; 6685 } 6686 6687 ksmbd_debug(SMB, "filename = %s\n", filename); 6688 delete_pending = ksmbd_inode_pending_delete(fp); 6689 file_info = (struct smb2_file_all_info *)rsp->Buffer; 6690 6691 file_info->CreationTime = cpu_to_le64(fp->create_time); 6692 time = ksmbd_UnixTimeToNT(stat.atime); 6693 file_info->LastAccessTime = cpu_to_le64(time); 6694 time = ksmbd_UnixTimeToNT(stat.mtime); 6695 file_info->LastWriteTime = cpu_to_le64(time); 6696 file_info->ChangeTime = cpu_to_le64(fp->change_time); 6697 file_info->Attributes = fp->f_ci->m_fattr; 6698 file_info->Pad1 = 0; 6699 if (ksmbd_stream_fd(fp) == false) { 6700 file_info->AllocationSize = cpu_to_le64(fp->allocation_size); 6701 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size); 6702 } else { 6703 loff_t seof = ksmbd_stream_eof(fp); 6704 6705 file_info->AllocationSize = cpu_to_le64((u64)seof); 6706 file_info->EndOfFile = cpu_to_le64((u64)seof); 6707 } 6708 file_info->NumberOfLinks = 6709 cpu_to_le32(get_nlink(&stat) - delete_pending); 6710 file_info->DeletePending = delete_pending; 6711 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0; 6712 file_info->Pad2 = 0; 6713 file_info->IndexNumber = cpu_to_le64(stat.ino); 6714 file_info->EASize = 0; 6715 file_info->AccessFlags = fp->daccess; 6716 if (ksmbd_stream_fd(fp) == false) 6717 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos); 6718 else 6719 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos); 6720 file_info->Mode = fp->coption; 6721 file_info->AlignmentRequirement = 0; 6722 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename, 6723 min(filename_len, PATH_MAX), 6724 conn->local_nls, 0); 6725 conv_len *= 2; 6726 file_info->FileNameLength = cpu_to_le32(conv_len); 6727 rsp->OutputBufferLength = 6728 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1); 6729 kfree(filename); 6730 return 0; 6731 } 6732 6733 static void get_file_alternate_info(struct ksmbd_work *work, 6734 struct smb2_query_info_rsp *rsp, 6735 struct ksmbd_file *fp, 6736 void *rsp_org) 6737 { 6738 struct ksmbd_conn *conn = work->conn; 6739 struct smb2_file_alt_name_info *file_info; 6740 struct dentry *dentry = fp->filp->f_path.dentry; 6741 int conv_len; 6742 6743 spin_lock(&dentry->d_lock); 6744 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer; 6745 conv_len = ksmbd_extract_shortname(conn, 6746 dentry->d_name.name, 6747 file_info->FileName); 6748 spin_unlock(&dentry->d_lock); 6749 file_info->FileNameLength = cpu_to_le32(conv_len); 6750 rsp->OutputBufferLength = 6751 cpu_to_le32(struct_size(file_info, FileName, conv_len)); 6752 } 6753 6754 static char *smb2_get_normalized_stream_name(struct ksmbd_file *fp) 6755 { 6756 char *name, *stream_name = NULL, *xattr_list = NULL; 6757 ssize_t xattr_list_len; 6758 6759 if (!ksmbd_stream_fd(fp)) 6760 return NULL; 6761 6762 xattr_list_len = ksmbd_vfs_listxattr(fp->filp->f_path.dentry, 6763 &xattr_list); 6764 if (xattr_list_len <= 0) 6765 goto out; 6766 6767 for (name = xattr_list; name - xattr_list < xattr_list_len; 6768 name += strlen(name) + 1) { 6769 char *type; 6770 6771 if (strlen(name) + 1 != fp->stream.size || 6772 strncasecmp(name, fp->stream.name, fp->stream.size - 1)) 6773 continue; 6774 6775 name += XATTR_NAME_STREAM_LEN; 6776 type = strrchr(name, ':'); 6777 if (type) 6778 stream_name = kstrndup(name, type - name, 6779 KSMBD_DEFAULT_GFP); 6780 break; 6781 } 6782 out: 6783 kvfree(xattr_list); 6784 return stream_name; 6785 } 6786 6787 static int get_file_normalized_name_info(struct ksmbd_work *work, 6788 struct smb2_query_info_rsp *rsp, 6789 struct ksmbd_file *fp) 6790 { 6791 struct smb2_file_alt_name_info *file_info; 6792 char *filename, *normalized, *stream_name; 6793 int buf_free_len, conv_len, filename_len; 6794 6795 if (work->conn->dialect < SMB311_PROT_ID) { 6796 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 6797 return -EOPNOTSUPP; 6798 } 6799 6800 filename = convert_to_nt_pathname(work->tcon->share_conf, 6801 &fp->filp->f_path); 6802 if (IS_ERR(filename)) 6803 return PTR_ERR(filename); 6804 if (filename[0] == '\\') 6805 memmove(filename, filename + 1, strlen(filename)); 6806 6807 stream_name = smb2_get_normalized_stream_name(fp); 6808 normalized = kasprintf(KSMBD_DEFAULT_GFP, "%s%s%s", filename, 6809 stream_name ? ":" : "", 6810 stream_name ? stream_name : ""); 6811 kfree(stream_name); 6812 kfree(filename); 6813 if (!normalized) 6814 return -ENOMEM; 6815 6816 filename_len = strlen(normalized); 6817 buf_free_len = smb2_resp_buf_len(work, sizeof(*rsp) + 6818 sizeof(*file_info)); 6819 if (buf_free_len < 0 || 6820 (size_t)buf_free_len < (filename_len + 1) * sizeof(__le16)) { 6821 kfree(normalized); 6822 return -EINVAL; 6823 } 6824 6825 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer; 6826 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, 6827 normalized, filename_len, 6828 work->conn->local_nls, 0); 6829 kfree(normalized); 6830 conv_len *= 2; 6831 file_info->FileNameLength = cpu_to_le32(conv_len); 6832 rsp->OutputBufferLength = cpu_to_le32(sizeof(*file_info) + conv_len); 6833 return 0; 6834 } 6835 6836 static int get_file_stream_info(struct ksmbd_work *work, 6837 struct smb2_query_info_rsp *rsp, 6838 struct ksmbd_file *fp, 6839 void *rsp_org) 6840 { 6841 struct ksmbd_conn *conn = work->conn; 6842 struct smb2_file_stream_info *file_info; 6843 char *stream_name, *xattr_list = NULL, *stream_buf; 6844 struct kstat stat; 6845 const struct path *path = &fp->filp->f_path; 6846 ssize_t xattr_list_len; 6847 ssize_t slen; 6848 loff_t ssize; 6849 int nbytes = 0, streamlen, stream_name_len, next, idx = 0; 6850 int buf_free_len; 6851 int ret; 6852 6853 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 6854 AT_STATX_SYNC_AS_STAT); 6855 if (ret) 6856 return ret; 6857 6858 file_info = (struct smb2_file_stream_info *)rsp->Buffer; 6859 6860 buf_free_len = smb2_resp_buf_len(work, 6861 offsetof(struct smb2_query_info_rsp, Buffer)); 6862 if (buf_free_len < 0) 6863 goto out; 6864 6865 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list); 6866 if (xattr_list_len < 0) { 6867 goto out; 6868 } else if (!xattr_list_len) { 6869 ksmbd_debug(SMB, "empty xattr in the file\n"); 6870 goto out; 6871 } 6872 6873 while (idx < xattr_list_len) { 6874 stream_name = xattr_list + idx; 6875 streamlen = strlen(stream_name); 6876 idx += streamlen + 1; 6877 6878 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen); 6879 6880 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN], 6881 STREAM_PREFIX, STREAM_PREFIX_LEN)) 6882 continue; 6883 6884 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN + 6885 STREAM_PREFIX_LEN); 6886 streamlen = stream_name_len; 6887 6888 /* plus : size */ 6889 streamlen += 1; 6890 stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP); 6891 if (!stream_buf) 6892 break; 6893 6894 streamlen = snprintf(stream_buf, streamlen + 1, 6895 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]); 6896 6897 next = sizeof(struct smb2_file_stream_info) + streamlen * 2; 6898 if (next > buf_free_len) { 6899 kfree(stream_buf); 6900 break; 6901 } 6902 6903 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes]; 6904 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName, 6905 stream_buf, streamlen, 6906 conn->local_nls, 0); 6907 streamlen *= 2; 6908 kfree(stream_buf); 6909 file_info->StreamNameLength = cpu_to_le32(streamlen); 6910 /* 6911 * stream_name_len is the byte length of the xattr's *name*, 6912 * not its value -- same class of bug ksmbd_stream_eof() 6913 * (smb2pdu.c) already fixes for EndOfFile/AllocationSize on 6914 * a stream handle; this enumeration path needs the same 6915 * real xattr value length, not the name length reused as a 6916 * size. 6917 */ 6918 slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp), 6919 path->dentry, stream_name, 6920 strlen(stream_name) + 1); 6921 ssize = slen < 0 ? 0 : (loff_t)slen; 6922 file_info->StreamSize = cpu_to_le64(ssize); 6923 file_info->StreamAllocationSize = cpu_to_le64(ssize); 6924 6925 nbytes += next; 6926 buf_free_len -= next; 6927 file_info->NextEntryOffset = cpu_to_le32(next); 6928 } 6929 6930 out: 6931 if (!S_ISDIR(stat.mode) && 6932 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) { 6933 file_info = (struct smb2_file_stream_info *) 6934 &rsp->Buffer[nbytes]; 6935 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName, 6936 "::$DATA", 7, conn->local_nls, 0); 6937 streamlen *= 2; 6938 file_info->StreamNameLength = cpu_to_le32(streamlen); 6939 file_info->StreamSize = cpu_to_le64(stat.size); 6940 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9); 6941 nbytes += sizeof(struct smb2_file_stream_info) + streamlen; 6942 } 6943 6944 /* last entry offset should be 0 */ 6945 file_info->NextEntryOffset = 0; 6946 kvfree(xattr_list); 6947 6948 rsp->OutputBufferLength = cpu_to_le32(nbytes); 6949 6950 return 0; 6951 } 6952 6953 static int get_file_internal_info(struct smb2_query_info_rsp *rsp, 6954 struct ksmbd_file *fp, void *rsp_org) 6955 { 6956 struct smb2_file_internal_info *file_info; 6957 struct kstat stat; 6958 int ret; 6959 6960 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 6961 AT_STATX_SYNC_AS_STAT); 6962 if (ret) 6963 return ret; 6964 6965 file_info = (struct smb2_file_internal_info *)rsp->Buffer; 6966 file_info->IndexNumber = cpu_to_le64(stat.ino); 6967 rsp->OutputBufferLength = 6968 cpu_to_le32(sizeof(struct smb2_file_internal_info)); 6969 6970 return 0; 6971 } 6972 6973 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp, 6974 struct ksmbd_file *fp, void *rsp_org) 6975 { 6976 struct smb2_file_network_open_info *file_info; 6977 struct kstat stat; 6978 u64 time; 6979 int ret; 6980 6981 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) { 6982 pr_err("no right to read the attributes : 0x%x\n", 6983 fp->daccess); 6984 return -EACCES; 6985 } 6986 6987 ret = get_file_allocation_stat(fp, &stat); 6988 if (ret) 6989 return ret; 6990 6991 file_info = (struct smb2_file_network_open_info *)rsp->Buffer; 6992 6993 file_info->CreationTime = cpu_to_le64(fp->create_time); 6994 time = ksmbd_UnixTimeToNT(stat.atime); 6995 file_info->LastAccessTime = cpu_to_le64(time); 6996 time = ksmbd_UnixTimeToNT(stat.mtime); 6997 file_info->LastWriteTime = cpu_to_le64(time); 6998 file_info->ChangeTime = cpu_to_le64(fp->change_time); 6999 file_info->Attributes = fp->f_ci->m_fattr; 7000 if (ksmbd_stream_fd(fp) == false) { 7001 file_info->AllocationSize = cpu_to_le64(fp->allocation_size); 7002 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size); 7003 } else { 7004 loff_t seof = ksmbd_stream_eof(fp); 7005 7006 file_info->AllocationSize = cpu_to_le64((u64)seof); 7007 file_info->EndOfFile = cpu_to_le64((u64)seof); 7008 } 7009 file_info->Reserved = cpu_to_le32(0); 7010 rsp->OutputBufferLength = 7011 cpu_to_le32(sizeof(struct smb2_file_network_open_info)); 7012 return 0; 7013 } 7014 7015 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org) 7016 { 7017 struct smb2_file_ea_info *file_info; 7018 7019 file_info = (struct smb2_file_ea_info *)rsp->Buffer; 7020 file_info->EASize = 0; 7021 rsp->OutputBufferLength = 7022 cpu_to_le32(sizeof(struct smb2_file_ea_info)); 7023 } 7024 7025 static void get_file_position_info(struct smb2_query_info_rsp *rsp, 7026 struct ksmbd_file *fp, void *rsp_org) 7027 { 7028 struct smb2_file_pos_info *file_info; 7029 7030 file_info = (struct smb2_file_pos_info *)rsp->Buffer; 7031 if (ksmbd_stream_fd(fp) == false) 7032 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos); 7033 else 7034 file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos); 7035 7036 rsp->OutputBufferLength = 7037 cpu_to_le32(sizeof(struct smb2_file_pos_info)); 7038 } 7039 7040 static void get_file_mode_info(struct smb2_query_info_rsp *rsp, 7041 struct ksmbd_file *fp, void *rsp_org) 7042 { 7043 struct smb2_file_mode_info *file_info; 7044 7045 file_info = (struct smb2_file_mode_info *)rsp->Buffer; 7046 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK; 7047 rsp->OutputBufferLength = 7048 cpu_to_le32(sizeof(struct smb2_file_mode_info)); 7049 } 7050 7051 static int get_file_compression_info(struct smb2_query_info_rsp *rsp, 7052 struct ksmbd_file *fp, void *rsp_org) 7053 { 7054 struct smb2_file_comp_info *file_info; 7055 struct kstat stat; 7056 u16 fmt; 7057 int ret; 7058 7059 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 7060 AT_STATX_SYNC_AS_STAT); 7061 if (ret) 7062 return ret; 7063 7064 ret = ksmbd_vfs_get_compression(fp, &fmt); 7065 if (ret) 7066 return ret; 7067 7068 file_info = (struct smb2_file_comp_info *)rsp->Buffer; 7069 file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size)); 7070 file_info->CompressionFormat = cpu_to_le16(fmt); 7071 file_info->CompressionUnitShift = 0; 7072 file_info->ChunkShift = 0; 7073 file_info->ClusterShift = 0; 7074 memset(&file_info->Reserved[0], 0, 3); 7075 7076 rsp->OutputBufferLength = 7077 cpu_to_le32(sizeof(struct smb2_file_comp_info)); 7078 7079 return 0; 7080 } 7081 7082 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp, 7083 struct ksmbd_file *fp, void *rsp_org) 7084 { 7085 struct smb2_file_attr_tag_info *file_info; 7086 7087 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) { 7088 pr_err("no right to read the attributes : 0x%x\n", 7089 fp->daccess); 7090 return -EACCES; 7091 } 7092 7093 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer; 7094 file_info->FileAttributes = fp->f_ci->m_fattr; 7095 file_info->ReparseTag = 0; 7096 rsp->OutputBufferLength = 7097 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info)); 7098 return 0; 7099 } 7100 7101 static int find_file_posix_info(struct smb2_query_info_rsp *rsp, 7102 struct ksmbd_file *fp, void *rsp_org) 7103 { 7104 struct smb311_posix_qinfo *file_info; 7105 struct inode *inode = file_inode(fp->filp); 7106 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp); 7107 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode); 7108 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode); 7109 struct kstat stat; 7110 u64 time; 7111 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32; 7112 int ret; 7113 7114 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) { 7115 pr_err("no right to read the attributes : 0x%x\n", 7116 fp->daccess); 7117 return -EACCES; 7118 } 7119 7120 ret = get_file_allocation_stat(fp, &stat); 7121 if (ret) 7122 return ret; 7123 7124 file_info = (struct smb311_posix_qinfo *)rsp->Buffer; 7125 file_info->CreationTime = cpu_to_le64(fp->create_time); 7126 time = ksmbd_UnixTimeToNT(stat.atime); 7127 file_info->LastAccessTime = cpu_to_le64(time); 7128 time = ksmbd_UnixTimeToNT(stat.mtime); 7129 file_info->LastWriteTime = cpu_to_le64(time); 7130 file_info->ChangeTime = cpu_to_le64(fp->change_time); 7131 file_info->DosAttributes = fp->f_ci->m_fattr; 7132 file_info->Inode = cpu_to_le64(stat.ino); 7133 if (ksmbd_stream_fd(fp) == false) { 7134 file_info->EndOfFile = cpu_to_le64(stat.size); 7135 file_info->AllocationSize = cpu_to_le64(fp->allocation_size); 7136 } else { 7137 loff_t seof = ksmbd_stream_eof(fp); 7138 7139 file_info->EndOfFile = cpu_to_le64((u64)seof); 7140 file_info->AllocationSize = cpu_to_le64((u64)seof); 7141 } 7142 file_info->HardLinks = cpu_to_le32(stat.nlink); 7143 file_info->Mode = cpu_to_le32(stat.mode & 0777); 7144 switch (stat.mode & S_IFMT) { 7145 case S_IFDIR: 7146 file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT); 7147 break; 7148 case S_IFLNK: 7149 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT); 7150 break; 7151 case S_IFCHR: 7152 file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT); 7153 break; 7154 case S_IFBLK: 7155 file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT); 7156 break; 7157 case S_IFIFO: 7158 file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT); 7159 break; 7160 case S_IFSOCK: 7161 file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT); 7162 } 7163 7164 file_info->DeviceId = cpu_to_le32(stat.rdev); 7165 7166 /* 7167 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)). 7168 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) + 7169 * sub_auth(4 * 1(num_subauth)) + RID(4). 7170 */ 7171 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)), 7172 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]); 7173 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)), 7174 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]); 7175 7176 rsp->OutputBufferLength = cpu_to_le32(out_buf_len); 7177 7178 return 0; 7179 } 7180 7181 static int smb2_get_info_file(struct ksmbd_work *work, 7182 struct smb2_query_info_req *req, 7183 struct smb2_query_info_rsp *rsp) 7184 { 7185 struct ksmbd_file *fp; 7186 int fileinfoclass = 0; 7187 int rc = 0; 7188 unsigned int fixed_len; 7189 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 7190 7191 if (test_share_config_flag(work->tcon->share_conf, 7192 KSMBD_SHARE_FLAG_PIPE)) { 7193 /* smb2 info file called for pipe */ 7194 rc = smb2_get_info_file_pipe(work->sess, req, rsp, 7195 work->response_buf); 7196 goto iov_pin_out; 7197 } 7198 7199 if (work->next_smb2_rcv_hdr_off) { 7200 if (!has_file_id(req->VolatileFileId)) { 7201 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 7202 work->compound_fid); 7203 id = work->compound_fid; 7204 pid = work->compound_pfid; 7205 } 7206 } 7207 7208 if (!has_file_id(id)) { 7209 id = req->VolatileFileId; 7210 pid = req->PersistentFileId; 7211 } 7212 7213 fp = ksmbd_lookup_fd_slow(work, id, pid); 7214 if (!fp) 7215 return -ENOENT; 7216 7217 fileinfoclass = req->FileInfoClass; 7218 7219 switch (fileinfoclass) { 7220 case FILE_ACCESS_INFORMATION: 7221 get_file_access_info(rsp, fp, work->response_buf); 7222 break; 7223 7224 case FILE_BASIC_INFORMATION: 7225 rc = get_file_basic_info(rsp, fp, work->response_buf); 7226 break; 7227 7228 case FILE_STANDARD_INFORMATION: 7229 rc = get_file_standard_info(rsp, fp, work->response_buf); 7230 break; 7231 7232 case FILE_ALIGNMENT_INFORMATION: 7233 get_file_alignment_info(rsp, work->response_buf); 7234 break; 7235 7236 case FILE_ALL_INFORMATION: 7237 rc = get_file_all_info(work, rsp, fp, work->response_buf); 7238 break; 7239 7240 case FILE_ALTERNATE_NAME_INFORMATION: 7241 get_file_alternate_info(work, rsp, fp, work->response_buf); 7242 break; 7243 case FILE_NORMALIZED_NAME_INFORMATION: 7244 rc = get_file_normalized_name_info(work, rsp, fp); 7245 break; 7246 7247 case FILE_STREAM_INFORMATION: 7248 rc = get_file_stream_info(work, rsp, fp, work->response_buf); 7249 break; 7250 7251 case FILE_INTERNAL_INFORMATION: 7252 rc = get_file_internal_info(rsp, fp, work->response_buf); 7253 break; 7254 7255 case FILE_NETWORK_OPEN_INFORMATION: 7256 rc = get_file_network_open_info(rsp, fp, work->response_buf); 7257 break; 7258 7259 case FILE_EA_INFORMATION: 7260 get_file_ea_info(rsp, work->response_buf); 7261 break; 7262 7263 case FILE_FULL_EA_INFORMATION: 7264 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf); 7265 break; 7266 7267 case FILE_POSITION_INFORMATION: 7268 get_file_position_info(rsp, fp, work->response_buf); 7269 break; 7270 7271 case FILE_MODE_INFORMATION: 7272 get_file_mode_info(rsp, fp, work->response_buf); 7273 break; 7274 7275 case FILE_COMPRESSION_INFORMATION: 7276 rc = get_file_compression_info(rsp, fp, work->response_buf); 7277 break; 7278 7279 case FILE_ATTRIBUTE_TAG_INFORMATION: 7280 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf); 7281 break; 7282 case SMB_FIND_FILE_POSIX_INFO: 7283 if (!work->tcon->posix_extensions) { 7284 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n"); 7285 rc = -EOPNOTSUPP; 7286 } else { 7287 rc = find_file_posix_info(rsp, fp, work->response_buf); 7288 } 7289 break; 7290 default: 7291 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n", 7292 fileinfoclass); 7293 rc = -EOPNOTSUPP; 7294 } 7295 if (!rc) { 7296 fixed_len = le32_to_cpu(rsp->OutputBufferLength); 7297 switch (fileinfoclass) { 7298 case FILE_ALL_INFORMATION: 7299 fixed_len = FILE_ALL_INFORMATION_SIZE; 7300 break; 7301 case FILE_ALTERNATE_NAME_INFORMATION: 7302 fixed_len = FILE_ALTERNATE_NAME_INFORMATION_SIZE; 7303 break; 7304 case FILE_STREAM_INFORMATION: 7305 fixed_len = FILE_STREAM_INFORMATION_SIZE; 7306 break; 7307 } 7308 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength), 7309 fixed_len, 7310 rsp, work->response_buf); 7311 } 7312 ksmbd_fd_put(work, fp); 7313 7314 iov_pin_out: 7315 if (!rc) 7316 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, 7317 offsetof(struct smb2_query_info_rsp, Buffer) + 7318 le32_to_cpu(rsp->OutputBufferLength)); 7319 return rc; 7320 } 7321 7322 static int smb2_get_info_filesystem(struct ksmbd_work *work, 7323 struct smb2_query_info_req *req, 7324 struct smb2_query_info_rsp *rsp) 7325 { 7326 struct ksmbd_conn *conn = work->conn; 7327 struct ksmbd_share_config *share = work->tcon->share_conf; 7328 int fsinfoclass = 0; 7329 struct kstatfs stfs; 7330 struct path path; 7331 int rc = 0, len; 7332 unsigned int fixed_len = 0; 7333 7334 if (!share->path) 7335 return -EIO; 7336 7337 scoped_with_init_fs() 7338 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path); 7339 if (rc) { 7340 pr_err("cannot create vfs path\n"); 7341 return -EIO; 7342 } 7343 7344 rc = vfs_statfs(&path, &stfs); 7345 if (rc) { 7346 pr_err("cannot do stat of path %s\n", share->path); 7347 path_put(&path); 7348 return -EIO; 7349 } 7350 7351 fsinfoclass = req->FileInfoClass; 7352 7353 switch (fsinfoclass) { 7354 case FS_DEVICE_INFORMATION: 7355 { 7356 FILE_SYSTEM_DEVICE_INFO *info; 7357 7358 info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer; 7359 7360 info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK); 7361 info->DeviceCharacteristics = 7362 cpu_to_le32(FILE_DEVICE_IS_MOUNTED); 7363 if (!test_tree_conn_flag(work->tcon, 7364 KSMBD_TREE_CONN_FLAG_WRITABLE)) 7365 info->DeviceCharacteristics |= 7366 cpu_to_le32(FILE_READ_ONLY_DEVICE); 7367 rsp->OutputBufferLength = cpu_to_le32(8); 7368 fixed_len = 8; 7369 break; 7370 } 7371 case FS_ATTRIBUTE_INFORMATION: 7372 { 7373 FILE_SYSTEM_ATTRIBUTE_INFO *info; 7374 struct file_kattr fa = {}; 7375 size_t sz; 7376 u32 attrs; 7377 int err; 7378 7379 info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer; 7380 attrs = FILE_SUPPORTS_OBJECT_IDS | 7381 FILE_PERSISTENT_ACLS | 7382 FILE_UNICODE_ON_DISK | 7383 FILE_FILE_COMPRESSION | 7384 FILE_SUPPORTS_SPARSE_FILES | 7385 FILE_SUPPORTS_BLOCK_REFCOUNTING; 7386 7387 err = vfs_fileattr_get(path.dentry, &fa); 7388 /* 7389 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE 7390 * filesystems that lack FS_IOC_FSGETXATTR support. 7391 */ 7392 if (err && err != -ENOIOCTLCMD && err != -ENOTTY && 7393 err != -EINVAL && err != -EOPNOTSUPP) { 7394 path_put(&path); 7395 return err; 7396 } 7397 if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD)) 7398 attrs |= FILE_CASE_SENSITIVE_SEARCH; 7399 if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING)) 7400 attrs |= FILE_CASE_PRESERVED_NAMES; 7401 7402 info->Attributes = cpu_to_le32(attrs); 7403 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps); 7404 7405 if (test_share_config_flag(work->tcon->share_conf, 7406 KSMBD_SHARE_FLAG_STREAMS)) 7407 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS); 7408 7409 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen); 7410 /* 7411 * some application(potableapp) can not run on ksmbd share 7412 * because only NTFS handle security setting on windows. 7413 * So Although local fs(EXT4 or F2fs, etc) is not NTFS, 7414 * ksmbd should show share as NTFS. Later, If needed, we can add 7415 * fs type(s) parameter to change fs type user wanted. 7416 */ 7417 len = smbConvertToUTF16((__le16 *)info->FileSystemName, 7418 "NTFS", PATH_MAX, conn->local_nls, 0); 7419 len = len * 2; 7420 info->FileSystemNameLen = cpu_to_le32(len); 7421 sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len; 7422 rsp->OutputBufferLength = cpu_to_le32(sz); 7423 fixed_len = 16; 7424 break; 7425 } 7426 case FS_VOLUME_INFORMATION: 7427 { 7428 struct filesystem_vol_info *info; 7429 size_t sz; 7430 unsigned int serial_crc = 0; 7431 7432 info = (struct filesystem_vol_info *)(rsp->Buffer); 7433 info->VolumeCreationTime = 0; 7434 serial_crc = crc32_le(serial_crc, share->name, 7435 strlen(share->name)); 7436 serial_crc = crc32_le(serial_crc, share->path, 7437 strlen(share->path)); 7438 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(), 7439 strlen(ksmbd_netbios_name())); 7440 /* Taking dummy value of serial number*/ 7441 info->VolumeSerialNumber = cpu_to_le32(serial_crc); 7442 len = smbConvertToUTF16((__le16 *)info->VolumeLabel, 7443 share->name, PATH_MAX, 7444 conn->local_nls, 0); 7445 len = len * 2; 7446 info->VolumeLabelLength = cpu_to_le32(len); 7447 info->Reserved = 0; 7448 info->SupportsObjects = 0; 7449 sz = sizeof(struct filesystem_vol_info) + len; 7450 rsp->OutputBufferLength = cpu_to_le32(sz); 7451 fixed_len = 24; 7452 break; 7453 } 7454 case FS_SIZE_INFORMATION: 7455 { 7456 FILE_SYSTEM_SIZE_INFO *info; 7457 7458 info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer); 7459 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks); 7460 info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree); 7461 info->SectorsPerAllocationUnit = cpu_to_le32(1); 7462 info->BytesPerSector = cpu_to_le32(stfs.f_bsize); 7463 rsp->OutputBufferLength = cpu_to_le32(24); 7464 fixed_len = 24; 7465 break; 7466 } 7467 case FS_FULL_SIZE_INFORMATION: 7468 { 7469 struct smb2_fs_full_size_info *info; 7470 7471 info = (struct smb2_fs_full_size_info *)(rsp->Buffer); 7472 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks); 7473 info->CallerAvailableAllocationUnits = 7474 cpu_to_le64(stfs.f_bavail); 7475 info->ActualAvailableAllocationUnits = 7476 cpu_to_le64(stfs.f_bfree); 7477 info->SectorsPerAllocationUnit = cpu_to_le32(1); 7478 info->BytesPerSector = cpu_to_le32(stfs.f_bsize); 7479 rsp->OutputBufferLength = cpu_to_le32(32); 7480 fixed_len = 32; 7481 break; 7482 } 7483 case FS_OBJECT_ID_INFORMATION: 7484 { 7485 struct object_id_info *info; 7486 7487 info = (struct object_id_info *)(rsp->Buffer); 7488 memset(info, 0, sizeof(*info)); 7489 7490 if (path.mnt->mnt_sb->s_uuid_len == 16) 7491 memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b, 7492 path.mnt->mnt_sb->s_uuid_len); 7493 else 7494 memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid)); 7495 7496 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC); 7497 info->extended_info.version = cpu_to_le32(1); 7498 info->extended_info.release = cpu_to_le32(1); 7499 info->extended_info.rel_date = 0; 7500 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0")); 7501 rsp->OutputBufferLength = cpu_to_le32(64); 7502 fixed_len = 64; 7503 break; 7504 } 7505 case FS_SECTOR_SIZE_INFORMATION: 7506 { 7507 struct smb3_fs_ss_info *info; 7508 unsigned int sector_size = 7509 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096); 7510 7511 info = (struct smb3_fs_ss_info *)(rsp->Buffer); 7512 7513 info->LogicalBytesPerSector = cpu_to_le32(sector_size); 7514 info->PhysicalBytesPerSectorForAtomicity = 7515 cpu_to_le32(sector_size); 7516 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size); 7517 info->FSEffPhysicalBytesPerSectorForAtomicity = 7518 cpu_to_le32(sector_size); 7519 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE | 7520 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE | 7521 SSINFO_FLAGS_TRIM_ENABLED); 7522 info->ByteOffsetForSectorAlignment = 0; 7523 info->ByteOffsetForPartitionAlignment = 0; 7524 rsp->OutputBufferLength = cpu_to_le32(28); 7525 fixed_len = 28; 7526 break; 7527 } 7528 case FS_CONTROL_INFORMATION: 7529 { 7530 /* 7531 * TODO : The current implementation is based on 7532 * test result with win7(NTFS) server. It's need to 7533 * modify this to get valid Quota values 7534 * from Linux kernel 7535 */ 7536 struct smb2_fs_control_info *info; 7537 7538 info = (struct smb2_fs_control_info *)(rsp->Buffer); 7539 info->FreeSpaceStartFiltering = 0; 7540 info->FreeSpaceThreshold = 0; 7541 info->FreeSpaceStopFiltering = 0; 7542 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID); 7543 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID); 7544 info->FileSystemControlFlags = 0; 7545 info->Padding = 0; 7546 rsp->OutputBufferLength = cpu_to_le32(48); 7547 fixed_len = 48; 7548 break; 7549 } 7550 case FS_POSIX_INFORMATION: 7551 { 7552 FILE_SYSTEM_POSIX_INFO *info; 7553 7554 if (!work->tcon->posix_extensions) { 7555 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n"); 7556 path_put(&path); 7557 return -EOPNOTSUPP; 7558 } else { 7559 info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer); 7560 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize); 7561 info->BlockSize = cpu_to_le32(stfs.f_bsize); 7562 info->TotalBlocks = cpu_to_le64(stfs.f_blocks); 7563 info->BlocksAvail = cpu_to_le64(stfs.f_bfree); 7564 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail); 7565 info->TotalFileNodes = cpu_to_le64(stfs.f_files); 7566 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree); 7567 info->FileSysIdentifier = 7568 cpu_to_le64((u64)(u32)stfs.f_fsid.val[1] << 32 | 7569 (u32)stfs.f_fsid.val[0]); 7570 rsp->OutputBufferLength = cpu_to_le32(56); 7571 fixed_len = 56; 7572 } 7573 break; 7574 } 7575 default: 7576 path_put(&path); 7577 return -EOPNOTSUPP; 7578 } 7579 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength), 7580 fixed_len, 7581 rsp, work->response_buf); 7582 path_put(&path); 7583 7584 if (!rc) 7585 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, 7586 offsetof(struct smb2_query_info_rsp, Buffer) + 7587 le32_to_cpu(rsp->OutputBufferLength)); 7588 return rc; 7589 } 7590 7591 static int smb2_get_info_sec(struct ksmbd_work *work, 7592 struct smb2_query_info_req *req, 7593 struct smb2_query_info_rsp *rsp) 7594 { 7595 struct ksmbd_file *fp; 7596 struct mnt_idmap *idmap; 7597 struct smb_ntsd *pntsd = NULL, *ppntsd = NULL; 7598 struct smb_fattr fattr = {{0}}; 7599 struct inode *inode; 7600 __u32 secdesclen = 0; 7601 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 7602 int addition_info = le32_to_cpu(req->AdditionalInformation); 7603 int rc = 0, ppntsd_size = 0, max_len; 7604 size_t scratch_len = 0; 7605 7606 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO | 7607 PROTECTED_DACL_SECINFO | 7608 UNPROTECTED_DACL_SECINFO)) { 7609 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n", 7610 addition_info); 7611 7612 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 7613 return -EINVAL; 7614 } 7615 7616 if (work->next_smb2_rcv_hdr_off) { 7617 if (!has_file_id(req->VolatileFileId)) { 7618 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 7619 work->compound_fid); 7620 id = work->compound_fid; 7621 pid = work->compound_pfid; 7622 } 7623 } 7624 7625 if (!has_file_id(id)) { 7626 id = req->VolatileFileId; 7627 pid = req->PersistentFileId; 7628 } 7629 7630 fp = ksmbd_lookup_fd_slow(work, id, pid); 7631 if (!fp) 7632 return -ENOENT; 7633 7634 if (addition_info & (OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO) && 7635 !(fp->daccess & FILE_READ_CONTROL_LE)) { 7636 ksmbd_fd_put(work, fp); 7637 return -EACCES; 7638 } 7639 7640 if (le32_to_cpu(req->OutputBufferLength) < sizeof(struct smb_ntsd)) { 7641 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL; 7642 ksmbd_fd_put(work, fp); 7643 return -ENOSPC; 7644 } 7645 7646 idmap = file_mnt_idmap(fp->filp); 7647 inode = file_inode(fp->filp); 7648 ksmbd_acls_fattr(&fattr, idmap, inode); 7649 7650 if (test_share_config_flag(work->tcon->share_conf, 7651 KSMBD_SHARE_FLAG_ACL_XATTR)) 7652 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap, 7653 fp->filp->f_path.dentry, 7654 &ppntsd); 7655 7656 /* Check if sd buffer size exceeds response buffer size */ 7657 max_len = smb2_calc_max_out_buf_len(work, 7658 offsetof(struct smb2_query_info_rsp, Buffer), 7659 le32_to_cpu(req->OutputBufferLength)); 7660 if (max_len < 0) { 7661 rc = -EINVAL; 7662 goto release_acl; 7663 } 7664 7665 scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd, 7666 ppntsd_size, addition_info); 7667 if (!scratch_len || scratch_len == SIZE_MAX) { 7668 rc = -EFBIG; 7669 goto release_acl; 7670 } 7671 7672 pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP); 7673 if (!pntsd) { 7674 rc = -ENOMEM; 7675 goto release_acl; 7676 } 7677 7678 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size, 7679 addition_info, &secdesclen, &fattr); 7680 7681 release_acl: 7682 posix_acl_release(fattr.cf_acls); 7683 posix_acl_release(fattr.cf_dacls); 7684 kfree(ppntsd); 7685 ksmbd_fd_put(work, fp); 7686 7687 if (!rc && ALIGN(secdesclen, 8) > scratch_len) 7688 rc = -EFBIG; 7689 if (rc) 7690 goto err_out; 7691 7692 rsp->OutputBufferLength = cpu_to_le32(secdesclen); 7693 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength), 7694 le32_to_cpu(rsp->OutputBufferLength), 7695 rsp, work->response_buf); 7696 if (rc) 7697 goto err_out; 7698 7699 rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp, 7700 offsetof(struct smb2_query_info_rsp, Buffer), 7701 pntsd, secdesclen); 7702 err_out: 7703 if (rc) { 7704 rsp->OutputBufferLength = 0; 7705 kvfree(pntsd); 7706 } 7707 7708 return rc; 7709 } 7710 7711 /** 7712 * smb2_query_info() - handler for smb2 query info command 7713 * @work: smb work containing query info request buffer 7714 * 7715 * Return: 0 on success, otherwise error 7716 */ 7717 int smb2_query_info(struct ksmbd_work *work) 7718 { 7719 struct smb2_query_info_req *req; 7720 struct smb2_query_info_rsp *rsp; 7721 int rc = 0; 7722 7723 ksmbd_debug(SMB, "Received request smb2 query info request\n"); 7724 7725 WORK_BUFFERS(work, req, rsp); 7726 7727 if (smb2_compound_has_failed(work, &rsp->hdr)) 7728 return -EACCES; 7729 7730 if (ksmbd_override_fsids(work)) { 7731 rc = -ENOMEM; 7732 goto err_out; 7733 } 7734 7735 rsp->StructureSize = cpu_to_le16(9); 7736 rsp->OutputBufferOffset = cpu_to_le16(72); 7737 7738 switch (req->InfoType) { 7739 case SMB2_O_INFO_FILE: 7740 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n"); 7741 rc = smb2_get_info_file(work, req, rsp); 7742 break; 7743 case SMB2_O_INFO_FILESYSTEM: 7744 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n"); 7745 rc = smb2_get_info_filesystem(work, req, rsp); 7746 break; 7747 case SMB2_O_INFO_SECURITY: 7748 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n"); 7749 rc = smb2_get_info_sec(work, req, rsp); 7750 break; 7751 default: 7752 ksmbd_debug(SMB, "InfoType %d not supported yet\n", 7753 req->InfoType); 7754 rc = -EOPNOTSUPP; 7755 } 7756 ksmbd_revert_fsids(work); 7757 7758 err_out: 7759 if (rc < 0) { 7760 if (rc == -EACCES) 7761 rsp->hdr.Status = STATUS_ACCESS_DENIED; 7762 else if (rc == -ENOENT) 7763 rsp->hdr.Status = STATUS_FILE_CLOSED; 7764 else if (rc == -EIO) 7765 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 7766 else if (rc == -ENOMEM) 7767 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 7768 else if (rc == -EINVAL && rsp->hdr.Status == 0) 7769 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 7770 else if (rsp->hdr.Status == 0) 7771 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS; 7772 smb2_set_err_rsp(work); 7773 7774 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", 7775 rc); 7776 return rc; 7777 } 7778 return 0; 7779 } 7780 7781 /** 7782 * smb2_close_pipe() - handler for closing IPC pipe 7783 * @work: smb work containing close request buffer 7784 * 7785 * Return: 0 7786 */ 7787 static noinline int smb2_close_pipe(struct ksmbd_work *work) 7788 { 7789 u64 id; 7790 struct smb2_close_req *req; 7791 struct smb2_close_rsp *rsp; 7792 7793 WORK_BUFFERS(work, req, rsp); 7794 7795 id = req->VolatileFileId; 7796 ksmbd_session_rpc_close(work->sess, id); 7797 7798 rsp->StructureSize = cpu_to_le16(60); 7799 rsp->Flags = 0; 7800 rsp->Reserved = 0; 7801 rsp->CreationTime = 0; 7802 rsp->LastAccessTime = 0; 7803 rsp->LastWriteTime = 0; 7804 rsp->ChangeTime = 0; 7805 rsp->AllocationSize = 0; 7806 rsp->EndOfFile = 0; 7807 rsp->Attributes = 0; 7808 7809 return ksmbd_iov_pin_rsp(work, (void *)rsp, 7810 sizeof(struct smb2_close_rsp)); 7811 } 7812 7813 /** 7814 * smb2_close() - handler for smb2 close file command 7815 * @work: smb work containing close request buffer 7816 * 7817 * Return: 0 on success, otherwise error 7818 */ 7819 int smb2_close(struct ksmbd_work *work) 7820 { 7821 u64 volatile_id = KSMBD_NO_FID; 7822 u64 sess_id; 7823 struct smb2_close_req *req; 7824 struct smb2_close_rsp *rsp; 7825 struct ksmbd_file *fp; 7826 u64 time; 7827 int err = 0; 7828 7829 ksmbd_debug(SMB, "Received smb2 close request\n"); 7830 7831 WORK_BUFFERS(work, req, rsp); 7832 7833 if (smb2_compound_has_failed(work, &rsp->hdr)) 7834 return -EACCES; 7835 7836 if (test_share_config_flag(work->tcon->share_conf, 7837 KSMBD_SHARE_FLAG_PIPE)) { 7838 ksmbd_debug(SMB, "IPC pipe close request\n"); 7839 return smb2_close_pipe(work); 7840 } 7841 7842 sess_id = le64_to_cpu(req->hdr.SessionId); 7843 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS) 7844 sess_id = work->compound_sid; 7845 7846 work->compound_sid = 0; 7847 if (work->sess && work->sess->id == sess_id) { 7848 work->compound_sid = sess_id; 7849 } else { 7850 rsp->hdr.Status = STATUS_USER_SESSION_DELETED; 7851 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS) 7852 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 7853 err = -EBADF; 7854 goto out; 7855 } 7856 7857 if (work->next_smb2_rcv_hdr_off && 7858 !has_file_id(req->VolatileFileId)) { 7859 if (!has_file_id(work->compound_fid)) { 7860 /* file already closed, return FILE_CLOSED */ 7861 ksmbd_debug(SMB, "file already closed\n"); 7862 rsp->hdr.Status = STATUS_FILE_CLOSED; 7863 err = -EBADF; 7864 goto out; 7865 } else { 7866 ksmbd_debug(SMB, 7867 "Compound request set FID = %llu:%llu\n", 7868 work->compound_fid, 7869 work->compound_pfid); 7870 volatile_id = work->compound_fid; 7871 7872 /* file closed, stored id is not valid anymore */ 7873 work->compound_fid = KSMBD_NO_FID; 7874 work->compound_pfid = KSMBD_NO_FID; 7875 } 7876 } else { 7877 volatile_id = req->VolatileFileId; 7878 } 7879 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id); 7880 7881 rsp->StructureSize = cpu_to_le16(60); 7882 rsp->Reserved = 0; 7883 7884 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) { 7885 struct kstat stat; 7886 int ret; 7887 7888 fp = ksmbd_lookup_fd_fast(work, volatile_id); 7889 if (!fp) { 7890 err = -ENOENT; 7891 goto out; 7892 } 7893 7894 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 7895 AT_STATX_SYNC_AS_STAT); 7896 if (ret) { 7897 ksmbd_fd_put(work, fp); 7898 goto out; 7899 } 7900 7901 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB; 7902 rsp->AllocationSize = cpu_to_le64(fp->allocation_size); 7903 rsp->EndOfFile = cpu_to_le64(stat.size); 7904 rsp->Attributes = fp->f_ci->m_fattr; 7905 rsp->CreationTime = cpu_to_le64(fp->create_time); 7906 time = ksmbd_UnixTimeToNT(stat.atime); 7907 rsp->LastAccessTime = cpu_to_le64(time); 7908 time = ksmbd_UnixTimeToNT(stat.mtime); 7909 if (time > fp->open_mtime && 7910 time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION) 7911 time = fp->open_mtime; 7912 rsp->LastWriteTime = cpu_to_le64(time); 7913 rsp->ChangeTime = cpu_to_le64(fp->change_time); 7914 ksmbd_fd_put(work, fp); 7915 } else { 7916 rsp->Flags = 0; 7917 rsp->AllocationSize = 0; 7918 rsp->EndOfFile = 0; 7919 rsp->Attributes = 0; 7920 rsp->CreationTime = 0; 7921 rsp->LastAccessTime = 0; 7922 rsp->LastWriteTime = 0; 7923 rsp->ChangeTime = 0; 7924 } 7925 7926 err = ksmbd_close_fd(work, volatile_id); 7927 out: 7928 if (!err) 7929 err = ksmbd_iov_pin_rsp(work, (void *)rsp, 7930 sizeof(struct smb2_close_rsp)); 7931 7932 if (err) { 7933 if (rsp->hdr.Status == 0) 7934 rsp->hdr.Status = STATUS_FILE_CLOSED; 7935 smb2_set_err_rsp(work); 7936 } 7937 7938 return err; 7939 } 7940 7941 /** 7942 * smb2_echo() - handler for smb2 echo(ping) command 7943 * @work: smb work containing echo request buffer 7944 * 7945 * Return: 0 on success, otherwise error 7946 */ 7947 int smb2_echo(struct ksmbd_work *work) 7948 { 7949 struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf); 7950 7951 ksmbd_debug(SMB, "Received smb2 echo request\n"); 7952 7953 if (work->next_smb2_rcv_hdr_off) 7954 rsp = ksmbd_resp_buf_next(work); 7955 7956 rsp->StructureSize = cpu_to_le16(4); 7957 rsp->Reserved = 0; 7958 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp)); 7959 } 7960 7961 static int smb2_rename(struct ksmbd_work *work, 7962 struct ksmbd_file *fp, 7963 struct smb2_file_rename_info *file_info, 7964 struct nls_table *local_nls) 7965 { 7966 struct ksmbd_share_config *share = fp->tcon->share_conf; 7967 char *new_name = NULL; 7968 int rc, flags = 0; 7969 7970 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n"); 7971 new_name = smb2_get_name(file_info->FileName, 7972 le32_to_cpu(file_info->FileNameLength), 7973 local_nls); 7974 if (IS_ERR(new_name)) 7975 return PTR_ERR(new_name); 7976 7977 if (fp->is_posix_ctxt == false && strchr(new_name, ':')) { 7978 int s_type; 7979 char *xattr_stream_name, *stream_name = NULL; 7980 size_t xattr_stream_size; 7981 int len; 7982 7983 rc = parse_stream_name(new_name, &stream_name, &s_type); 7984 if (rc < 0) 7985 goto out; 7986 7987 len = strlen(new_name); 7988 if (len > 0 && new_name[len - 1] != '/') { 7989 pr_err("not allow base filename in rename\n"); 7990 rc = -ESHARE; 7991 goto out; 7992 } 7993 7994 rc = ksmbd_vfs_xattr_stream_name(stream_name, 7995 &xattr_stream_name, 7996 &xattr_stream_size, 7997 s_type); 7998 if (rc) 7999 goto out; 8000 8001 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp), 8002 &fp->filp->f_path, 8003 xattr_stream_name, 8004 NULL, 0, 0, true); 8005 if (rc < 0) { 8006 pr_err("failed to store stream name in xattr: %d\n", 8007 rc); 8008 rc = -EINVAL; 8009 } 8010 kfree(xattr_stream_name); 8011 goto out; 8012 } 8013 8014 ksmbd_debug(SMB, "new name %s\n", new_name); 8015 if (ksmbd_share_veto_filename(share, new_name)) { 8016 rc = -ENOENT; 8017 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name); 8018 goto out; 8019 } 8020 8021 if (!file_info->ReplaceIfExists) 8022 flags = RENAME_NOREPLACE; 8023 8024 rc = ksmbd_vfs_check_rename_share(work, &fp->filp->f_path); 8025 if (rc) 8026 goto out; 8027 8028 smb_break_all_levII_oplock_rename(work, fp); 8029 rc = ksmbd_vfs_rename(work, fp, new_name, flags); 8030 out: 8031 kfree(new_name); 8032 return rc; 8033 } 8034 8035 static int smb2_create_link(struct ksmbd_work *work, 8036 struct ksmbd_share_config *share, 8037 struct smb2_file_link_info *file_info, 8038 unsigned int buf_len, struct file *filp, 8039 struct nls_table *local_nls) 8040 { 8041 char *link_name = NULL, *target_name = NULL, *pathname = NULL; 8042 struct path path; 8043 int rc; 8044 8045 if (buf_len < (u64)sizeof(struct smb2_file_link_info) + 8046 le32_to_cpu(file_info->FileNameLength)) 8047 return -EINVAL; 8048 8049 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n"); 8050 pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP); 8051 if (!pathname) 8052 return -ENOMEM; 8053 8054 link_name = smb2_get_name(file_info->FileName, 8055 le32_to_cpu(file_info->FileNameLength), 8056 local_nls); 8057 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) { 8058 rc = -EINVAL; 8059 goto out; 8060 } 8061 8062 ksmbd_debug(SMB, "link name is %s\n", link_name); 8063 target_name = file_path(filp, pathname, PATH_MAX); 8064 if (IS_ERR(target_name)) { 8065 rc = -EINVAL; 8066 goto out; 8067 } 8068 8069 ksmbd_debug(SMB, "target name is %s\n", target_name); 8070 rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS, 8071 &path, 0); 8072 if (rc) { 8073 if (rc != -ENOENT) 8074 goto out; 8075 } else { 8076 if (file_info->ReplaceIfExists) { 8077 rc = ksmbd_vfs_remove_file(work, &path); 8078 if (rc) { 8079 rc = -EINVAL; 8080 ksmbd_debug(SMB, "cannot delete %s\n", 8081 link_name); 8082 } 8083 } else { 8084 rc = -EEXIST; 8085 ksmbd_debug(SMB, "link already exists\n"); 8086 } 8087 ksmbd_vfs_kern_path_end_removing(&path); 8088 if (rc) 8089 goto out; 8090 } 8091 rc = ksmbd_vfs_link(work, target_name, link_name); 8092 if (rc) 8093 rc = -EINVAL; 8094 out: 8095 8096 if (!IS_ERR(link_name)) 8097 kfree(link_name); 8098 kfree(pathname); 8099 return rc; 8100 } 8101 8102 static int set_file_basic_info(struct ksmbd_file *fp, 8103 struct file_basic_info *file_info, 8104 struct ksmbd_share_config *share) 8105 { 8106 struct iattr attrs; 8107 struct file *filp; 8108 struct inode *inode; 8109 struct mnt_idmap *idmap; 8110 __le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE | 8111 FILE_ATTRIBUTE_COMPRESSED_LE; 8112 int rc = 0; 8113 8114 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE)) 8115 return -EACCES; 8116 8117 attrs.ia_valid = 0; 8118 filp = fp->filp; 8119 inode = file_inode(filp); 8120 idmap = file_mnt_idmap(filp); 8121 8122 if (file_info->CreationTime) 8123 fp->create_time = le64_to_cpu(file_info->CreationTime); 8124 8125 if (file_info->LastAccessTime) { 8126 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime); 8127 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); 8128 } 8129 8130 if (file_info->ChangeTime) { 8131 fp->change_time = le64_to_cpu(file_info->ChangeTime); 8132 inode_set_ctime_to_ts(inode, 8133 ksmbd_NTtimeToUnix(file_info->ChangeTime)); 8134 } 8135 8136 if (file_info->LastWriteTime) { 8137 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime); 8138 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME); 8139 } 8140 8141 if (file_info->Attributes) { 8142 if (!S_ISDIR(inode->i_mode) && 8143 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) { 8144 pr_err("can't change a file to a directory\n"); 8145 return -EINVAL; 8146 } 8147 8148 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE)) 8149 fp->f_ci->m_fattr = 8150 (file_info->Attributes & ~FILE_ATTRIBUTE_COMPRESSED_LE) | 8151 (fp->f_ci->m_fattr & attrs_mask); 8152 } 8153 8154 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) && 8155 (file_info->CreationTime || file_info->Attributes)) { 8156 struct xattr_dos_attrib da = {0}; 8157 8158 da.version = 4; 8159 da.itime = fp->itime; 8160 da.create_time = fp->create_time; 8161 da.attr = le32_to_cpu(fp->f_ci->m_fattr); 8162 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME | 8163 XATTR_DOSINFO_ITIME; 8164 8165 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da, 8166 true); 8167 if (rc) 8168 ksmbd_debug(SMB, 8169 "failed to restore file attribute in EA\n"); 8170 rc = 0; 8171 } 8172 8173 if (attrs.ia_valid) { 8174 struct dentry *dentry = filp->f_path.dentry; 8175 struct inode *inode = d_inode(dentry); 8176 8177 if (IS_IMMUTABLE(inode) || IS_APPEND(inode)) 8178 return -EACCES; 8179 8180 inode_lock(inode); 8181 rc = notify_change(idmap, dentry, &attrs, NULL); 8182 inode_unlock(inode); 8183 } 8184 return rc; 8185 } 8186 8187 static int set_file_allocation_info(struct ksmbd_work *work, 8188 struct ksmbd_file *fp, 8189 struct smb2_file_alloc_info *file_alloc_info) 8190 { 8191 /* 8192 * TODO : It's working fine only when store dos attributes 8193 * is not yes. need to implement a logic which works 8194 * properly with any smb.conf option 8195 */ 8196 8197 loff_t alloc_blks; 8198 u64 alloc_size; 8199 struct inode *inode; 8200 struct kstat stat; 8201 int rc; 8202 8203 if (!(fp->daccess & FILE_WRITE_DATA_LE)) 8204 return -EACCES; 8205 8206 if (ksmbd_stream_fd(fp) == true) 8207 return 0; 8208 8209 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, 8210 AT_STATX_SYNC_AS_STAT); 8211 if (rc) 8212 return rc; 8213 8214 /* 8215 * AllocationSize is fully client-controlled (the caller only 8216 * validates the fixed 8-byte buffer length). Reject values that 8217 * would overflow the "round up to 512-byte blocks" conversion 8218 * below instead of silently wrapping it to a tiny block count, 8219 * which would truncate the file to a size the client never 8220 * asked for. 8221 */ 8222 alloc_size = le64_to_cpu(file_alloc_info->AllocationSize); 8223 if (alloc_size > MAX_LFS_FILESIZE - 511) 8224 return -EINVAL; 8225 8226 alloc_blks = (alloc_size + 511) >> 9; 8227 inode = file_inode(fp->filp); 8228 8229 if (alloc_blks > stat.blocks) { 8230 smb_break_all_levII_oplock(work, fp, 1); 8231 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, 8232 alloc_blks * 512); 8233 if (rc && rc != -EOPNOTSUPP) { 8234 pr_err("vfs_fallocate is failed : %d\n", rc); 8235 return rc; 8236 } 8237 } else if (alloc_blks < stat.blocks) { 8238 loff_t size; 8239 8240 /* 8241 * Allocation size could be smaller than original one 8242 * which means allocated blocks in file should be 8243 * deallocated. use truncate to cut out it, but inode 8244 * size is also updated with truncate offset. 8245 * inode size is retained by backup inode size. 8246 */ 8247 size = i_size_read(inode); 8248 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512); 8249 if (rc) { 8250 pr_err("truncate failed!, err %d\n", rc); 8251 return rc; 8252 } 8253 if (size < alloc_blks * 512) 8254 i_size_write(inode, size); 8255 } 8256 8257 fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize); 8258 fp->allocation_size_set = true; 8259 return 0; 8260 } 8261 8262 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp, 8263 struct smb2_file_eof_info *file_eof_info) 8264 { 8265 loff_t newsize; 8266 struct inode *inode; 8267 int rc; 8268 8269 if (!(fp->daccess & FILE_WRITE_DATA_LE)) 8270 return -EACCES; 8271 8272 newsize = le64_to_cpu(file_eof_info->EndOfFile); 8273 inode = file_inode(fp->filp); 8274 8275 /* 8276 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called 8277 * on FAT32 shared device, truncate execution time is too long 8278 * and network error could cause from windows client. because 8279 * truncate of some filesystem like FAT32 fill zero data in 8280 * truncated range. 8281 */ 8282 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC && 8283 ksmbd_stream_fd(fp) == false) { 8284 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize); 8285 rc = ksmbd_vfs_truncate(work, fp, newsize); 8286 if (rc) { 8287 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc); 8288 if (rc != -EAGAIN) 8289 rc = -EBADF; 8290 return rc; 8291 } 8292 } 8293 return 0; 8294 } 8295 8296 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp, 8297 struct smb2_file_rename_info *rename_info, 8298 unsigned int buf_len) 8299 { 8300 if (!(fp->daccess & FILE_DELETE_LE)) { 8301 pr_err("no right to delete : 0x%x\n", fp->daccess); 8302 return -EACCES; 8303 } 8304 8305 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) + 8306 le32_to_cpu(rename_info->FileNameLength)) 8307 return -EINVAL; 8308 8309 if (!le32_to_cpu(rename_info->FileNameLength)) 8310 return -EINVAL; 8311 8312 return smb2_rename(work, fp, rename_info, work->conn->local_nls); 8313 } 8314 8315 static int set_file_disposition_info(struct ksmbd_work *work, 8316 struct ksmbd_file *fp, 8317 struct smb2_file_disposition_info *file_info) 8318 { 8319 struct inode *inode; 8320 8321 if (!(fp->daccess & FILE_DELETE_LE)) { 8322 pr_err("no right to delete : 0x%x\n", fp->daccess); 8323 return -EACCES; 8324 } 8325 8326 if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE) 8327 return -EACCES; 8328 8329 inode = file_inode(fp->filp); 8330 if (file_info->DeletePending) { 8331 if (ksmbd_has_stream_without_delete_share(fp)) 8332 return -ESHARE; 8333 8334 if (S_ISDIR(inode->i_mode) && !ksmbd_stream_fd(fp) && 8335 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY) 8336 return -EBUSY; 8337 smb_break_all_levII_oplock_for_delete(work, fp); 8338 ksmbd_fd_set_delete_pending(fp); 8339 } else { 8340 ksmbd_fd_clear_delete_pending(fp); 8341 } 8342 return 0; 8343 } 8344 8345 static int set_file_position_info(struct ksmbd_file *fp, 8346 struct smb2_file_pos_info *file_info) 8347 { 8348 loff_t current_byte_offset; 8349 unsigned long sector_size; 8350 struct inode *inode; 8351 8352 inode = file_inode(fp->filp); 8353 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset); 8354 sector_size = inode->i_sb->s_blocksize; 8355 8356 if (current_byte_offset < 0 || 8357 (fp->coption & FILE_NO_INTERMEDIATE_BUFFERING_LE && 8358 current_byte_offset & (sector_size - 1))) { 8359 pr_err("CurrentByteOffset is not valid : %llu\n", 8360 current_byte_offset); 8361 return -EINVAL; 8362 } 8363 8364 if (ksmbd_stream_fd(fp) == false) 8365 fp->filp->f_pos = current_byte_offset; 8366 else { 8367 if (current_byte_offset > XATTR_SIZE_MAX) 8368 current_byte_offset = XATTR_SIZE_MAX; 8369 fp->stream.pos = current_byte_offset; 8370 } 8371 return 0; 8372 } 8373 8374 static int set_file_mode_info(struct ksmbd_file *fp, 8375 struct smb2_file_mode_info *file_info) 8376 { 8377 __le32 mode; 8378 8379 mode = file_info->Mode; 8380 8381 if ((mode & ~FILE_MODE_INFO_MASK)) { 8382 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode)); 8383 return -EINVAL; 8384 } 8385 8386 /* 8387 * TODO : need to implement consideration for 8388 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT 8389 */ 8390 ksmbd_vfs_set_fadvise(fp->filp, mode); 8391 fp->coption = mode; 8392 return 0; 8393 } 8394 8395 /** 8396 * smb2_set_info_file() - handler for smb2 set info command 8397 * @work: smb work containing set info command buffer 8398 * @fp: ksmbd_file pointer 8399 * @req: request buffer pointer 8400 * @share: ksmbd_share_config pointer 8401 * 8402 * Return: 0 on success, otherwise error 8403 */ 8404 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, 8405 struct smb2_set_info_req *req, 8406 struct ksmbd_share_config *share) 8407 { 8408 unsigned int buf_len = le32_to_cpu(req->BufferLength); 8409 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset); 8410 8411 switch (req->FileInfoClass) { 8412 case FILE_BASIC_INFORMATION: 8413 { 8414 if (buf_len < sizeof(struct file_basic_info)) 8415 return -EMSGSIZE; 8416 8417 return set_file_basic_info(fp, (struct file_basic_info *)buffer, share); 8418 } 8419 case FILE_ALLOCATION_INFORMATION: 8420 { 8421 if (buf_len < sizeof(struct smb2_file_alloc_info)) 8422 return -EMSGSIZE; 8423 8424 return set_file_allocation_info(work, fp, 8425 (struct smb2_file_alloc_info *)buffer); 8426 } 8427 case FILE_END_OF_FILE_INFORMATION: 8428 { 8429 if (buf_len < sizeof(struct smb2_file_eof_info)) 8430 return -EMSGSIZE; 8431 8432 return set_end_of_file_info(work, fp, 8433 (struct smb2_file_eof_info *)buffer); 8434 } 8435 case FILE_RENAME_INFORMATION: 8436 { 8437 if (buf_len < sizeof(struct smb2_file_rename_info)) 8438 return -EMSGSIZE; 8439 8440 return set_rename_info(work, fp, 8441 (struct smb2_file_rename_info *)buffer, 8442 buf_len); 8443 } 8444 case FILE_LINK_INFORMATION: 8445 { 8446 struct smb2_file_link_info *file_info; 8447 8448 if (buf_len < sizeof(struct smb2_file_link_info)) 8449 return -EMSGSIZE; 8450 8451 file_info = (struct smb2_file_link_info *)buffer; 8452 if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) { 8453 pr_err("no right to delete : 0x%x\n", fp->daccess); 8454 return -EACCES; 8455 } 8456 8457 return smb2_create_link(work, work->tcon->share_conf, file_info, 8458 buf_len, fp->filp, 8459 work->conn->local_nls); 8460 } 8461 case FILE_DISPOSITION_INFORMATION: 8462 { 8463 if (buf_len < sizeof(struct smb2_file_disposition_info)) 8464 return -EMSGSIZE; 8465 8466 return set_file_disposition_info(work, fp, 8467 (struct smb2_file_disposition_info *)buffer); 8468 } 8469 case FILE_FULL_EA_INFORMATION: 8470 { 8471 if (!(fp->daccess & FILE_WRITE_EA_LE)) { 8472 pr_err("Not permitted to write ext attr: 0x%x\n", 8473 fp->daccess); 8474 return -EACCES; 8475 } 8476 8477 if (buf_len < sizeof(struct smb2_ea_info)) 8478 return -EMSGSIZE; 8479 8480 return smb2_set_ea((struct smb2_ea_info *)buffer, 8481 buf_len, &fp->filp->f_path, true); 8482 } 8483 case FILE_POSITION_INFORMATION: 8484 { 8485 if (buf_len < sizeof(struct smb2_file_pos_info)) 8486 return -EMSGSIZE; 8487 8488 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer); 8489 } 8490 case FILE_MODE_INFORMATION: 8491 { 8492 if (buf_len < sizeof(struct smb2_file_mode_info)) 8493 return -EMSGSIZE; 8494 8495 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer); 8496 } 8497 } 8498 8499 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass); 8500 return -EOPNOTSUPP; 8501 } 8502 8503 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info, 8504 char *buffer, int buf_len) 8505 { 8506 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer; 8507 8508 fp->saccess |= FILE_SHARE_DELETE_LE; 8509 8510 if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE))) 8511 return -EACCES; 8512 8513 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd, 8514 buf_len, false, true); 8515 } 8516 8517 /** 8518 * smb2_set_info() - handler for smb2 set info command handler 8519 * @work: smb work containing set info request buffer 8520 * 8521 * Return: 0 on success, otherwise error 8522 */ 8523 int smb2_set_info(struct ksmbd_work *work) 8524 { 8525 const struct cred *saved_cred; 8526 struct smb2_set_info_req *req; 8527 struct smb2_set_info_rsp *rsp; 8528 struct ksmbd_file *fp = NULL; 8529 int rc = 0; 8530 bool chseq_err = false; 8531 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 8532 8533 ksmbd_debug(SMB, "Received smb2 set info request\n"); 8534 8535 if (work->next_smb2_rcv_hdr_off) { 8536 req = ksmbd_req_buf_next(work); 8537 rsp = ksmbd_resp_buf_next(work); 8538 if (smb2_compound_has_failed(work, &rsp->hdr)) 8539 return -EACCES; 8540 if (!has_file_id(req->VolatileFileId)) { 8541 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 8542 work->compound_fid); 8543 id = work->compound_fid; 8544 pid = work->compound_pfid; 8545 } 8546 } else { 8547 req = smb_get_msg(work->request_buf); 8548 rsp = smb_get_msg(work->response_buf); 8549 } 8550 8551 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 8552 ksmbd_debug(SMB, "User does not have write permission\n"); 8553 pr_err("User does not have write permission\n"); 8554 rc = -EACCES; 8555 goto err_out; 8556 } 8557 8558 if (!has_file_id(id)) { 8559 id = req->VolatileFileId; 8560 pid = req->PersistentFileId; 8561 } 8562 8563 fp = ksmbd_lookup_fd_slow(work, id, pid); 8564 if (!fp) { 8565 ksmbd_debug(SMB, "Invalid id for close: %u\n", id); 8566 rc = -ENOENT; 8567 goto err_out; 8568 } 8569 8570 rc = smb2_set_request_open(work, fp, &req->hdr, true, false); 8571 if (rc) { 8572 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE; 8573 chseq_err = true; 8574 goto err_out; 8575 } 8576 8577 saved_cred = override_creds(fp->filp->f_cred); 8578 switch (req->InfoType) { 8579 case SMB2_O_INFO_FILE: 8580 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n"); 8581 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf); 8582 break; 8583 case SMB2_O_INFO_SECURITY: 8584 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n"); 8585 rc = smb2_set_info_sec(fp, 8586 le32_to_cpu(req->AdditionalInformation), 8587 (char *)req + le16_to_cpu(req->BufferOffset), 8588 le32_to_cpu(req->BufferLength)); 8589 break; 8590 default: 8591 rc = -EOPNOTSUPP; 8592 } 8593 revert_creds(saved_cred); 8594 8595 if (rc < 0) 8596 goto err_out; 8597 8598 rsp->StructureSize = cpu_to_le16(2); 8599 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, 8600 sizeof(struct smb2_set_info_rsp)); 8601 if (rc) 8602 goto err_out; 8603 ksmbd_fd_put(work, fp); 8604 return 0; 8605 8606 err_out: 8607 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV) { 8608 if (fp && req->InfoType == SMB2_O_INFO_FILE && 8609 req->FileInfoClass == FILE_DISPOSITION_INFORMATION && 8610 fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE) 8611 rsp->hdr.Status = STATUS_CANNOT_DELETE; 8612 else 8613 rsp->hdr.Status = STATUS_ACCESS_DENIED; 8614 } 8615 else if (rc == -EINVAL) 8616 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 8617 else if (rc == -EMSGSIZE) 8618 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH; 8619 else if (rc == -ENOSPC || rc == -EFBIG) 8620 rsp->hdr.Status = STATUS_DISK_FULL; 8621 else if (rc == -ESHARE) 8622 rsp->hdr.Status = STATUS_SHARING_VIOLATION; 8623 else if (rc == -ENOENT) 8624 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID; 8625 else if (rc == -EBUSY || rc == -ENOTEMPTY) 8626 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY; 8627 else if (rc == -EAGAIN && !chseq_err) 8628 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 8629 else if (rc == -EBADF || rc == -ESTALE) 8630 rsp->hdr.Status = STATUS_INVALID_HANDLE; 8631 else if (rc == -EEXIST) 8632 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION; 8633 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP) 8634 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS; 8635 smb2_set_err_rsp(work); 8636 ksmbd_fd_put(work, fp); 8637 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc); 8638 return rc; 8639 } 8640 8641 /** 8642 * smb2_read_pipe() - handler for smb2 read from IPC pipe 8643 * @work: smb work containing read IPC pipe command buffer 8644 * 8645 * Return: 0 on success, otherwise error 8646 */ 8647 static noinline int smb2_read_pipe(struct ksmbd_work *work) 8648 { 8649 int nbytes = 0, err; 8650 u64 id; 8651 struct ksmbd_rpc_command *rpc_resp; 8652 struct smb2_read_req *req; 8653 struct smb2_read_rsp *rsp; 8654 8655 WORK_BUFFERS(work, req, rsp); 8656 8657 id = req->VolatileFileId; 8658 8659 rpc_resp = ksmbd_rpc_read(work->sess, id); 8660 if (rpc_resp) { 8661 void *aux_payload_buf; 8662 8663 if (rpc_resp->flags != KSMBD_RPC_OK) { 8664 err = -EINVAL; 8665 goto out; 8666 } 8667 8668 aux_payload_buf = 8669 kvmalloc(ALIGN(rpc_resp->payload_sz, 8), 8670 KSMBD_DEFAULT_GFP); 8671 if (!aux_payload_buf) { 8672 err = -ENOMEM; 8673 goto out; 8674 } 8675 8676 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz); 8677 if (rpc_resp->payload_sz & 7) 8678 memset(aux_payload_buf + rpc_resp->payload_sz, 0, 8679 ALIGN(rpc_resp->payload_sz, 8) - 8680 rpc_resp->payload_sz); 8681 8682 nbytes = rpc_resp->payload_sz; 8683 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp, 8684 offsetof(struct smb2_read_rsp, Buffer), 8685 aux_payload_buf, nbytes); 8686 if (err) { 8687 kvfree(aux_payload_buf); 8688 goto out; 8689 } 8690 kvfree(rpc_resp); 8691 } else { 8692 err = ksmbd_iov_pin_rsp(work, (void *)rsp, 8693 offsetof(struct smb2_read_rsp, Buffer)); 8694 if (err) 8695 goto out; 8696 } 8697 8698 rsp->StructureSize = cpu_to_le16(17); 8699 rsp->DataOffset = 80; 8700 rsp->Reserved = 0; 8701 rsp->DataLength = cpu_to_le32(nbytes); 8702 rsp->DataRemaining = 0; 8703 rsp->Flags = 0; 8704 return 0; 8705 8706 out: 8707 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 8708 smb2_set_err_rsp(work); 8709 kvfree(rpc_resp); 8710 return err; 8711 } 8712 8713 /** 8714 * smb2_set_rdma_key() - validate descriptors and save invalidation state 8715 * @work: request work item 8716 * @desc: first RDMA buffer descriptor 8717 * @Channel: nested RDMA channel type 8718 * @channel_info_len: descriptor array length 8719 * 8720 * Return: 0 on success, otherwise -EINVAL 8721 */ 8722 static int smb2_set_rdma_key(struct ksmbd_work *work, 8723 struct smbdirect_buffer_descriptor_v1 *desc, 8724 __le32 Channel, __le16 channel_info_len) 8725 { 8726 unsigned int i, ch_count; 8727 8728 if (Channel != SMB2_CHANNEL_RDMA_V1 && 8729 Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) 8730 return -EINVAL; 8731 if (work->conn->dialect == SMB30_PROT_ID && 8732 Channel != SMB2_CHANNEL_RDMA_V1) 8733 return -EINVAL; 8734 if (le16_to_cpu(channel_info_len) % sizeof(*desc)) 8735 return -EINVAL; 8736 8737 ch_count = le16_to_cpu(channel_info_len) / sizeof(*desc); 8738 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) { 8739 for (i = 0; i < ch_count; i++) { 8740 pr_info("RDMA r/w request %#x: token %#x, length %#x\n", 8741 i, 8742 le32_to_cpu(desc[i].token), 8743 le32_to_cpu(desc[i].length)); 8744 } 8745 } 8746 if (!ch_count) 8747 return -EINVAL; 8748 8749 work->need_invalidate_rkey = 8750 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE); 8751 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) 8752 work->remote_key = le32_to_cpu(desc->token); 8753 return 0; 8754 } 8755 8756 /** 8757 * smb2_prep_rdma_read() - transform an RDMA READ payload 8758 * @work: request work item 8759 * @req: READ request controlling encryption or signing 8760 * @rsp: READ response receiving transform metadata 8761 * @data: data that will be transferred through RDMA 8762 * @datalen: data length 8763 * 8764 * Encrypt the payload in place and encode the detached crypto metadata in 8765 * the response buffer. 8766 * 8767 * Return: metadata length, zero when no transform applies, or negative errno 8768 */ 8769 static int smb2_prep_rdma_read(struct ksmbd_work *work, 8770 struct smb2_read_req *req, 8771 struct smb2_read_rsp *rsp, 8772 void *data, unsigned int datalen) 8773 { 8774 struct ksmbd_conn *conn = work->conn; 8775 struct smb2_rdma_transform *transform; 8776 struct smb2_rdma_crypto_transform *crypto; 8777 u8 *nonce; 8778 unsigned int nonce_len = 0, transform_len; 8779 u16 transform_type; 8780 int err; 8781 8782 if (!work->encrypted || 8783 !(conn->rdma_transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION))) 8784 return 0; 8785 8786 transform_type = SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION; 8787 nonce_len = (conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM || 8788 conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ? 8789 SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE; 8790 8791 transform = (struct smb2_rdma_transform *)rsp->Buffer; 8792 crypto = (struct smb2_rdma_crypto_transform *)(transform + 1); 8793 memset(transform, 0, sizeof(*transform) + sizeof(*crypto) + 8794 SMB2_SIGNATURE_SIZE + nonce_len); 8795 transform->Channel = SMB2_CHANNEL_NONE; 8796 transform->TransformCount = cpu_to_le16(1); 8797 8798 crypto->TransformType = cpu_to_le16(transform_type); 8799 crypto->SignatureLength = cpu_to_le16(SMB2_SIGNATURE_SIZE); 8800 crypto->NonceLength = cpu_to_le16(nonce_len); 8801 nonce = crypto->Signature + SMB2_SIGNATURE_SIZE; 8802 8803 get_random_bytes(nonce, nonce_len); 8804 err = ksmbd_crypt_rdma(conn, 8805 work->sess->smb3encryptionkey, 8806 data, datalen, nonce, nonce_len, 8807 crypto->Signature, 8808 SMB2_SIGNATURE_SIZE, true); 8809 if (err) { 8810 pr_err("RDMA READ encryption failed: session=%llu payload=%u rc=%d\n", 8811 work->sess->id, datalen, err); 8812 return err; 8813 } 8814 8815 transform_len = sizeof(*transform) + sizeof(*crypto) + 8816 SMB2_SIGNATURE_SIZE + nonce_len; 8817 rsp->Flags = SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM; 8818 rsp->DataLength = cpu_to_le32(transform_len); 8819 ksmbd_debug(RDMA, 8820 "RDMA READ encryption prepared: session=%llu cipher=0x%04x payload=%u transform=%u nonce=%u tag=%u\n", 8821 work->sess->id, le16_to_cpu(conn->cipher_type), datalen, 8822 transform_len, nonce_len, SMB2_SIGNATURE_SIZE); 8823 return transform_len; 8824 } 8825 8826 struct smb2_rdma_write_transform { 8827 struct smbdirect_buffer_descriptor_v1 *desc; 8828 struct smb2_rdma_crypto_transform *crypto; 8829 u8 *nonce; 8830 unsigned int desc_len; 8831 unsigned int nonce_len; 8832 unsigned int signature_len; 8833 u16 type; 8834 __le32 channel; 8835 }; 8836 8837 /** 8838 * smb2_current_req_len() - return the current compound request element size 8839 * @work: request work item 8840 * @hdr: current SMB2 header 8841 * 8842 * Return: current request element length measured from the SMB2 header 8843 */ 8844 static unsigned int smb2_current_req_len(struct ksmbd_work *work, 8845 struct smb2_hdr *hdr) 8846 { 8847 if (hdr->NextCommand) 8848 return le32_to_cpu(hdr->NextCommand); 8849 return get_rfc1002_len(work->request_buf) - 8850 work->next_smb2_rcv_hdr_off; 8851 } 8852 8853 /** 8854 * check_rdma_desc() - validate an RDMA descriptor array 8855 * @desc: descriptor array 8856 * @desc_len: descriptor array length 8857 * @required_len: minimum aggregate buffer length 8858 * 8859 * Return: 0 when the descriptors cover the transfer, otherwise -EINVAL 8860 */ 8861 static int check_rdma_desc(struct smbdirect_buffer_descriptor_v1 *desc, 8862 unsigned int desc_len, 8863 unsigned int required_len) 8864 { 8865 unsigned int i, count; 8866 u64 described_len = 0; 8867 8868 if (!desc_len || desc_len % sizeof(*desc)) 8869 return -EINVAL; 8870 count = desc_len / sizeof(*desc); 8871 if (!le32_to_cpu(desc[0].length)) 8872 return -EINVAL; 8873 for (i = 0; i < count; i++) 8874 described_len += le32_to_cpu(desc[i].length); 8875 return described_len < required_len ? -EINVAL : 0; 8876 } 8877 8878 /** 8879 * smb2_parse_rdma_write_transform() - validate RDMA WRITE transform metadata 8880 * @work: request work item 8881 * @req: WRITE request containing the transform 8882 * @info: parsed transform information 8883 * 8884 * Validate transform counts, crypto fields, descriptor alignment and bounds, 8885 * negotiated algorithms, and the nested RDMA channel. 8886 * 8887 * Return: 0 on success, otherwise a negative errno 8888 */ 8889 static int smb2_parse_rdma_write_transform(struct ksmbd_work *work, 8890 struct smb2_write_req *req, 8891 struct smb2_rdma_write_transform *info) 8892 { 8893 struct smb2_rdma_transform *transform; 8894 struct smb2_rdma_crypto_transform *crypto; 8895 unsigned int req_len = smb2_current_req_len(work, &req->hdr); 8896 unsigned int offset = le16_to_cpu(req->WriteChannelInfoOffset); 8897 unsigned int length = le16_to_cpu(req->WriteChannelInfoLength); 8898 unsigned int desc_offset, desc_len, crypto_len, expected_desc_offset; 8899 int err; 8900 8901 if (!work->conn->rdma_transform_ids || 8902 offset < offsetof(struct smb2_write_req, Buffer) || 8903 length < sizeof(*transform) || offset > req_len || 8904 length > req_len - offset) 8905 return -EINVAL; 8906 8907 transform = (struct smb2_rdma_transform *)((char *)req + offset); 8908 if (le16_to_cpu(transform->TransformCount) != 1 || 8909 (transform->Channel != SMB2_CHANNEL_RDMA_V1 && 8910 transform->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE)) 8911 return -EINVAL; 8912 8913 desc_offset = le16_to_cpu(transform->RdmaDescriptorOffset); 8914 desc_len = le16_to_cpu(transform->RdmaDescriptorLength); 8915 if (!desc_len || desc_len % sizeof(*info->desc) || 8916 desc_offset < sizeof(*transform) || desc_offset > length || 8917 desc_len > length - desc_offset) 8918 return -EINVAL; 8919 8920 crypto = (struct smb2_rdma_crypto_transform *)(transform + 1); 8921 if (length - sizeof(*transform) < sizeof(*crypto)) 8922 return -EINVAL; 8923 info->type = le16_to_cpu(crypto->TransformType); 8924 info->signature_len = le16_to_cpu(crypto->SignatureLength); 8925 info->nonce_len = le16_to_cpu(crypto->NonceLength); 8926 if (!info->signature_len) 8927 return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ? 8928 -EBADMSG : -EINVAL; 8929 if (info->signature_len > SMB2_SIGNATURE_SIZE) 8930 return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ? 8931 -EBADMSG : -EINVAL; 8932 if (info->signature_len > length - sizeof(*transform) - sizeof(*crypto) || 8933 info->nonce_len > length - sizeof(*transform) - sizeof(*crypto) - 8934 info->signature_len) 8935 return -EINVAL; 8936 8937 crypto_len = sizeof(*crypto) + info->signature_len + info->nonce_len; 8938 expected_desc_offset = ALIGN(sizeof(*transform) + crypto_len, 8); 8939 if (desc_offset != expected_desc_offset) 8940 return -EINVAL; 8941 8942 if (info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) { 8943 unsigned int expected_nonce_len; 8944 8945 if (!(work->conn->rdma_transform_ids & 8946 BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) || !work->encrypted) 8947 return -EINVAL; 8948 expected_nonce_len = 8949 (work->conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM || 8950 work->conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ? 8951 SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE; 8952 if (info->nonce_len != expected_nonce_len) 8953 return -EBADMSG; 8954 } else { 8955 return -EINVAL; 8956 } 8957 8958 info->desc = (struct smbdirect_buffer_descriptor_v1 *) 8959 ((char *)transform + desc_offset); 8960 info->desc_len = desc_len; 8961 info->crypto = crypto; 8962 info->nonce = crypto->Signature + info->signature_len; 8963 info->channel = transform->Channel; 8964 err = check_rdma_desc(info->desc, info->desc_len, 8965 le32_to_cpu(req->RemainingBytes)); 8966 if (err) 8967 return err; 8968 8969 ksmbd_debug(RDMA, 8970 "RDMA WRITE encryption metadata: session=%llu cipher=0x%04x payload=%u channel=0x%x descriptors=%zu nonce=%u tag=%u\n", 8971 work->sess->id, le16_to_cpu(work->conn->cipher_type), 8972 le32_to_cpu(req->RemainingBytes), le32_to_cpu(info->channel), 8973 info->desc_len / sizeof(*info->desc), info->nonce_len, 8974 info->signature_len); 8975 return 0; 8976 } 8977 8978 /** 8979 * smb2_read_rdma() - transfer READ data to client RDMA buffers 8980 * @work: request work item 8981 * @req: READ request containing client descriptors 8982 * @data_buf: data to transfer 8983 * @length: data length 8984 * 8985 * Return: transferred length on success, otherwise a negative errno 8986 */ 8987 static ssize_t smb2_read_rdma(struct ksmbd_work *work, 8988 struct smb2_read_req *req, void *data_buf, 8989 size_t length) 8990 { 8991 int err; 8992 8993 err = ksmbd_conn_rdma_write(work->conn, data_buf, length, 8994 (struct smbdirect_buffer_descriptor_v1 *) 8995 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)), 8996 le16_to_cpu(req->ReadChannelInfoLength)); 8997 if (err) 8998 return err; 8999 9000 return length; 9001 } 9002 9003 /** 9004 * smb2_read() - handler for smb2 read from file 9005 * @work: smb work containing read command buffer 9006 * 9007 * Return: 0 on success, otherwise error 9008 */ 9009 int smb2_read(struct ksmbd_work *work) 9010 { 9011 struct ksmbd_conn *conn = work->conn; 9012 struct smb2_read_req *req; 9013 struct smb2_read_rsp *rsp; 9014 struct ksmbd_file *fp = NULL; 9015 loff_t offset; 9016 size_t length, mincount; 9017 ssize_t nbytes = 0, remain_bytes = 0; 9018 int err = 0; 9019 int rdma_transform_len = 0; 9020 bool is_rdma_channel = false, async_interim = false; 9021 unsigned int max_read_size = conn->vals->max_read_size; 9022 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 9023 void *aux_payload_buf; 9024 9025 ksmbd_debug(SMB, "Received smb2 read request\n"); 9026 9027 if (test_share_config_flag(work->tcon->share_conf, 9028 KSMBD_SHARE_FLAG_PIPE)) { 9029 ksmbd_debug(SMB, "IPC pipe read request\n"); 9030 return smb2_read_pipe(work); 9031 } 9032 9033 if (work->next_smb2_rcv_hdr_off) { 9034 req = ksmbd_req_buf_next(work); 9035 rsp = ksmbd_resp_buf_next(work); 9036 if (smb2_compound_has_failed(work, &rsp->hdr)) 9037 return -EACCES; 9038 if (!has_file_id(req->VolatileFileId)) { 9039 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 9040 work->compound_fid); 9041 id = work->compound_fid; 9042 pid = work->compound_pfid; 9043 } 9044 } else { 9045 req = smb_get_msg(work->request_buf); 9046 rsp = smb_get_msg(work->response_buf); 9047 } 9048 9049 if (!has_file_id(id)) { 9050 id = req->VolatileFileId; 9051 pid = req->PersistentFileId; 9052 } 9053 9054 if (req->Channel != SMB2_CHANNEL_NONE && 9055 req->Channel != SMB2_CHANNEL_RDMA_V1 && 9056 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) { 9057 err = -EINVAL; 9058 goto out; 9059 } 9060 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE || 9061 req->Channel == SMB2_CHANNEL_RDMA_V1) { 9062 is_rdma_channel = true; 9063 max_read_size = get_smbd_max_read_write_size(work->conn->transport); 9064 if (max_read_size == 0) { 9065 err = -EINVAL; 9066 goto out; 9067 } 9068 } 9069 9070 if (is_rdma_channel == true) { 9071 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset); 9072 unsigned int ch_len = le16_to_cpu(req->ReadChannelInfoLength); 9073 unsigned int req_len = smb2_current_req_len(work, &req->hdr); 9074 struct smbdirect_buffer_descriptor_v1 *desc; 9075 9076 if (!le32_to_cpu(req->Length) || 9077 ch_offset < offsetof(struct smb2_read_req, Buffer) || 9078 ch_offset > req_len || ch_len > req_len - ch_offset) { 9079 err = -EINVAL; 9080 goto out; 9081 } 9082 desc = (struct smbdirect_buffer_descriptor_v1 *) 9083 ((char *)req + ch_offset); 9084 err = check_rdma_desc(desc, ch_len, le32_to_cpu(req->Length)); 9085 if (err) 9086 goto out; 9087 err = smb2_set_rdma_key(work, desc, 9088 req->Channel, 9089 req->ReadChannelInfoLength); 9090 if (err) 9091 goto out; 9092 } 9093 9094 fp = ksmbd_lookup_fd_slow(work, id, pid); 9095 if (!fp) { 9096 err = -ENOENT; 9097 goto out; 9098 } 9099 9100 err = smb2_set_request_open(work, fp, &req->hdr, true, true); 9101 if (err) 9102 goto out; 9103 9104 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) { 9105 pr_err("Not permitted to read : 0x%x\n", fp->daccess); 9106 err = -EACCES; 9107 goto out; 9108 } 9109 9110 if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) { 9111 err = setup_async_work(work, NULL, NULL); 9112 if (err) 9113 goto out; 9114 smb2_send_interim_resp(work, STATUS_PENDING); 9115 async_interim = true; 9116 } 9117 9118 offset = le64_to_cpu(req->Offset); 9119 if (offset < 0) { 9120 err = -EINVAL; 9121 goto out; 9122 } 9123 length = le32_to_cpu(req->Length); 9124 mincount = le32_to_cpu(req->MinimumCount); 9125 9126 if (length > max_read_size) { 9127 ksmbd_debug(SMB, "limiting read size to max size(%u)\n", 9128 max_read_size); 9129 err = -EINVAL; 9130 goto out; 9131 } 9132 9133 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n", 9134 fp->filp, offset, length); 9135 9136 aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP); 9137 if (!aux_payload_buf) { 9138 err = -ENOMEM; 9139 goto out; 9140 } 9141 9142 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf); 9143 if (nbytes < 0) { 9144 kvfree(aux_payload_buf); 9145 err = nbytes; 9146 goto out; 9147 } 9148 9149 /* 9150 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8)) 9151 * tail of the un-zeroed buffer is transmitted as compound-response 9152 * alignment padding, leaking uninitialized kernel memory to the 9153 * client. Zero just that tail. 9154 */ 9155 if (nbytes & 7) 9156 memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes); 9157 9158 if ((nbytes == 0 && length != 0) || nbytes < mincount) { 9159 kvfree(aux_payload_buf); 9160 rsp->hdr.Status = STATUS_END_OF_FILE; 9161 smb2_set_err_rsp(work); 9162 if (async_interim) 9163 release_async_work(work); 9164 ksmbd_fd_put(work, fp); 9165 return -ENODATA; 9166 } 9167 9168 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n", 9169 nbytes, offset, mincount); 9170 9171 if (is_rdma_channel == true) { 9172 rdma_transform_len = smb2_prep_rdma_read(work, req, 9173 rsp, 9174 aux_payload_buf, 9175 nbytes); 9176 if (rdma_transform_len < 0) { 9177 kvfree(aux_payload_buf); 9178 err = rdma_transform_len; 9179 goto out; 9180 } 9181 /* write data to the client using rdma channel */ 9182 remain_bytes = smb2_read_rdma(work, req, 9183 aux_payload_buf, 9184 nbytes); 9185 if (remain_bytes < 0) 9186 pr_err("RDMA READ transfer failed: session=%llu payload=%zu transform=%d rc=%zd\n", 9187 work->sess ? work->sess->id : 0, nbytes, 9188 rdma_transform_len, remain_bytes); 9189 else 9190 ksmbd_debug(RDMA, 9191 "RDMA READ transfer completed: session=%llu payload=%zu transform=%d\n", 9192 work->sess ? work->sess->id : 0, nbytes, 9193 rdma_transform_len); 9194 kvfree(aux_payload_buf); 9195 aux_payload_buf = NULL; 9196 nbytes = 0; 9197 if (remain_bytes < 0) { 9198 err = (int)remain_bytes; 9199 goto out; 9200 } 9201 } 9202 9203 rsp->StructureSize = cpu_to_le16(17); 9204 rsp->DataOffset = 80; 9205 rsp->Reserved = 0; 9206 rsp->DataLength = cpu_to_le32(rdma_transform_len ?: nbytes); 9207 rsp->DataRemaining = cpu_to_le32(remain_bytes); 9208 rsp->Flags = rdma_transform_len ? 9209 SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM : 0; 9210 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp, 9211 offsetof(struct smb2_read_rsp, Buffer) + 9212 rdma_transform_len, 9213 aux_payload_buf, nbytes); 9214 if (err) { 9215 kvfree(aux_payload_buf); 9216 goto out; 9217 } 9218 if (async_interim) 9219 release_async_work(work); 9220 /* 9221 * RDMA responses are transferred through channel buffers and encrypted 9222 * responses use the encryption transform, so only normal SMB transport 9223 * responses are candidates for compression. 9224 */ 9225 if (!is_rdma_channel && nbytes && 9226 (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) && 9227 conn->compress_algorithm != SMB3_COMPRESS_NONE) 9228 work->compress_response = true; 9229 ksmbd_fd_put(work, fp); 9230 return 0; 9231 9232 out: 9233 if (async_interim) 9234 release_async_work(work); 9235 if (err) { 9236 if (err == -EISDIR) 9237 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST; 9238 else if (err == -EAGAIN) 9239 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 9240 else if (err == -ENOENT) 9241 rsp->hdr.Status = STATUS_FILE_CLOSED; 9242 else if (err == -EACCES) 9243 rsp->hdr.Status = STATUS_ACCESS_DENIED; 9244 else if (err == -ESHARE) 9245 rsp->hdr.Status = STATUS_SHARING_VIOLATION; 9246 else if (err == -EINVAL) 9247 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 9248 else 9249 rsp->hdr.Status = STATUS_INVALID_HANDLE; 9250 9251 smb2_set_err_rsp(work); 9252 } 9253 ksmbd_fd_put(work, fp); 9254 return err; 9255 } 9256 9257 /** 9258 * smb2_write_pipe() - handler for smb2 write on IPC pipe 9259 * @work: smb work containing write IPC pipe command buffer 9260 * 9261 * Return: 0 on success, otherwise error 9262 */ 9263 static noinline int smb2_write_pipe(struct ksmbd_work *work) 9264 { 9265 struct smb2_write_req *req; 9266 struct smb2_write_rsp *rsp; 9267 struct ksmbd_rpc_command *rpc_resp; 9268 u64 id = 0; 9269 int err = 0, ret = 0; 9270 char *data_buf; 9271 size_t length; 9272 9273 WORK_BUFFERS(work, req, rsp); 9274 9275 length = le32_to_cpu(req->Length); 9276 id = req->VolatileFileId; 9277 9278 if ((u64)le16_to_cpu(req->DataOffset) + length > 9279 get_rfc1002_len(work->request_buf)) { 9280 pr_err("invalid write data offset %u, smb_len %u\n", 9281 le16_to_cpu(req->DataOffset), 9282 get_rfc1002_len(work->request_buf)); 9283 err = -EINVAL; 9284 goto out; 9285 } 9286 9287 data_buf = (char *)(((char *)&req->hdr.ProtocolId) + 9288 le16_to_cpu(req->DataOffset)); 9289 9290 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length); 9291 if (rpc_resp) { 9292 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { 9293 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 9294 kvfree(rpc_resp); 9295 smb2_set_err_rsp(work); 9296 return -EOPNOTSUPP; 9297 } 9298 if (rpc_resp->flags != KSMBD_RPC_OK) { 9299 rsp->hdr.Status = STATUS_INVALID_HANDLE; 9300 smb2_set_err_rsp(work); 9301 kvfree(rpc_resp); 9302 return ret; 9303 } 9304 kvfree(rpc_resp); 9305 } 9306 9307 rsp->StructureSize = cpu_to_le16(17); 9308 rsp->DataOffset = 0; 9309 rsp->Reserved = 0; 9310 rsp->DataLength = cpu_to_le32(length); 9311 rsp->DataRemaining = 0; 9312 rsp->Reserved2 = 0; 9313 err = ksmbd_iov_pin_rsp(work, (void *)rsp, 9314 offsetof(struct smb2_write_rsp, Buffer)); 9315 out: 9316 if (err) { 9317 rsp->hdr.Status = STATUS_INVALID_HANDLE; 9318 smb2_set_err_rsp(work); 9319 } 9320 9321 return err; 9322 } 9323 9324 /** 9325 * smb2_write_rdma() - receive and store an RDMA WRITE payload 9326 * @work: request work item 9327 * @desc: client RDMA buffer descriptors 9328 * @desc_len: descriptor array length 9329 * @transform: parsed transform, or NULL for an untransformed transfer 9330 * @fp: target open file 9331 * @offset: target file offset 9332 * @length: transfer length 9333 * @sync: request synchronous storage completion 9334 * 9335 * Receive the payload, authenticate or decrypt it when required, and write it 9336 * to the target file. 9337 * 9338 * Return: written byte count on success, otherwise a negative errno 9339 */ 9340 static ssize_t smb2_write_rdma(struct ksmbd_work *work, 9341 struct smbdirect_buffer_descriptor_v1 *desc, 9342 unsigned int desc_len, 9343 struct smb2_rdma_write_transform *transform, 9344 struct ksmbd_file *fp, loff_t offset, 9345 size_t length, bool sync) 9346 { 9347 char *data_buf; 9348 int ret; 9349 ssize_t nbytes; 9350 9351 data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP); 9352 if (!data_buf) 9353 return -ENOMEM; 9354 9355 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length, desc, 9356 desc_len); 9357 if (ret < 0) { 9358 if (transform) 9359 pr_err("RDMA WRITE encrypted transfer failed: session=%llu payload=%zu rdma_read_rc=%d\n", 9360 work->sess->id, length, ret); 9361 kvfree(data_buf); 9362 return ret; 9363 } 9364 if (transform && 9365 transform->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) { 9366 ret = ksmbd_crypt_rdma(work->conn, 9367 work->sess->smb3decryptionkey, 9368 data_buf, length, transform->nonce, 9369 transform->nonce_len, 9370 transform->crypto->Signature, 9371 transform->signature_len, false); 9372 if (ret) { 9373 pr_err("RDMA WRITE decryption failed: session=%llu payload=%zu rc=%d\n", 9374 work->sess->id, length, ret); 9375 kvfree(data_buf); 9376 return ret == -ENOMEM ? ret : -EBADMSG; 9377 } 9378 } 9379 9380 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes); 9381 kvfree(data_buf); 9382 if (ret < 0) { 9383 if (transform) 9384 pr_err("RDMA WRITE encrypted file write failed: session=%llu payload=%zu rc=%d\n", 9385 work->sess->id, length, ret); 9386 return ret; 9387 } 9388 ksmbd_debug(RDMA, 9389 "RDMA WRITE transfer completed: session=%llu payload=%zu transformed=%u written=%zd\n", 9390 work->sess ? work->sess->id : 0, length, !!transform, nbytes); 9391 9392 return nbytes; 9393 } 9394 9395 /** 9396 * smb2_write() - handler for smb2 write from file 9397 * @work: smb work containing write command buffer 9398 * 9399 * Return: 0 on success, otherwise error 9400 */ 9401 int smb2_write(struct ksmbd_work *work) 9402 { 9403 struct smb2_write_req *req; 9404 struct smb2_write_rsp *rsp; 9405 struct smb2_rdma_write_transform rdma_transform = {}; 9406 struct smb2_rdma_write_transform *rdma_info = NULL; 9407 struct smbdirect_buffer_descriptor_v1 *rdma_desc = NULL; 9408 unsigned int rdma_desc_len = 0; 9409 struct ksmbd_file *fp = NULL; 9410 loff_t offset; 9411 size_t length; 9412 ssize_t nbytes; 9413 char *data_buf; 9414 bool writethrough = false, is_rdma_channel = false; 9415 bool async_interim = false; 9416 bool chseq_err = false; 9417 int err = 0; 9418 unsigned int max_write_size = work->conn->vals->max_write_size; 9419 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 9420 9421 ksmbd_debug(SMB, "Received smb2 write request\n"); 9422 9423 WORK_BUFFERS(work, req, rsp); 9424 9425 if (smb2_compound_has_failed(work, &rsp->hdr)) 9426 return -EACCES; 9427 9428 if (work->next_smb2_rcv_hdr_off && 9429 !has_file_id(req->VolatileFileId)) { 9430 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 9431 work->compound_fid); 9432 id = work->compound_fid; 9433 pid = work->compound_pfid; 9434 } 9435 9436 if (!has_file_id(id)) { 9437 id = req->VolatileFileId; 9438 pid = req->PersistentFileId; 9439 } 9440 9441 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) { 9442 ksmbd_debug(SMB, "IPC pipe write request\n"); 9443 return smb2_write_pipe(work); 9444 } 9445 9446 offset = le64_to_cpu(req->Offset); 9447 if (offset < 0) { 9448 err = -EINVAL; 9449 goto out; 9450 } 9451 length = le32_to_cpu(req->Length); 9452 9453 if (req->Channel != SMB2_CHANNEL_NONE && 9454 req->Channel != SMB2_CHANNEL_RDMA_V1 && 9455 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE && 9456 req->Channel != SMB2_CHANNEL_RDMA_TRANSFORM) { 9457 err = -EINVAL; 9458 goto out; 9459 } 9460 if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM && 9461 work->conn->dialect != SMB311_PROT_ID) { 9462 err = -EINVAL; 9463 goto out; 9464 } 9465 if (req->Channel == SMB2_CHANNEL_RDMA_V1 || 9466 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE || 9467 req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) { 9468 is_rdma_channel = true; 9469 max_write_size = get_smbd_max_read_write_size(work->conn->transport); 9470 if (max_write_size == 0) { 9471 err = -EINVAL; 9472 goto out; 9473 } 9474 length = le32_to_cpu(req->RemainingBytes); 9475 } 9476 9477 if (length) { 9478 u64 end = (u64)offset + length; 9479 9480 if (end > SMB2_MAX_FILE_SIZE) { 9481 err = -EINVAL; 9482 goto out; 9483 } 9484 if (end == SMB2_MAX_FILE_SIZE) { 9485 err = -EFBIG; 9486 goto out; 9487 } 9488 } 9489 9490 if (is_rdma_channel == true) { 9491 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset); 9492 unsigned int ch_len = le16_to_cpu(req->WriteChannelInfoLength); 9493 unsigned int req_len = smb2_current_req_len(work, &req->hdr); 9494 9495 if (!length || req->Length != 0 || req->DataOffset != 0 || 9496 ch_offset < offsetof(struct smb2_write_req, Buffer) || 9497 ch_offset > req_len || ch_len > req_len - ch_offset) { 9498 err = -EINVAL; 9499 goto out; 9500 } 9501 if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) { 9502 err = smb2_parse_rdma_write_transform(work, req, 9503 &rdma_transform); 9504 if (err) { 9505 pr_err("RDMA WRITE encryption metadata rejected: session=%llu rc=%d\n", 9506 work->sess ? work->sess->id : 0, err); 9507 goto out; 9508 } 9509 rdma_desc = rdma_transform.desc; 9510 rdma_desc_len = rdma_transform.desc_len; 9511 rdma_info = &rdma_transform; 9512 err = smb2_set_rdma_key(work, rdma_desc, 9513 rdma_transform.channel, 9514 cpu_to_le16(rdma_desc_len)); 9515 } else { 9516 rdma_desc = (struct smbdirect_buffer_descriptor_v1 *) 9517 ((char *)req + ch_offset); 9518 rdma_desc_len = ch_len; 9519 err = check_rdma_desc(rdma_desc, rdma_desc_len, length); 9520 if (err) 9521 goto out; 9522 err = smb2_set_rdma_key(work, rdma_desc, 9523 req->Channel, 9524 req->WriteChannelInfoLength); 9525 } 9526 if (err) 9527 goto out; 9528 } 9529 9530 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 9531 ksmbd_debug(SMB, "User does not have write permission\n"); 9532 err = -EACCES; 9533 goto out; 9534 } 9535 9536 fp = ksmbd_lookup_fd_slow(work, id, pid); 9537 if (!fp) { 9538 err = -ENOENT; 9539 goto out; 9540 } 9541 9542 err = smb2_set_request_open(work, fp, &req->hdr, true, false); 9543 if (err) { 9544 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE; 9545 chseq_err = true; 9546 goto out; 9547 } 9548 9549 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) { 9550 pr_err("Not permitted to write : 0x%x\n", fp->daccess); 9551 err = -EACCES; 9552 goto out; 9553 } 9554 9555 if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) { 9556 err = setup_async_work(work, NULL, NULL); 9557 if (err) 9558 goto out; 9559 smb2_send_interim_resp(work, STATUS_PENDING); 9560 async_interim = true; 9561 } 9562 9563 if (length > max_write_size) { 9564 ksmbd_debug(SMB, "limiting write size to max size(%u)\n", 9565 max_write_size); 9566 err = -EINVAL; 9567 goto out; 9568 } 9569 9570 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags)); 9571 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH) 9572 writethrough = true; 9573 9574 if (is_rdma_channel == false) { 9575 if (le16_to_cpu(req->DataOffset) < 9576 offsetof(struct smb2_write_req, Buffer)) { 9577 err = -EINVAL; 9578 goto out; 9579 } 9580 9581 data_buf = (char *)(((char *)&req->hdr.ProtocolId) + 9582 le16_to_cpu(req->DataOffset)); 9583 9584 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n", 9585 fp->filp, offset, length); 9586 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset, 9587 writethrough, &nbytes); 9588 if (err < 0) 9589 goto out; 9590 } else { 9591 /* read data from the client using rdma channel, and 9592 * write the data. 9593 */ 9594 nbytes = smb2_write_rdma(work, rdma_desc, rdma_desc_len, 9595 rdma_info, fp, offset, length, 9596 writethrough); 9597 if (nbytes < 0) { 9598 err = (int)nbytes; 9599 goto out; 9600 } 9601 } 9602 9603 rsp->StructureSize = cpu_to_le16(17); 9604 rsp->DataOffset = 0; 9605 rsp->Reserved = 0; 9606 rsp->DataLength = cpu_to_le32(nbytes); 9607 rsp->DataRemaining = 0; 9608 rsp->Reserved2 = 0; 9609 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer)); 9610 if (err) 9611 goto out; 9612 if (async_interim) 9613 release_async_work(work); 9614 ksmbd_fd_put(work, fp); 9615 return 0; 9616 9617 out: 9618 if (async_interim) 9619 release_async_work(work); 9620 9621 if (err == -EAGAIN && !chseq_err) 9622 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 9623 else if (err == -ENOSPC || err == -EFBIG) 9624 rsp->hdr.Status = STATUS_DISK_FULL; 9625 else if (err == -ENOENT) 9626 rsp->hdr.Status = STATUS_FILE_CLOSED; 9627 else if (err == -EACCES) 9628 rsp->hdr.Status = STATUS_ACCESS_DENIED; 9629 else if (err == -ESHARE) 9630 rsp->hdr.Status = STATUS_SHARING_VIOLATION; 9631 else if (err == -EINVAL) 9632 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 9633 else if (err == -EBADMSG) 9634 rsp->hdr.Status = STATUS_AUTH_TAG_MISMATCH; 9635 else if (err == -EKEYREJECTED) 9636 rsp->hdr.Status = STATUS_INVALID_SIGNATURE; 9637 else if (rsp->hdr.Status == 0) 9638 rsp->hdr.Status = STATUS_INVALID_HANDLE; 9639 9640 smb2_set_err_rsp(work); 9641 ksmbd_fd_put(work, fp); 9642 return err; 9643 } 9644 9645 /** 9646 * smb2_flush() - handler for smb2 flush file - fsync 9647 * @work: smb work containing flush command buffer 9648 * 9649 * Return: 0 on success, otherwise error 9650 */ 9651 int smb2_flush(struct ksmbd_work *work) 9652 { 9653 struct smb2_flush_req *req; 9654 struct smb2_flush_rsp *rsp; 9655 u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 9656 int err; 9657 9658 WORK_BUFFERS(work, req, rsp); 9659 9660 ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId); 9661 9662 if (smb2_compound_has_failed(work, &rsp->hdr)) 9663 return -EACCES; 9664 9665 if (work->next_smb2_rcv_hdr_off && 9666 !has_file_id(req->VolatileFileId)) { 9667 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 9668 work->compound_fid); 9669 id = work->compound_fid; 9670 pid = work->compound_pfid; 9671 } 9672 9673 if (!has_file_id(id)) { 9674 id = req->VolatileFileId; 9675 pid = req->PersistentFileId; 9676 } 9677 9678 err = ksmbd_vfs_fsync(work, id, pid); 9679 if (err) 9680 goto out; 9681 9682 rsp->StructureSize = cpu_to_le16(4); 9683 rsp->Reserved = 0; 9684 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp)); 9685 9686 out: 9687 rsp->hdr.Status = STATUS_INVALID_HANDLE; 9688 smb2_set_err_rsp(work); 9689 return err; 9690 } 9691 9692 /** 9693 * smb2_cancel() - handler for smb2 cancel command 9694 * @work: smb work containing cancel command buffer 9695 * 9696 * Return: 0 on success, otherwise error 9697 */ 9698 int smb2_cancel(struct ksmbd_work *work) 9699 { 9700 struct ksmbd_conn *conn = work->conn; 9701 struct smb2_hdr *hdr = smb_get_msg(work->request_buf); 9702 struct smb2_hdr *chdr; 9703 struct ksmbd_work *iter; 9704 struct ksmbd_work *cancelled_notify = NULL; 9705 struct list_head *command_list; 9706 9707 if (work->next_smb2_rcv_hdr_off) 9708 hdr = ksmbd_resp_buf_next(work); 9709 9710 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n", 9711 le64_to_cpu(hdr->MessageId), 9712 le32_to_cpu(hdr->Flags)); 9713 9714 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) { 9715 command_list = &conn->async_requests; 9716 9717 spin_lock(&conn->request_lock); 9718 list_for_each_entry(iter, command_list, 9719 async_request_entry) { 9720 chdr = smb_get_msg(iter->request_buf); 9721 9722 if (iter->async_id != 9723 le64_to_cpu(hdr->Id.AsyncId)) 9724 continue; 9725 9726 /* 9727 * Only an ACTIVE deferred work may have its cancel_fn 9728 * fired. A CANCELLED or CLOSED work already took the 9729 * smb2_lock() non-ACTIVE early-exit that frees the 9730 * file_lock and skips release_async_work(), so it is 9731 * still on conn->async_requests with a live cancel_fn 9732 * pointing at the freed file_lock. 9733 */ 9734 if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE, 9735 KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE) 9736 break; 9737 9738 ksmbd_debug(SMB, 9739 "smb2 with AsyncId %llu cancelled command = 0x%x\n", 9740 le64_to_cpu(hdr->Id.AsyncId), 9741 le16_to_cpu(chdr->Command)); 9742 if (iter->cancel_fn == smb2_notify_cancel_fn) 9743 cancelled_notify = 9744 smb2_notify_cancel_claim(iter->cancel_argv); 9745 else if (iter->cancel_fn) 9746 iter->cancel_fn(iter->cancel_argv); 9747 break; 9748 } 9749 spin_unlock(&conn->request_lock); 9750 9751 /* 9752 * Complete a cancelled notify before this CANCEL handler returns. 9753 * Deferring it to the system workqueue lets a following request and 9754 * its response overtake STATUS_CANCELLED, leaving clients waiting 9755 * for the original notify even though the cancellation was accepted. 9756 */ 9757 if (cancelled_notify) 9758 smb2_complete_notify_cancel(cancelled_notify); 9759 } else { 9760 command_list = &conn->requests; 9761 9762 spin_lock(&conn->request_lock); 9763 list_for_each_entry(iter, command_list, request_entry) { 9764 chdr = smb_get_msg(iter->request_buf); 9765 9766 if (chdr->MessageId != hdr->MessageId || 9767 iter == work) 9768 continue; 9769 9770 if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE, 9771 KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE) 9772 break; 9773 9774 ksmbd_debug(SMB, 9775 "smb2 with mid %llu cancelled command = 0x%x\n", 9776 le64_to_cpu(hdr->MessageId), 9777 le16_to_cpu(chdr->Command)); 9778 if (iter->cancel_fn) 9779 iter->cancel_fn(iter->cancel_argv); 9780 break; 9781 } 9782 spin_unlock(&conn->request_lock); 9783 } 9784 9785 /* For SMB2_CANCEL command itself send no response*/ 9786 work->send_no_response = 1; 9787 return 0; 9788 } 9789 9790 struct file_lock *smb_flock_init(struct file *f) 9791 { 9792 struct file_lock *fl; 9793 9794 fl = locks_alloc_lock(); 9795 if (!fl) 9796 goto out; 9797 9798 locks_init_lock(fl); 9799 9800 fl->c.flc_owner = f; 9801 fl->c.flc_pid = current->tgid; 9802 fl->c.flc_file = f; 9803 fl->c.flc_flags = FL_POSIX; 9804 fl->fl_ops = NULL; 9805 fl->fl_lmops = NULL; 9806 9807 out: 9808 return fl; 9809 } 9810 9811 static int smb2_set_flock_flags(struct file_lock *flock, int flags) 9812 { 9813 int cmd = -EINVAL; 9814 9815 /* Checking for wrong flag combination during lock request*/ 9816 switch (flags) { 9817 case SMB2_LOCKFLAG_SHARED: 9818 ksmbd_debug(SMB, "received shared request\n"); 9819 cmd = F_SETLKW; 9820 flock->c.flc_type = F_RDLCK; 9821 flock->c.flc_flags |= FL_SLEEP; 9822 break; 9823 case SMB2_LOCKFLAG_EXCLUSIVE: 9824 ksmbd_debug(SMB, "received exclusive request\n"); 9825 cmd = F_SETLKW; 9826 flock->c.flc_type = F_WRLCK; 9827 flock->c.flc_flags |= FL_SLEEP; 9828 break; 9829 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY: 9830 ksmbd_debug(SMB, 9831 "received shared & fail immediately request\n"); 9832 cmd = F_SETLK; 9833 flock->c.flc_type = F_RDLCK; 9834 break; 9835 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY: 9836 ksmbd_debug(SMB, 9837 "received exclusive & fail immediately request\n"); 9838 cmd = F_SETLK; 9839 flock->c.flc_type = F_WRLCK; 9840 break; 9841 case SMB2_LOCKFLAG_UNLOCK: 9842 ksmbd_debug(SMB, "received unlock request\n"); 9843 flock->c.flc_type = F_UNLCK; 9844 cmd = F_SETLK; 9845 break; 9846 } 9847 9848 return cmd; 9849 } 9850 9851 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock, 9852 unsigned int cmd, int flags, bool zero_len, 9853 struct list_head *lock_list) 9854 { 9855 struct ksmbd_lock *lock; 9856 9857 lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP); 9858 if (!lock) 9859 return NULL; 9860 9861 lock->cmd = cmd; 9862 lock->fl = flock; 9863 lock->start = flock->fl_start; 9864 lock->end = flock->fl_end; 9865 lock->flags = flags; 9866 lock->zero_len = zero_len; 9867 INIT_LIST_HEAD(&lock->clist); 9868 INIT_LIST_HEAD(&lock->flist); 9869 INIT_LIST_HEAD(&lock->llist); 9870 list_add_tail(&lock->llist, lock_list); 9871 9872 return lock; 9873 } 9874 9875 static void smb2_remove_blocked_lock(void **argv) 9876 { 9877 struct file_lock *flock = (struct file_lock *)argv[0]; 9878 9879 ksmbd_vfs_posix_lock_unblock(flock); 9880 locks_wake_up(flock); 9881 } 9882 9883 static void smb2_free_lock(struct file_lock *flock) 9884 { 9885 ksmbd_vfs_posix_lock_unblock(flock); 9886 locks_free_lock(flock); 9887 } 9888 9889 static void smb2_free_blocked_lock(struct file_lock *flock) 9890 { 9891 ksmbd_vfs_posix_lock_unblock(flock); 9892 locks_wake_up(flock); 9893 locks_free_lock(flock); 9894 } 9895 9896 static inline bool lock_defer_pending(struct file_lock *fl) 9897 { 9898 /* check pending lock waiters */ 9899 return waitqueue_active(&fl->c.flc_wait); 9900 } 9901 9902 /** 9903 * smb2_lock() - handler for smb2 file lock command 9904 * @work: smb work containing lock command buffer 9905 * 9906 * Return: 0 on success, otherwise error 9907 */ 9908 int smb2_lock(struct ksmbd_work *work) 9909 { 9910 struct smb2_lock_req *req; 9911 struct smb2_lock_rsp *rsp; 9912 struct smb2_lock_element *lock_ele; 9913 struct ksmbd_file *fp = NULL; 9914 struct file_lock *flock = NULL; 9915 struct file *filp = NULL; 9916 int lock_count; 9917 int flags = 0; 9918 int cmd = 0; 9919 int err = -EIO, i, rc = 0; 9920 u64 lock_start, lock_length; 9921 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2; 9922 struct ksmbd_conn *conn; 9923 int nolock = 0; 9924 LIST_HEAD(lock_list); 9925 LIST_HEAD(rollback_list); 9926 int prior_lock = 0, bkt; 9927 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 9928 bool lock_replayed; 9929 9930 WORK_BUFFERS(work, req, rsp); 9931 9932 ksmbd_debug(SMB, "Received smb2 lock request\n"); 9933 9934 if (smb2_compound_has_failed(work, &rsp->hdr)) 9935 return -EACCES; 9936 9937 if (work->next_smb2_rcv_hdr_off && 9938 !has_file_id(req->VolatileFileId)) { 9939 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 9940 work->compound_fid); 9941 id = work->compound_fid; 9942 pid = work->compound_pfid; 9943 } 9944 9945 if (!has_file_id(id)) { 9946 id = req->VolatileFileId; 9947 pid = req->PersistentFileId; 9948 } 9949 9950 fp = ksmbd_lookup_fd_slow(work, id, pid); 9951 if (!fp) { 9952 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId); 9953 err = -ENOENT; 9954 goto out2; 9955 } 9956 9957 err = smb2_set_request_open(work, fp, &req->hdr, false, false); 9958 if (err) 9959 goto out2; 9960 9961 lock_replayed = smb2_verify_lock_sequence(work, fp, req); 9962 if (lock_replayed) 9963 goto lock_success; 9964 9965 filp = fp->filp; 9966 lock_count = le16_to_cpu(req->LockCount); 9967 lock_ele = req->locks; 9968 9969 ksmbd_debug(SMB, "lock count is %d\n", lock_count); 9970 /* 9971 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray 9972 * as exactly 64 entries so 64 is the intended ceiling. No real workload 9973 * comes close to this in a single request. 9974 */ 9975 if (!lock_count || lock_count > 64) { 9976 err = -EINVAL; 9977 goto out2; 9978 } 9979 9980 for (i = 0; i < lock_count; i++) { 9981 flags = le32_to_cpu(lock_ele[i].Flags); 9982 9983 flock = smb_flock_init(filp); 9984 if (!flock) 9985 goto out; 9986 9987 cmd = smb2_set_flock_flags(flock, flags); 9988 9989 lock_start = le64_to_cpu(lock_ele[i].Offset); 9990 lock_length = le64_to_cpu(lock_ele[i].Length); 9991 if (lock_start > OFFSET_MAX || 9992 (lock_length && 9993 lock_length - 1 > OFFSET_MAX - lock_start)) { 9994 pr_err("Invalid lock range requested\n"); 9995 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE; 9996 locks_free_lock(flock); 9997 goto out; 9998 } 9999 10000 flock->fl_start = lock_start; 10001 flock->fl_end = lock_length ? 10002 flock->fl_start + lock_length - 1 : flock->fl_start; 10003 10004 /* Check conflict locks in one request */ 10005 list_for_each_entry(cmp_lock, &lock_list, llist) { 10006 if (cmp_lock->fl->fl_start <= flock->fl_start && 10007 cmp_lock->fl->fl_end >= flock->fl_end) { 10008 if (cmp_lock->fl->c.flc_type != F_UNLCK && 10009 flock->c.flc_type != F_UNLCK) { 10010 pr_err("conflict two locks in one request\n"); 10011 err = -EINVAL; 10012 locks_free_lock(flock); 10013 goto out; 10014 } 10015 } 10016 } 10017 10018 smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length, 10019 &lock_list); 10020 if (!smb_lock) { 10021 err = -EINVAL; 10022 locks_free_lock(flock); 10023 goto out; 10024 } 10025 } 10026 10027 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) { 10028 if (lock_count > 1 && 10029 !(le32_to_cpu(lock_ele[0].Flags) & SMB2_LOCKFLAG_UNLOCK) && 10030 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) { 10031 err = -EINVAL; 10032 goto out; 10033 } 10034 10035 if (smb_lock->cmd < 0) { 10036 err = -EINVAL; 10037 goto out; 10038 } 10039 10040 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) { 10041 err = -EINVAL; 10042 goto out; 10043 } 10044 10045 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) && 10046 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) || 10047 (prior_lock == SMB2_LOCKFLAG_UNLOCK && 10048 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) { 10049 err = -EINVAL; 10050 goto out; 10051 } 10052 10053 prior_lock = smb_lock->flags; 10054 10055 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) && 10056 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) 10057 goto no_check_cl; 10058 10059 nolock = 1; 10060 /* check locks in connection list */ 10061 down_read(&conn_list_lock); 10062 hash_for_each(conn_list, bkt, conn, hlist) { 10063 spin_lock(&conn->llist_lock); 10064 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) { 10065 if (file_inode(cmp_lock->fl->c.flc_file) != 10066 file_inode(smb_lock->fl->c.flc_file)) 10067 continue; 10068 10069 if (lock_is_unlock(smb_lock->fl)) { 10070 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file && 10071 cmp_lock->start == smb_lock->start && 10072 cmp_lock->end == smb_lock->end && 10073 !lock_defer_pending(cmp_lock->fl)) { 10074 nolock = 0; 10075 list_del_init(&cmp_lock->flist); 10076 list_del_init(&cmp_lock->clist); 10077 cmp_lock->conn = NULL; 10078 spin_unlock(&conn->llist_lock); 10079 up_read(&conn_list_lock); 10080 10081 ksmbd_conn_put(conn); 10082 smb2_free_lock(cmp_lock->fl); 10083 kfree(cmp_lock); 10084 goto out_check_cl; 10085 } 10086 continue; 10087 } 10088 10089 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) { 10090 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED) 10091 continue; 10092 } else { 10093 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED) 10094 continue; 10095 } 10096 10097 /* check zero byte lock range */ 10098 if (cmp_lock->zero_len && !smb_lock->zero_len && 10099 cmp_lock->start > smb_lock->start && 10100 cmp_lock->start <= smb_lock->end) { 10101 spin_unlock(&conn->llist_lock); 10102 up_read(&conn_list_lock); 10103 pr_err("previous lock conflict with zero byte lock range\n"); 10104 goto out; 10105 } 10106 10107 if (smb_lock->zero_len && !cmp_lock->zero_len && 10108 smb_lock->start > cmp_lock->start && 10109 smb_lock->start <= cmp_lock->end) { 10110 spin_unlock(&conn->llist_lock); 10111 up_read(&conn_list_lock); 10112 pr_err("current lock conflict with zero byte lock range\n"); 10113 goto out; 10114 } 10115 10116 if (cmp_lock->start <= smb_lock->end && 10117 smb_lock->start <= cmp_lock->end && 10118 !cmp_lock->zero_len && !smb_lock->zero_len) { 10119 spin_unlock(&conn->llist_lock); 10120 up_read(&conn_list_lock); 10121 pr_err("Not allow lock operation on exclusive lock range\n"); 10122 goto out; 10123 } 10124 } 10125 spin_unlock(&conn->llist_lock); 10126 } 10127 up_read(&conn_list_lock); 10128 out_check_cl: 10129 if (lock_is_unlock(smb_lock->fl) && nolock) { 10130 pr_err("Try to unlock nolocked range\n"); 10131 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED; 10132 goto out; 10133 } 10134 10135 no_check_cl: 10136 flock = smb_lock->fl; 10137 list_del(&smb_lock->llist); 10138 10139 if (smb_lock->zero_len) { 10140 err = 0; 10141 goto skip; 10142 } 10143 retry: 10144 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL); 10145 skip: 10146 if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) { 10147 locks_free_lock(flock); 10148 kfree(smb_lock); 10149 if (!rc) { 10150 ksmbd_debug(SMB, "File unlocked\n"); 10151 } else if (rc == -ENOENT) { 10152 rsp->hdr.Status = STATUS_NOT_LOCKED; 10153 err = rc; 10154 goto out; 10155 } 10156 } else { 10157 if (rc == FILE_LOCK_DEFERRED) { 10158 void **argv; 10159 10160 ksmbd_debug(SMB, 10161 "would have to wait for getting lock\n"); 10162 10163 argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP); 10164 if (!argv) { 10165 err = -ENOMEM; 10166 smb2_free_blocked_lock(flock); 10167 kfree(smb_lock); 10168 goto out; 10169 } 10170 argv[0] = flock; 10171 10172 rc = setup_async_work(work, 10173 smb2_remove_blocked_lock, 10174 argv); 10175 if (rc) { 10176 kfree(argv); 10177 err = -ENOMEM; 10178 smb2_free_blocked_lock(flock); 10179 kfree(smb_lock); 10180 goto out; 10181 } 10182 list_add(&smb_lock->llist, &rollback_list); 10183 spin_lock(&fp->f_lock); 10184 list_add(&work->fp_entry, &fp->blocked_works); 10185 spin_unlock(&fp->f_lock); 10186 10187 smb2_send_interim_resp(work, STATUS_PENDING); 10188 10189 ksmbd_vfs_posix_lock_wait(flock); 10190 10191 spin_lock(&fp->f_lock); 10192 list_del(&work->fp_entry); 10193 spin_unlock(&fp->f_lock); 10194 10195 list_del(&smb_lock->llist); 10196 10197 if (work->state == KSMBD_WORK_CANCELLED) { 10198 rsp->hdr.Status = STATUS_CANCELLED; 10199 kfree(smb_lock); 10200 smb2_send_interim_resp(work, 10201 STATUS_CANCELLED); 10202 release_async_work(work); 10203 locks_free_lock(flock); 10204 work->send_no_response = 1; 10205 goto out; 10206 } 10207 10208 release_async_work(work); 10209 10210 if (work->state == KSMBD_WORK_ACTIVE) 10211 goto retry; 10212 10213 locks_free_lock(flock); 10214 10215 rsp->hdr.Status = 10216 STATUS_RANGE_NOT_LOCKED; 10217 kfree(smb_lock); 10218 /* rollback_list may still hold earlier grants */ 10219 goto out; 10220 } else if (!rc) { 10221 list_add(&smb_lock->llist, &rollback_list); 10222 ksmbd_debug(SMB, "successful in taking lock\n"); 10223 } else { 10224 locks_free_lock(flock); 10225 kfree(smb_lock); 10226 err = rc; 10227 goto out; 10228 } 10229 } 10230 } 10231 10232 if (atomic_read(&fp->f_ci->op_count) > 1) 10233 smb_break_all_oplock(work, fp); 10234 10235 lock_success: 10236 rsp->StructureSize = cpu_to_le16(4); 10237 ksmbd_debug(SMB, "successful in taking lock\n"); 10238 rsp->hdr.Status = STATUS_SUCCESS; 10239 rsp->Reserved = 0; 10240 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp)); 10241 if (err) 10242 goto out; 10243 10244 /* publish only once the whole batch has committed */ 10245 if (!list_empty(&rollback_list)) { 10246 spin_lock(&work->conn->llist_lock); 10247 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) { 10248 list_del_init(&smb_lock->llist); 10249 smb_lock->conn = ksmbd_conn_get(work->conn); 10250 list_add_tail(&smb_lock->clist, 10251 &work->conn->lock_list); 10252 list_add_tail(&smb_lock->flist, 10253 &fp->lock_list); 10254 } 10255 spin_unlock(&work->conn->llist_lock); 10256 } 10257 10258 if (!lock_replayed) 10259 smb2_update_lock_sequence(work, fp, req); 10260 10261 ksmbd_fd_put(work, fp); 10262 return 0; 10263 10264 out: 10265 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) { 10266 locks_free_lock(smb_lock->fl); 10267 list_del(&smb_lock->llist); 10268 kfree(smb_lock); 10269 } 10270 10271 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) { 10272 struct file_lock *rlock = NULL; 10273 10274 rlock = smb_flock_init(filp); 10275 if (rlock) { 10276 rlock->c.flc_type = F_UNLCK; 10277 rlock->fl_start = smb_lock->start; 10278 rlock->fl_end = smb_lock->end; 10279 10280 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL); 10281 if (rc) 10282 pr_err("rollback unlock fail : %d\n", rc); 10283 } else { 10284 pr_err("rollback unlock alloc failed\n"); 10285 } 10286 10287 list_del(&smb_lock->llist); 10288 smb2_free_lock(smb_lock->fl); 10289 if (rlock) 10290 locks_free_lock(rlock); 10291 kfree(smb_lock); 10292 } 10293 out2: 10294 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err); 10295 10296 if (!rsp->hdr.Status) { 10297 if (err == -EINVAL) 10298 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10299 else if (err == -ENOMEM) 10300 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 10301 else if (err == -ENOENT) 10302 rsp->hdr.Status = STATUS_FILE_CLOSED; 10303 else 10304 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED; 10305 } 10306 10307 smb2_set_err_rsp(work); 10308 ksmbd_fd_put(work, fp); 10309 return err; 10310 } 10311 10312 static int fsctl_copychunk(struct ksmbd_work *work, 10313 struct copychunk_ioctl_req *ci_req, 10314 unsigned int cnt_code, 10315 unsigned int input_count, 10316 unsigned long long volatile_id, 10317 unsigned long long persistent_id, 10318 struct smb2_ioctl_rsp *rsp) 10319 { 10320 struct copychunk_ioctl_rsp *ci_rsp; 10321 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL; 10322 struct srv_copychunk *chunks; 10323 unsigned int i, chunk_count, chunk_count_written = 0; 10324 unsigned int chunk_size_written = 0; 10325 loff_t total_size_written = 0; 10326 int ret = 0; 10327 10328 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0]; 10329 10330 rsp->VolatileFileId = volatile_id; 10331 rsp->PersistentFileId = persistent_id; 10332 ci_rsp->ChunksWritten = 10333 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count()); 10334 ci_rsp->ChunkBytesWritten = 10335 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size()); 10336 ci_rsp->TotalBytesWritten = 10337 cpu_to_le32(ksmbd_server_side_copy_max_total_size()); 10338 10339 chunk_count = le32_to_cpu(ci_req->ChunkCount); 10340 /* 10341 * ChunkCount=0 is the standard SMB2 "query my copy limits" request 10342 * (no data copied) -- but macOS Finder's Cmd+D duplicate sends 10343 * FSCTL_SRV_COPYCHUNK with ChunkCount=0 meaning "copy the whole 10344 * file", relying on the AAPL-negotiated server to do a full copy 10345 * instead. Keep the standard no-op behavior for everyone else. 10346 * 10347 * Gate on the TIME_MACHINE share flag, not just conn->is_aapl: 10348 * that flag alone has ambiguous provenance -- the pre-existing 10349 * narrow UniqueId=0 path can also set it on ordinary, 10350 * non-Time-Machine shares, and this series' stated design keeps 10351 * every AAPL-driven behavior opt-in per share. 10352 */ 10353 if (chunk_count == 0 && 10354 !(work->conn->is_aapl && 10355 test_share_config_flag(work->tcon->share_conf, 10356 KSMBD_SHARE_FLAG_TIME_MACHINE))) 10357 goto out; 10358 total_size_written = 0; 10359 i = 0; 10360 10361 if (chunk_count) { 10362 /* verify the SRV_COPYCHUNK_COPY packet */ 10363 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() || 10364 input_count < struct_size(ci_req, Chunks, chunk_count)) { 10365 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10366 return -EINVAL; 10367 } 10368 10369 chunks = &ci_req->Chunks[0]; 10370 for (i = 0; i < chunk_count; i++) { 10371 if (le32_to_cpu(chunks[i].Length) == 0 || 10372 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size()) 10373 break; 10374 total_size_written += le32_to_cpu(chunks[i].Length); 10375 } 10376 } else { 10377 chunks = &ci_req->Chunks[0]; 10378 } 10379 10380 if (i < chunk_count || 10381 total_size_written > ksmbd_server_side_copy_max_total_size()) { 10382 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10383 return -EINVAL; 10384 } 10385 10386 src_fp = ksmbd_lookup_foreign_fd(work, 10387 le64_to_cpu(ci_req->SourceKeyU64[0])); 10388 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id); 10389 ret = -EINVAL; 10390 if (!src_fp || 10391 src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) { 10392 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND; 10393 goto out; 10394 } 10395 10396 if (!dst_fp) { 10397 rsp->hdr.Status = STATUS_FILE_CLOSED; 10398 goto out; 10399 } 10400 10401 /* 10402 * FILE_READ_DATA should only be included in 10403 * the FSCTL_SRV_COPYCHUNK case 10404 */ 10405 if (cnt_code == FSCTL_SRV_COPYCHUNK && 10406 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) { 10407 rsp->hdr.Status = STATUS_ACCESS_DENIED; 10408 goto out; 10409 } 10410 10411 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp, 10412 chunks, chunk_count, 10413 &chunk_count_written, 10414 &chunk_size_written, 10415 &total_size_written); 10416 if (ret < 0) { 10417 if (ret == -EACCES) 10418 rsp->hdr.Status = STATUS_ACCESS_DENIED; 10419 else if (ret == -EAGAIN) 10420 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 10421 else if (ret == -EBADF) 10422 rsp->hdr.Status = STATUS_INVALID_HANDLE; 10423 else if (ret == -EFBIG || ret == -ENOSPC) 10424 rsp->hdr.Status = STATUS_DISK_FULL; 10425 else if (ret == -EINVAL) 10426 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10427 else if (ret == -EISDIR) 10428 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY; 10429 else if (ret == -E2BIG) 10430 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE; 10431 else 10432 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; 10433 } 10434 10435 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written); 10436 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written); 10437 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written); 10438 out: 10439 ksmbd_fd_put(work, src_fp); 10440 ksmbd_fd_put(work, dst_fp); 10441 return ret; 10442 } 10443 10444 static __be32 idev_ipv4_address(struct in_device *idev) 10445 { 10446 __be32 addr = 0; 10447 10448 struct in_ifaddr *ifa; 10449 10450 rcu_read_lock(); 10451 in_dev_for_each_ifa_rcu(ifa, idev) { 10452 if (ifa->ifa_flags & IFA_F_SECONDARY) 10453 continue; 10454 10455 addr = ifa->ifa_address; 10456 break; 10457 } 10458 rcu_read_unlock(); 10459 return addr; 10460 } 10461 10462 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn, 10463 struct smb2_ioctl_rsp *rsp, 10464 unsigned int out_buf_len) 10465 { 10466 struct network_interface_info_ioctl_rsp *nii_rsp = NULL; 10467 int nbytes = 0; 10468 struct net_device *netdev; 10469 struct sockaddr_storage_rsp *sockaddr_storage; 10470 unsigned int flags; 10471 unsigned long long speed; 10472 10473 rtnl_lock(); 10474 for_each_netdev(&init_net, netdev) { 10475 bool ipv4_set = false; 10476 10477 if (netdev->type == ARPHRD_LOOPBACK) 10478 continue; 10479 10480 if (!ksmbd_find_netdev_name_iface_list(netdev->name)) 10481 continue; 10482 10483 flags = netif_get_flags(netdev); 10484 if (!(flags & IFF_RUNNING)) 10485 continue; 10486 ipv6_retry: 10487 if (out_buf_len < 10488 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) { 10489 rtnl_unlock(); 10490 return -ENOSPC; 10491 } 10492 10493 nii_rsp = (struct network_interface_info_ioctl_rsp *) 10494 &rsp->Buffer[nbytes]; 10495 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex); 10496 10497 nii_rsp->Capability = 0; 10498 if (netdev->real_num_tx_queues > 1) 10499 nii_rsp->Capability |= RSS_CAPABLE; 10500 if (ksmbd_rdma_capable_netdev(netdev)) 10501 nii_rsp->Capability |= RDMA_CAPABLE; 10502 10503 nii_rsp->Next = cpu_to_le32(152); 10504 nii_rsp->Reserved = 0; 10505 10506 if (netdev->ethtool_ops->get_link_ksettings) { 10507 struct ethtool_link_ksettings cmd; 10508 10509 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd); 10510 speed = cmd.base.speed; 10511 } else { 10512 ksmbd_debug(SMB, "%s %s\n", netdev->name, 10513 "speed is unknown, defaulting to 1Gb/sec"); 10514 speed = SPEED_1000; 10515 } 10516 10517 speed *= 1000000; 10518 nii_rsp->LinkSpeed = cpu_to_le64(speed); 10519 10520 sockaddr_storage = (struct sockaddr_storage_rsp *) 10521 nii_rsp->SockAddr_Storage; 10522 memset(sockaddr_storage, 0, 128); 10523 10524 if (!ipv4_set) { 10525 struct in_device *idev; 10526 10527 sockaddr_storage->Family = INTERNETWORK; 10528 sockaddr_storage->addr4.Port = 0; 10529 10530 idev = __in_dev_get_rtnl(netdev); 10531 if (!idev) 10532 continue; 10533 sockaddr_storage->addr4.IPv4Address = 10534 idev_ipv4_address(idev); 10535 nbytes += sizeof(struct network_interface_info_ioctl_rsp); 10536 ipv4_set = true; 10537 goto ipv6_retry; 10538 } else { 10539 struct inet6_dev *idev6; 10540 struct inet6_ifaddr *ifa; 10541 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address; 10542 10543 sockaddr_storage->Family = INTERNETWORKV6; 10544 sockaddr_storage->addr6.Port = 0; 10545 sockaddr_storage->addr6.FlowInfo = 0; 10546 10547 idev6 = __in6_dev_get(netdev); 10548 if (!idev6) 10549 continue; 10550 10551 list_for_each_entry(ifa, &idev6->addr_list, if_list) { 10552 if (ifa->flags & (IFA_F_TENTATIVE | 10553 IFA_F_DEPRECATED)) 10554 continue; 10555 memcpy(ipv6_addr, ifa->addr.s6_addr, 16); 10556 break; 10557 } 10558 sockaddr_storage->addr6.ScopeId = 0; 10559 nbytes += sizeof(struct network_interface_info_ioctl_rsp); 10560 } 10561 } 10562 rtnl_unlock(); 10563 10564 /* zero if this is last one */ 10565 if (nii_rsp) 10566 nii_rsp->Next = 0; 10567 10568 rsp->PersistentFileId = SMB2_NO_FID; 10569 rsp->VolatileFileId = SMB2_NO_FID; 10570 return nbytes; 10571 } 10572 10573 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn, 10574 struct validate_negotiate_info_req *neg_req, 10575 struct validate_negotiate_info_rsp *neg_rsp, 10576 unsigned int in_buf_len) 10577 { 10578 int ret = 0; 10579 int dialect; 10580 10581 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) + 10582 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16)) 10583 return -EINVAL; 10584 10585 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects, 10586 neg_req->DialectCount); 10587 if (dialect == BAD_PROT_ID || dialect != conn->dialect) { 10588 ret = -EINVAL; 10589 goto err_out; 10590 } 10591 10592 if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) { 10593 ret = -EINVAL; 10594 goto err_out; 10595 } 10596 10597 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) { 10598 ret = -EINVAL; 10599 goto err_out; 10600 } 10601 10602 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) { 10603 ret = -EINVAL; 10604 goto err_out; 10605 } 10606 10607 neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities); 10608 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE); 10609 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode); 10610 neg_rsp->Dialect = cpu_to_le16(conn->dialect); 10611 err_out: 10612 return ret; 10613 } 10614 10615 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id, 10616 struct file_allocated_range_buffer *qar_req, 10617 struct file_allocated_range_buffer *qar_rsp, 10618 unsigned int in_count, unsigned int *out_count) 10619 { 10620 struct ksmbd_file *fp; 10621 loff_t start, length; 10622 int ret = 0; 10623 10624 *out_count = 0; 10625 10626 start = le64_to_cpu(qar_req->file_offset); 10627 length = le64_to_cpu(qar_req->length); 10628 10629 if (start < 0 || length < 0) 10630 return -EINVAL; 10631 10632 fp = ksmbd_lookup_fd_fast(work, id); 10633 if (!fp) 10634 return -ENOENT; 10635 10636 if (!(fp->daccess & FILE_READ_DATA_LE)) { 10637 ret = -EACCES; 10638 goto out; 10639 } 10640 10641 if (!in_count) { 10642 struct file_allocated_range_buffer range; 10643 10644 ret = ksmbd_vfs_query_allocated_ranges(fp, start, length, 10645 &range, 1, out_count); 10646 if ((!ret || ret == -E2BIG) && *out_count) 10647 ret = -ENOSPC; 10648 *out_count = 0; 10649 } else { 10650 ret = ksmbd_vfs_query_allocated_ranges(fp, start, length, 10651 qar_rsp, in_count, 10652 out_count); 10653 } 10654 if (ret && ret != -E2BIG) 10655 *out_count = 0; 10656 10657 out: 10658 ksmbd_fd_put(work, fp); 10659 return ret; 10660 } 10661 10662 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id, 10663 unsigned int out_buf_len, 10664 struct smb2_ioctl_req *req, 10665 struct smb2_ioctl_rsp *rsp) 10666 { 10667 struct ksmbd_rpc_command *rpc_resp; 10668 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset); 10669 int nbytes = 0; 10670 10671 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf, 10672 le32_to_cpu(req->InputCount)); 10673 if (rpc_resp) { 10674 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) { 10675 /* 10676 * set STATUS_SOME_NOT_MAPPED response 10677 * for unknown domain sid. 10678 */ 10679 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED; 10680 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { 10681 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 10682 goto out; 10683 } else if (rpc_resp->flags != KSMBD_RPC_OK) { 10684 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10685 goto out; 10686 } 10687 10688 nbytes = rpc_resp->payload_sz; 10689 if (rpc_resp->payload_sz > out_buf_len) { 10690 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; 10691 nbytes = out_buf_len; 10692 } 10693 10694 if (!rpc_resp->payload_sz) { 10695 rsp->hdr.Status = 10696 STATUS_UNEXPECTED_IO_ERROR; 10697 goto out; 10698 } 10699 10700 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes); 10701 } 10702 out: 10703 kvfree(rpc_resp); 10704 return nbytes; 10705 } 10706 10707 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id, 10708 struct file_sparse *sparse) 10709 { 10710 struct ksmbd_file *fp; 10711 struct mnt_idmap *idmap; 10712 int ret = 0; 10713 __le32 old_fattr; 10714 10715 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 10716 ksmbd_debug(SMB, "User does not have write permission\n"); 10717 return -EACCES; 10718 } 10719 10720 fp = ksmbd_lookup_fd_fast(work, id); 10721 if (!fp) 10722 return -ENOENT; 10723 10724 if (S_ISDIR(file_inode(fp->filp)->i_mode)) { 10725 ret = -EINVAL; 10726 goto out; 10727 } 10728 10729 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE | 10730 FILE_WRITE_ATTRIBUTES_LE))) { 10731 ret = -EACCES; 10732 goto out; 10733 } 10734 10735 idmap = file_mnt_idmap(fp->filp); 10736 10737 old_fattr = fp->f_ci->m_fattr; 10738 if (!sparse->SetSparse && 10739 (old_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) { 10740 ret = ksmbd_vfs_zero_holes(fp); 10741 if (ret) 10742 goto out; 10743 } 10744 10745 if (sparse->SetSparse) 10746 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE; 10747 else 10748 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE; 10749 10750 if (fp->f_ci->m_fattr != old_fattr) { 10751 const struct cred *saved_cred; 10752 struct xattr_dos_attrib da = {0}; 10753 10754 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap, 10755 fp->filp->f_path.dentry, &da); 10756 if (ret <= 0) { 10757 da.version = 4; 10758 da.itime = fp->itime; 10759 da.create_time = fp->create_time; 10760 da.flags = XATTR_DOSINFO_CREATE_TIME | 10761 XATTR_DOSINFO_ITIME; 10762 } 10763 10764 da.attr = le32_to_cpu(fp->f_ci->m_fattr); 10765 da.flags |= XATTR_DOSINFO_ATTRIB; 10766 saved_cred = override_creds(fp->filp->f_cred); 10767 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap, 10768 &fp->filp->f_path, 10769 &da, true); 10770 revert_creds(saved_cred); 10771 if (ret) 10772 fp->f_ci->m_fattr = old_fattr; 10773 } 10774 10775 out: 10776 ksmbd_fd_put(work, fp); 10777 return ret; 10778 } 10779 10780 static int fsctl_request_resume_key(struct ksmbd_work *work, 10781 struct smb2_ioctl_req *req, 10782 struct resume_key_ioctl_rsp *key_rsp) 10783 { 10784 struct ksmbd_file *fp; 10785 10786 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId); 10787 if (!fp) 10788 return -ENOENT; 10789 10790 memset(key_rsp, 0, sizeof(*key_rsp)); 10791 key_rsp->ResumeKeyU64[0] = req->VolatileFileId; 10792 key_rsp->ResumeKeyU64[1] = req->PersistentFileId; 10793 ksmbd_fd_put(work, fp); 10794 10795 return 0; 10796 } 10797 10798 /** 10799 * smb2_ioctl() - handler for smb2 ioctl command 10800 * @work: smb work containing ioctl command buffer 10801 * 10802 * Return: 0 on success, otherwise error 10803 */ 10804 int smb2_ioctl(struct ksmbd_work *work) 10805 { 10806 struct smb2_ioctl_req *req; 10807 struct smb2_ioctl_rsp *rsp; 10808 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len; 10809 u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID; 10810 struct ksmbd_conn *conn = work->conn; 10811 int ret = 0; 10812 char *buffer; 10813 bool no_fileid_ioctl = false; 10814 bool chseq_err = false; 10815 10816 ksmbd_debug(SMB, "Received smb2 ioctl request\n"); 10817 10818 if (work->next_smb2_rcv_hdr_off) { 10819 req = ksmbd_req_buf_next(work); 10820 rsp = ksmbd_resp_buf_next(work); 10821 if (smb2_compound_has_failed(work, &rsp->hdr)) 10822 return -EACCES; 10823 if (!has_file_id(req->VolatileFileId)) { 10824 ksmbd_debug(SMB, "Compound request set FID = %llu\n", 10825 work->compound_fid); 10826 id = work->compound_fid; 10827 pid = work->compound_pfid; 10828 } 10829 } else { 10830 req = smb_get_msg(work->request_buf); 10831 rsp = smb_get_msg(work->response_buf); 10832 } 10833 10834 if (!has_file_id(id)) { 10835 id = req->VolatileFileId; 10836 pid = req->PersistentFileId; 10837 } 10838 10839 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) { 10840 ret = -EOPNOTSUPP; 10841 goto out; 10842 } 10843 10844 buffer = (char *)req + le32_to_cpu(req->InputOffset); 10845 10846 cnt_code = le32_to_cpu(req->CtlCode); 10847 switch (cnt_code) { 10848 case FSCTL_DFS_GET_REFERRALS: 10849 case FSCTL_DFS_GET_REFERRALS_EX: 10850 case FSCTL_QUERY_NETWORK_INTERFACE_INFO: 10851 case FSCTL_VALIDATE_NEGOTIATE_INFO: 10852 case FSCTL_PIPE_WAIT: 10853 case FSCTL_PIPE_TRANSCEIVE: 10854 no_fileid_ioctl = true; 10855 break; 10856 default: 10857 break; 10858 } 10859 10860 if (!no_fileid_ioctl && has_file_id(id)) { 10861 struct ksmbd_file *fp; 10862 10863 fp = ksmbd_lookup_fd_slow(work, id, pid); 10864 if (!fp) { 10865 if (cnt_code == FSCTL_DUPLICATE_EXTENTS_TO_FILE) { 10866 rsp->hdr.Status = STATUS_FILE_CLOSED; 10867 goto out2; 10868 } 10869 ret = -ENOENT; 10870 goto out; 10871 } 10872 10873 ret = smb2_set_request_open(work, fp, &req->hdr, true, false); 10874 ksmbd_fd_put(work, fp); 10875 if (ret) { 10876 rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE; 10877 chseq_err = true; 10878 goto out; 10879 } 10880 } 10881 10882 ret = smb2_calc_max_out_buf_len(work, 10883 offsetof(struct smb2_ioctl_rsp, Buffer), 10884 le32_to_cpu(req->MaxOutputResponse)); 10885 if (ret < 0) { 10886 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 10887 goto out; 10888 } 10889 out_buf_len = (unsigned int)ret; 10890 in_buf_len = le32_to_cpu(req->InputCount); 10891 10892 switch (cnt_code) { 10893 case FSCTL_SRV_ENUM_SNAPS: { 10894 struct srv_snapshot_array *snap_rsp; 10895 struct ksmbd_file *fp; 10896 10897 if (out_buf_len < sizeof(*snap_rsp)) { 10898 ret = -EINVAL; 10899 goto out; 10900 } 10901 10902 fp = ksmbd_lookup_fd_fast(work, id); 10903 if (!fp) { 10904 ret = -ENOENT; 10905 goto out; 10906 } 10907 ksmbd_fd_put(work, fp); 10908 10909 snap_rsp = (struct srv_snapshot_array *)rsp->Buffer; 10910 snap_rsp->NumberOfSnapShots = 0; 10911 snap_rsp->NumberOfSnapShotsReturned = 0; 10912 snap_rsp->SnapShotArraySize = cpu_to_le32(2); 10913 snap_rsp->Reserved = 0; 10914 nbytes = sizeof(*snap_rsp); 10915 break; 10916 } 10917 case FSCTL_DFS_GET_REFERRALS: 10918 case FSCTL_DFS_GET_REFERRALS_EX: 10919 /* Not support DFS yet */ 10920 ret = -EOPNOTSUPP; 10921 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED; 10922 goto out2; 10923 case FSCTL_GET_COMPRESSION: { 10924 struct compress_ioctl *cmpr_rsp; 10925 struct ksmbd_file *fp; 10926 u16 fmt; 10927 10928 if (out_buf_len < sizeof(struct compress_ioctl)) { 10929 ret = -EINVAL; 10930 goto out; 10931 } 10932 10933 fp = ksmbd_lookup_fd_fast(work, id); 10934 if (!fp) { 10935 ret = -ENOENT; 10936 goto out; 10937 } 10938 10939 ret = ksmbd_vfs_get_compression(fp, &fmt); 10940 ksmbd_fd_put(work, fp); 10941 if (ret < 0) 10942 goto out; 10943 10944 cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0]; 10945 cmpr_rsp->CompressionState = cpu_to_le16(fmt); 10946 nbytes = sizeof(struct compress_ioctl); 10947 rsp->PersistentFileId = req->PersistentFileId; 10948 rsp->VolatileFileId = req->VolatileFileId; 10949 break; 10950 } 10951 case FSCTL_SET_COMPRESSION: { 10952 struct compress_ioctl *cmpr_req; 10953 struct ksmbd_file *fp; 10954 10955 if (in_buf_len < sizeof(struct compress_ioctl)) { 10956 ret = -EINVAL; 10957 goto out; 10958 } 10959 10960 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 10961 ksmbd_debug(SMB, "User does not have write permission\n"); 10962 ret = -EACCES; 10963 goto out; 10964 } 10965 10966 cmpr_req = (struct compress_ioctl *)buffer; 10967 fp = ksmbd_lookup_fd_fast(work, id); 10968 if (!fp) { 10969 ret = -ENOENT; 10970 goto out; 10971 } 10972 10973 ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState)); 10974 ksmbd_fd_put(work, fp); 10975 if (ret) 10976 goto out; 10977 break; 10978 } 10979 case FSCTL_CREATE_OR_GET_OBJECT_ID: 10980 { 10981 struct file_object_buf_type1_ioctl_rsp *obj_buf; 10982 struct ksmbd_file *fp; 10983 10984 fp = ksmbd_lookup_fd_fast(work, id); 10985 if (!fp) { 10986 ret = -EBADF; 10987 rsp->hdr.Status = STATUS_FILE_CLOSED; 10988 goto out2; 10989 } 10990 10991 if (out_buf_len < sizeof(struct file_object_buf_type1_ioctl_rsp)) { 10992 ksmbd_fd_put(work, fp); 10993 ret = -EINVAL; 10994 goto out; 10995 } 10996 ksmbd_fd_put(work, fp); 10997 10998 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp); 10999 obj_buf = (struct file_object_buf_type1_ioctl_rsp *) 11000 &rsp->Buffer[0]; 11001 11002 /* 11003 * TODO: This is dummy implementation to pass smbtorture 11004 * Need to check correct response later 11005 */ 11006 memset(obj_buf->ObjectId, 0x0, 16); 11007 memset(obj_buf->BirthVolumeId, 0x0, 16); 11008 memset(obj_buf->BirthObjectId, 0x0, 16); 11009 memset(obj_buf->DomainId, 0x0, 16); 11010 11011 break; 11012 } 11013 case FSCTL_PIPE_TRANSCEIVE: 11014 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len); 11015 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp); 11016 break; 11017 case FSCTL_VALIDATE_NEGOTIATE_INFO: 11018 if (conn->dialect < SMB30_PROT_ID) { 11019 ret = -EOPNOTSUPP; 11020 goto out; 11021 } 11022 11023 if (in_buf_len < offsetof(struct validate_negotiate_info_req, 11024 Dialects)) { 11025 ret = -EINVAL; 11026 goto out; 11027 } 11028 11029 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) { 11030 ret = -EINVAL; 11031 goto out; 11032 } 11033 11034 ret = fsctl_validate_negotiate_info(conn, 11035 (struct validate_negotiate_info_req *)buffer, 11036 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0], 11037 in_buf_len); 11038 if (ret < 0) 11039 goto out; 11040 11041 nbytes = sizeof(struct validate_negotiate_info_rsp); 11042 rsp->PersistentFileId = SMB2_NO_FID; 11043 rsp->VolatileFileId = SMB2_NO_FID; 11044 break; 11045 case FSCTL_QUERY_NETWORK_INTERFACE_INFO: 11046 if (req->PersistentFileId != SMB2_NO_FID || 11047 req->VolatileFileId != SMB2_NO_FID) { 11048 ret = -EINVAL; 11049 goto out; 11050 } 11051 11052 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len); 11053 if (ret < 0) 11054 goto out; 11055 nbytes = ret; 11056 break; 11057 case FSCTL_SRV_REQUEST_RESUME_KEY: 11058 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) { 11059 ret = -EINVAL; 11060 goto out; 11061 } 11062 11063 ret = fsctl_request_resume_key(work, req, 11064 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]); 11065 if (ret < 0) 11066 goto out; 11067 rsp->PersistentFileId = req->PersistentFileId; 11068 rsp->VolatileFileId = req->VolatileFileId; 11069 nbytes = sizeof(struct resume_key_ioctl_rsp); 11070 break; 11071 case FSCTL_SRV_COPYCHUNK: 11072 case FSCTL_SRV_COPYCHUNK_WRITE: 11073 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 11074 ksmbd_debug(SMB, 11075 "User does not have write permission\n"); 11076 ret = -EACCES; 11077 goto out; 11078 } 11079 11080 if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) { 11081 ret = -EINVAL; 11082 goto out; 11083 } 11084 11085 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) { 11086 ret = -EINVAL; 11087 goto out; 11088 } 11089 11090 nbytes = sizeof(struct copychunk_ioctl_rsp); 11091 rsp->VolatileFileId = req->VolatileFileId; 11092 rsp->PersistentFileId = req->PersistentFileId; 11093 fsctl_copychunk(work, 11094 (struct copychunk_ioctl_req *)buffer, 11095 le32_to_cpu(req->CtlCode), 11096 le32_to_cpu(req->InputCount), 11097 req->VolatileFileId, 11098 req->PersistentFileId, 11099 rsp); 11100 break; 11101 case FSCTL_SET_SPARSE: 11102 { 11103 struct file_sparse sparse = {0}; 11104 11105 if (in_buf_len && in_buf_len < sizeof(struct file_sparse)) { 11106 ret = -EINVAL; 11107 goto out; 11108 } 11109 11110 *(u8 *)&sparse = 1; 11111 ret = fsctl_set_sparse(work, id, in_buf_len ? 11112 (struct file_sparse *)buffer : &sparse); 11113 if (ret < 0) 11114 goto out; 11115 break; 11116 } 11117 case FSCTL_SET_ZERO_DATA: 11118 { 11119 struct file_zero_data_information *zero_data; 11120 struct ksmbd_file *fp; 11121 loff_t off, len, bfz; 11122 11123 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 11124 ksmbd_debug(SMB, 11125 "User does not have write permission\n"); 11126 ret = -EACCES; 11127 goto out; 11128 } 11129 11130 if (in_buf_len < sizeof(struct file_zero_data_information)) { 11131 ret = -EINVAL; 11132 goto out; 11133 } 11134 11135 zero_data = 11136 (struct file_zero_data_information *)buffer; 11137 11138 off = le64_to_cpu(zero_data->FileOffset); 11139 bfz = le64_to_cpu(zero_data->BeyondFinalZero); 11140 if (off < 0 || bfz < 0 || off > bfz) { 11141 ret = -EINVAL; 11142 goto out; 11143 } 11144 11145 len = bfz - off; 11146 if (len) { 11147 fp = ksmbd_lookup_fd_fast(work, id); 11148 if (!fp) { 11149 ret = -ENOENT; 11150 goto out; 11151 } 11152 11153 if (!(fp->daccess & FILE_WRITE_DATA_LE)) { 11154 ksmbd_fd_put(work, fp); 11155 ret = -EACCES; 11156 goto out; 11157 } 11158 11159 ret = ksmbd_vfs_zero_data(work, fp, off, len); 11160 ksmbd_fd_put(work, fp); 11161 if (ret == -EAGAIN) { 11162 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 11163 ret = 0; 11164 goto out; 11165 } else if (ret < 0) { 11166 goto out; 11167 } 11168 } 11169 break; 11170 } 11171 case FSCTL_FILE_LEVEL_TRIM: 11172 { 11173 struct file_level_trim *trim_req; 11174 struct file_level_trim_output *trim_rsp; 11175 struct ksmbd_file *fp; 11176 u32 i, num_ranges; 11177 11178 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) { 11179 ksmbd_debug(SMB, 11180 "User does not have write permission\n"); 11181 ret = -EACCES; 11182 goto out; 11183 } 11184 11185 if (in_buf_len < offsetof(struct file_level_trim, Ranges)) { 11186 ret = -EINVAL; 11187 goto out; 11188 } 11189 11190 if (out_buf_len < sizeof(struct file_level_trim_output)) { 11191 ret = -EINVAL; 11192 goto out; 11193 } 11194 11195 trim_req = (struct file_level_trim *)buffer; 11196 num_ranges = le32_to_cpu(trim_req->NumRanges); 11197 if (num_ranges > 11198 (in_buf_len - offsetof(struct file_level_trim, Ranges)) / 11199 sizeof(struct file_level_trim_range)) { 11200 ret = -EINVAL; 11201 goto out; 11202 } 11203 11204 fp = ksmbd_lookup_fd_fast(work, id); 11205 if (!fp) { 11206 ret = -ENOENT; 11207 goto out; 11208 } 11209 11210 if (!(fp->daccess & FILE_WRITE_DATA_LE)) { 11211 ksmbd_fd_put(work, fp); 11212 ret = -EACCES; 11213 goto out; 11214 } 11215 11216 trim_rsp = (struct file_level_trim_output *)&rsp->Buffer[0]; 11217 trim_rsp->NumRangesProcessed = 0; 11218 for (i = 0; i < num_ranges; i++) { 11219 loff_t off = le64_to_cpu(trim_req->Ranges[i].Offset); 11220 loff_t len = le64_to_cpu(trim_req->Ranges[i].Length); 11221 11222 if (off < 0 || len < 0) { 11223 ret = -EINVAL; 11224 break; 11225 } 11226 11227 if (!len) { 11228 trim_rsp->NumRangesProcessed = 11229 cpu_to_le32(i + 1); 11230 continue; 11231 } 11232 11233 ret = ksmbd_vfs_trim_data(work, fp, off, len); 11234 if (ret) 11235 break; 11236 trim_rsp->NumRangesProcessed = cpu_to_le32(i + 1); 11237 } 11238 ksmbd_fd_put(work, fp); 11239 if (ret == -EAGAIN) { 11240 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT; 11241 ret = 0; 11242 goto out; 11243 } else if (ret < 0) { 11244 goto out; 11245 } 11246 11247 nbytes = sizeof(struct file_level_trim_output); 11248 break; 11249 } 11250 case FSCTL_QUERY_ALLOCATED_RANGES: 11251 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) { 11252 ret = -EINVAL; 11253 goto out; 11254 } 11255 11256 ret = fsctl_query_allocated_ranges(work, id, 11257 (struct file_allocated_range_buffer *)buffer, 11258 (struct file_allocated_range_buffer *)&rsp->Buffer[0], 11259 out_buf_len / 11260 sizeof(struct file_allocated_range_buffer), &nbytes); 11261 if (ret == -E2BIG) { 11262 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; 11263 } else if (ret < 0) { 11264 nbytes = 0; 11265 goto out; 11266 } 11267 11268 nbytes *= sizeof(struct file_allocated_range_buffer); 11269 break; 11270 case FSCTL_GET_REPARSE_POINT: 11271 { 11272 struct reparse_data_buffer *reparse_ptr; 11273 struct ksmbd_file *fp; 11274 11275 if (out_buf_len < sizeof(struct reparse_data_buffer)) { 11276 ret = -EINVAL; 11277 goto out; 11278 } 11279 11280 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0]; 11281 fp = ksmbd_lookup_fd_fast(work, id); 11282 if (!fp) { 11283 pr_err("not found fp!!\n"); 11284 ret = -ENOENT; 11285 goto out; 11286 } 11287 11288 reparse_ptr->ReparseTag = 11289 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode); 11290 reparse_ptr->ReparseDataLength = 0; 11291 ksmbd_fd_put(work, fp); 11292 nbytes = sizeof(struct reparse_data_buffer); 11293 break; 11294 } 11295 case FSCTL_DUPLICATE_EXTENTS_TO_FILE: 11296 { 11297 struct ksmbd_file *fp_in, *fp_out = NULL; 11298 struct duplicate_extents_to_file *dup_ext; 11299 loff_t src_off, dst_off, length, cloned; 11300 11301 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) { 11302 ret = -EINVAL; 11303 goto out; 11304 } 11305 11306 dup_ext = (struct duplicate_extents_to_file *)buffer; 11307 11308 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle, 11309 dup_ext->PersistentFileHandle); 11310 if (!fp_in) { 11311 pr_err("not found file handle in duplicate extent to file\n"); 11312 ret = -EBADF; 11313 rsp->hdr.Status = STATUS_INVALID_HANDLE; 11314 goto out2; 11315 } 11316 11317 fp_out = ksmbd_lookup_fd_fast(work, id); 11318 if (!fp_out) { 11319 pr_err("not found fp\n"); 11320 ret = -EBADF; 11321 rsp->hdr.Status = STATUS_FILE_CLOSED; 11322 ksmbd_fd_put(work, fp_in); 11323 goto out2; 11324 } 11325 11326 if (!test_tree_conn_flag(work->tcon, 11327 KSMBD_TREE_CONN_FLAG_WRITABLE)) { 11328 ret = -EACCES; 11329 goto dup_ext_out; 11330 } 11331 11332 if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) { 11333 ret = -EACCES; 11334 goto dup_ext_out; 11335 } 11336 if (!(fp_in->daccess & FILE_READ_DATA_LE)) { 11337 ret = -EACCES; 11338 goto dup_ext_out; 11339 } 11340 11341 src_off = le64_to_cpu(dup_ext->SourceFileOffset); 11342 dst_off = le64_to_cpu(dup_ext->TargetFileOffset); 11343 length = le64_to_cpu(dup_ext->ByteCount); 11344 if (src_off < 0 || dst_off < 0 || length < 0 || 11345 src_off + length < src_off || dst_off + length < dst_off) { 11346 ret = -EINVAL; 11347 goto dup_ext_out; 11348 } 11349 if (src_off + length > i_size_read(file_inode(fp_in->filp))) { 11350 ret = -EOPNOTSUPP; 11351 goto dup_ext_out; 11352 } 11353 if (dst_off + length > i_size_read(file_inode(fp_out->filp))) 11354 goto dup_ext_out; 11355 if ((fp_in->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE) && 11356 !(fp_out->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) { 11357 ret = -EOPNOTSUPP; 11358 goto dup_ext_out; 11359 } 11360 if (file_inode(fp_in->filp) == file_inode(fp_out->filp) && 11361 dst_off + length > src_off && 11362 dst_off < src_off + length) { 11363 ret = -EOPNOTSUPP; 11364 goto dup_ext_out; 11365 } 11366 11367 cloned = vfs_clone_file_range(fp_in->filp, src_off, 11368 fp_out->filp, dst_off, length, 0); 11369 if (cloned != length) { 11370 cloned = vfs_copy_file_range(fp_in->filp, src_off, 11371 fp_out->filp, dst_off, 11372 length, 0); 11373 if (cloned != length) { 11374 if (cloned < 0) 11375 ret = cloned; 11376 else 11377 ret = -EINVAL; 11378 } 11379 } 11380 11381 dup_ext_out: 11382 ksmbd_fd_put(work, fp_in); 11383 ksmbd_fd_put(work, fp_out); 11384 if (ret < 0) 11385 goto out; 11386 break; 11387 } 11388 default: 11389 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n", 11390 cnt_code); 11391 ret = -EOPNOTSUPP; 11392 goto out; 11393 } 11394 11395 rsp->CtlCode = cpu_to_le32(cnt_code); 11396 rsp->InputCount = cpu_to_le32(0); 11397 rsp->InputOffset = cpu_to_le32(112); 11398 rsp->OutputOffset = cpu_to_le32(112); 11399 rsp->OutputCount = cpu_to_le32(nbytes); 11400 rsp->StructureSize = cpu_to_le16(49); 11401 rsp->Reserved = cpu_to_le16(0); 11402 rsp->Flags = cpu_to_le32(0); 11403 rsp->Reserved2 = cpu_to_le32(0); 11404 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes); 11405 if (!ret) 11406 return ret; 11407 11408 out: 11409 if (ret == -EACCES) 11410 rsp->hdr.Status = STATUS_ACCESS_DENIED; 11411 else if (ret == -ENOENT) 11412 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND; 11413 else if (ret == -EOPNOTSUPP) 11414 rsp->hdr.Status = STATUS_NOT_SUPPORTED; 11415 else if (ret == -ENOSPC) 11416 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL; 11417 else if (!chseq_err && (ret < 0 || rsp->hdr.Status == 0)) 11418 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 11419 11420 out2: 11421 smb2_set_err_rsp(work); 11422 return ret; 11423 } 11424 11425 /** 11426 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command 11427 * @work: smb work containing oplock break command buffer 11428 * 11429 * Return: 0 11430 */ 11431 static void smb20_oplock_break_ack(struct ksmbd_work *work) 11432 { 11433 struct smb2_oplock_break *req; 11434 struct smb2_oplock_break *rsp; 11435 struct ksmbd_file *fp; 11436 struct oplock_info *opinfo = NULL; 11437 __le32 status = STATUS_SUCCESS; 11438 int ret; 11439 u64 volatile_id, persistent_id; 11440 char req_oplevel = 0, rsp_oplevel = 0; 11441 11442 WORK_BUFFERS(work, req, rsp); 11443 11444 volatile_id = req->VolatileFid; 11445 persistent_id = req->PersistentFid; 11446 req_oplevel = req->OplockLevel; 11447 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n", 11448 volatile_id, persistent_id, req_oplevel); 11449 11450 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id); 11451 if (!fp) { 11452 rsp->hdr.Status = STATUS_FILE_CLOSED; 11453 smb2_set_err_rsp(work); 11454 return; 11455 } 11456 11457 ret = smb2_set_request_open(work, fp, &req->hdr, false, false); 11458 if (ret) { 11459 rsp->hdr.Status = STATUS_FILE_CLOSED; 11460 smb2_set_err_rsp(work); 11461 ksmbd_fd_put(work, fp); 11462 return; 11463 } 11464 11465 opinfo = opinfo_get(fp); 11466 if (!opinfo) { 11467 pr_err("unexpected null oplock_info\n"); 11468 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL; 11469 smb2_set_err_rsp(work); 11470 ksmbd_fd_put(work, fp); 11471 return; 11472 } 11473 11474 if (opinfo->op_state != OPLOCK_ACK_WAIT) { 11475 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", 11476 opinfo->op_state); 11477 if (smb3_hdr_replay(&req->hdr) && 11478 opinfo->op_state == OPLOCK_STATE_NONE) { 11479 rsp->StructureSize = cpu_to_le16(24); 11480 rsp->OplockLevel = opinfo->level; 11481 rsp->Reserved = 0; 11482 rsp->Reserved2 = 0; 11483 rsp->VolatileFid = volatile_id; 11484 rsp->PersistentFid = persistent_id; 11485 ret = ksmbd_iov_pin_rsp(work, rsp, 11486 sizeof(struct smb2_oplock_break)); 11487 if (ret) 11488 ksmbd_debug(SMB, 11489 "failed to pin replayed oplock break response: %d\n", 11490 ret); 11491 goto out_no_state_change; 11492 } 11493 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) 11494 status = STATUS_INVALID_OPLOCK_PROTOCOL; 11495 else 11496 status = STATUS_INVALID_DEVICE_STATE; 11497 goto err_out; 11498 } 11499 11500 if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) { 11501 opinfo->level = SMB2_OPLOCK_LEVEL_NONE; 11502 status = STATUS_INVALID_PARAMETER; 11503 goto err_out; 11504 } 11505 11506 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) { 11507 status = STATUS_INVALID_OPLOCK_PROTOCOL; 11508 goto err_out; 11509 } 11510 11511 if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE && 11512 req_oplevel != SMB2_OPLOCK_LEVEL_II && 11513 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) { 11514 opinfo->level = SMB2_OPLOCK_LEVEL_NONE; 11515 status = STATUS_INVALID_OPLOCK_PROTOCOL; 11516 goto err_out; 11517 } 11518 11519 if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH && 11520 req_oplevel != SMB2_OPLOCK_LEVEL_II && 11521 req_oplevel != SMB2_OPLOCK_LEVEL_NONE && 11522 req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) { 11523 opinfo->level = SMB2_OPLOCK_LEVEL_NONE; 11524 status = STATUS_INVALID_OPLOCK_PROTOCOL; 11525 goto err_out; 11526 } 11527 11528 if (opinfo->level == SMB2_OPLOCK_LEVEL_II && 11529 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) { 11530 opinfo->level = SMB2_OPLOCK_LEVEL_NONE; 11531 status = STATUS_INVALID_OPLOCK_PROTOCOL; 11532 goto err_out; 11533 } 11534 11535 if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE) 11536 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE; 11537 else 11538 rsp_oplevel = req_oplevel; 11539 11540 opinfo->level = rsp_oplevel; 11541 11542 rsp->StructureSize = cpu_to_le16(24); 11543 rsp->OplockLevel = rsp_oplevel; 11544 rsp->Reserved = 0; 11545 rsp->Reserved2 = 0; 11546 rsp->VolatileFid = volatile_id; 11547 rsp->PersistentFid = persistent_id; 11548 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break)); 11549 if (ret) 11550 ksmbd_debug(SMB, "failed to pin oplock break response: %d\n", 11551 ret); 11552 goto out; 11553 11554 err_out: 11555 rsp->hdr.Status = status; 11556 smb2_set_err_rsp(work); 11557 11558 out: 11559 spin_lock(&opinfo->state_lock); 11560 if (opinfo->op_state != OPLOCK_CLOSING) 11561 opinfo->op_state = OPLOCK_STATE_NONE; 11562 spin_unlock(&opinfo->state_lock); 11563 wake_up_interruptible_all(&opinfo->oplock_q); 11564 out_no_state_change: 11565 opinfo_put(opinfo); 11566 ksmbd_fd_put(work, fp); 11567 } 11568 11569 static bool smb2_lease_state_valid(__le32 state) 11570 { 11571 return !(state & ~(SMB2_LEASE_READ_CACHING_LE | 11572 SMB2_LEASE_HANDLE_CACHING_LE | 11573 SMB2_LEASE_WRITE_CACHING_LE)); 11574 } 11575 11576 static int check_lease_state(struct lease *lease, __le32 req_state) 11577 { 11578 if (smb2_lease_state_valid(req_state) && 11579 !(req_state & ~lease->new_state)) 11580 return 0; 11581 11582 return 1; 11583 } 11584 11585 /** 11586 * smb21_lease_break_ack() - handler for smb2.1 lease break command 11587 * @work: smb work containing lease break command buffer 11588 * 11589 * Return: 0 11590 */ 11591 static void smb21_lease_break_ack(struct ksmbd_work *work) 11592 { 11593 struct ksmbd_conn *conn = work->conn; 11594 struct smb2_lease_ack *req; 11595 struct smb2_lease_ack *rsp; 11596 struct oplock_info *opinfo; 11597 int ret = 0; 11598 __le32 lease_state; 11599 struct lease *lease; 11600 11601 WORK_BUFFERS(work, req, rsp); 11602 11603 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n", 11604 le32_to_cpu(req->LeaseState)); 11605 opinfo = lookup_lease_in_table(conn, req->LeaseKey); 11606 if (!opinfo) { 11607 ksmbd_debug(OPLOCK, "file not opened\n"); 11608 smb2_set_err_rsp(work); 11609 rsp->hdr.Status = STATUS_UNSUCCESSFUL; 11610 return; 11611 } 11612 lease = opinfo->o_lease; 11613 11614 if (opinfo->op_state == OPLOCK_STATE_NONE) { 11615 pr_err("unexpected lease break state 0x%x\n", 11616 opinfo->op_state); 11617 if (smb3_hdr_replay(&req->hdr)) 11618 goto replay_rsp; 11619 rsp->hdr.Status = STATUS_UNSUCCESSFUL; 11620 goto err_out; 11621 } 11622 11623 if (!atomic_read(&opinfo->breaking_cnt)) { 11624 if (smb3_hdr_replay(&req->hdr)) 11625 goto replay_rsp; 11626 rsp->hdr.Status = STATUS_UNSUCCESSFUL; 11627 goto err_out; 11628 } 11629 11630 if (check_lease_state(lease, req->LeaseState)) { 11631 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED; 11632 ksmbd_debug(OPLOCK, 11633 "req lease state: 0x%x, expected state: 0x%x\n", 11634 req->LeaseState, lease->new_state); 11635 goto err_out; 11636 } 11637 11638 lease_state = req->LeaseState; 11639 lease->state = lease_state; 11640 lease->new_state = SMB2_LEASE_NONE_LE; 11641 lease_update_oplock_levels(lease); 11642 11643 rsp->StructureSize = cpu_to_le16(36); 11644 rsp->Reserved = 0; 11645 rsp->Flags = 0; 11646 memcpy(rsp->LeaseKey, req->LeaseKey, 16); 11647 rsp->LeaseState = lease_state; 11648 rsp->LeaseDuration = 0; 11649 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack)); 11650 if (ret) 11651 goto err_out; 11652 11653 spin_lock(&opinfo->state_lock); 11654 if (opinfo->op_state != OPLOCK_CLOSING) 11655 opinfo->op_state = OPLOCK_STATE_NONE; 11656 spin_unlock(&opinfo->state_lock); 11657 wake_up_interruptible_all(&opinfo->oplock_q); 11658 atomic_dec_if_positive(&opinfo->breaking_cnt); 11659 wake_up_interruptible_all(&opinfo->oplock_brk); 11660 opinfo_put(opinfo); 11661 return; 11662 11663 replay_rsp: 11664 rsp->StructureSize = cpu_to_le16(36); 11665 rsp->Reserved = 0; 11666 rsp->Flags = 0; 11667 memcpy(rsp->LeaseKey, req->LeaseKey, 16); 11668 rsp->LeaseState = lease->state; 11669 rsp->LeaseDuration = 0; 11670 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack)); 11671 if (ret) 11672 goto err_out; 11673 opinfo_put(opinfo); 11674 return; 11675 11676 err_out: 11677 smb2_set_err_rsp(work); 11678 opinfo_put(opinfo); 11679 return; 11680 } 11681 11682 /** 11683 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break 11684 * @work: smb work containing oplock/lease break command buffer 11685 * 11686 * Return: 0 on success, otherwise error 11687 */ 11688 int smb2_oplock_break(struct ksmbd_work *work) 11689 { 11690 struct smb2_oplock_break *req; 11691 struct smb2_oplock_break *rsp; 11692 11693 ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n"); 11694 11695 WORK_BUFFERS(work, req, rsp); 11696 11697 switch (le16_to_cpu(req->StructureSize)) { 11698 case OP_BREAK_STRUCT_SIZE_20: 11699 smb20_oplock_break_ack(work); 11700 break; 11701 case OP_BREAK_STRUCT_SIZE_21: 11702 smb21_lease_break_ack(work); 11703 break; 11704 default: 11705 ksmbd_debug(OPLOCK, "invalid break cmd %d\n", 11706 le16_to_cpu(req->StructureSize)); 11707 rsp->hdr.Status = STATUS_INVALID_PARAMETER; 11708 smb2_set_err_rsp(work); 11709 return -EINVAL; 11710 } 11711 11712 return 0; 11713 } 11714 11715 /* 11716 * Cancel handler for a deferred CHANGE_NOTIFY. Races against 11717 * __ksmbd_close_fd()'s notify_pendings drain (vfs_cache.c), which can run 11718 * concurrently on a different connection closing the same handle -- only 11719 * one of the two may claim and free in_work, so both sides check 11720 * list_empty() under fp->f_lock before touching it (list_del_init() 11721 * leaves a node empty, so whichever side removes it first is the owner; 11722 * the loser must not touch in_work again, since the winner may already be 11723 * freeing it). 11724 * 11725 * smb2_cancel() holds conn->request_lock (a spinlock) for the entire 11726 * time it walks conn->async_requests and calls this function -- so this 11727 * runs with preemption disabled and must not sleep or re-acquire that 11728 * same lock. release_async_work() does both (it takes conn->request_lock 11729 * itself, and frees things that can involve sleeping paths), so calling 11730 * it from here would self-deadlock the very thread processing the 11731 * client's CANCEL command. ksmbd_conn_write() can also sleep (it takes 11732 * conn's write mutex). So: do only the non-sleeping, no-relock cleanup 11733 * inline here. smb2_cancel() sends and frees the claimed notify after it 11734 * drops request_lock, preserving response order for a client CANCEL. The 11735 * connection teardown caller has no such post-unlock path, so its wrapper 11736 * defers the send and free to a workqueue. 11737 */ 11738 struct notify_cancel_ctx { 11739 struct work_struct work; 11740 struct ksmbd_work *in_work; 11741 }; 11742 11743 static void smb2_send_notify_cancelled(struct ksmbd_work *work) 11744 { 11745 struct smb2_hdr *hdr = smb_get_msg(work->response_buf); 11746 struct ksmbd_conn *conn = work->conn; 11747 struct ksmbd_session *sess; 11748 11749 sess = ksmbd_session_lookup(conn, le64_to_cpu(hdr->SessionId)); 11750 if (sess) { 11751 work->sess = sess; 11752 if (work->encrypted && sess->enc && conn->ops->encrypt_resp) { 11753 conn->ops->encrypt_resp(work); 11754 } else if (conn->ops->is_sign_req && conn->ops->set_sign_rsp && 11755 conn->ops->is_sign_req(work, 11756 conn->ops->get_cmd_val(work))) { 11757 conn->ops->set_sign_rsp(work); 11758 } 11759 } 11760 11761 ksmbd_conn_write(work); 11762 if (sess) { 11763 ksmbd_user_session_put(sess); 11764 work->sess = NULL; 11765 } 11766 } 11767 11768 static void smb2_notify_cancel_deferred(struct work_struct *w) 11769 { 11770 struct notify_cancel_ctx *ctx = 11771 container_of(w, struct notify_cancel_ctx, work); 11772 struct ksmbd_conn *conn = ctx->in_work->conn; 11773 11774 smb2_complete_notify_cancel(ctx->in_work); 11775 kfree(ctx); 11776 /* 11777 * The connection teardown waits for r_count before destroying 11778 * connection sessions and their proc entries. 11779 */ 11780 ksmbd_conn_r_count_dec(conn); 11781 } 11782 11783 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv) 11784 { 11785 struct ksmbd_work *in_work = (struct ksmbd_work *)argv[0]; 11786 struct ksmbd_file *fp = (struct ksmbd_file *)argv[1]; 11787 bool claimed; 11788 11789 spin_lock(&fp->f_lock); 11790 claimed = !list_empty(&in_work->notify_entry); 11791 if (claimed) 11792 list_del_init(&in_work->notify_entry); 11793 spin_unlock(&fp->f_lock); 11794 11795 if (!claimed) 11796 return NULL; 11797 11798 /* conn->request_lock is held by smb2_cancel() or connection teardown. */ 11799 in_work->cancel_fn = NULL; 11800 kfree(in_work->cancel_argv); 11801 in_work->cancel_argv = NULL; 11802 return in_work; 11803 } 11804 11805 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work) 11806 { 11807 struct smb2_hdr *in_hdr = smb_get_msg(in_work->response_buf); 11808 11809 in_hdr->Status = STATUS_CANCELLED; 11810 smb2_send_notify_cancelled(in_work); 11811 release_async_work(in_work); 11812 ksmbd_free_work_struct(in_work); 11813 } 11814 11815 static void smb2_notify_cancel_fn(void **argv) 11816 { 11817 struct ksmbd_work *in_work = smb2_notify_cancel_claim(argv); 11818 struct ksmbd_conn *conn; 11819 struct notify_cancel_ctx *ctx; 11820 11821 if (!in_work) 11822 return; 11823 conn = in_work->conn; 11824 11825 ctx = kmalloc(sizeof(*ctx), GFP_ATOMIC); 11826 if (!ctx) { 11827 /* Can't defer the response -- free without sending one. */ 11828 list_del_init(&in_work->async_request_entry); 11829 in_work->asynchronous = false; 11830 if (in_work->async_id) { 11831 ksmbd_release_id(&conn->async_ida, in_work->async_id); 11832 in_work->async_id = 0; 11833 } 11834 ksmbd_free_work_struct(in_work); 11835 return; 11836 } 11837 ctx->in_work = in_work; 11838 INIT_WORK(&ctx->work, smb2_notify_cancel_deferred); 11839 /* 11840 * This deferred work can outlive the connection handler's receive loop. 11841 * Keep teardown from destroying the connection's sessions until the 11842 * deferred response has finished using them. 11843 */ 11844 ksmbd_conn_r_count_inc(conn); 11845 schedule_work(&ctx->work); 11846 } 11847 11848 /** 11849 * smb2_notify() - handler for smb2 notify request 11850 * @work: smb work containing notify command buffer 11851 * 11852 * Return: 0 on success, otherwise error 11853 */ 11854 int smb2_notify(struct ksmbd_work *work) 11855 { 11856 struct smb2_change_notify_req *req; 11857 struct smb2_change_notify_rsp *rsp; 11858 struct ksmbd_work *in_work; 11859 struct smb2_hdr *in_hdr; 11860 struct ksmbd_file *fp; 11861 11862 ksmbd_debug(SMB, "Received smb2 notify\n"); 11863 11864 WORK_BUFFERS(work, req, rsp); 11865 11866 if (smb2_compound_has_failed(work, &rsp->hdr)) 11867 return -EACCES; 11868 11869 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) { 11870 rsp->hdr.Status = STATUS_INTERNAL_ERROR; 11871 smb2_set_err_rsp(work); 11872 return -EIO; 11873 } 11874 11875 /* 11876 * macOS backupd sends CHANGE_NOTIFY with FileId=FFFF...FFFF (share-root 11877 * sentinel) to watch for changes on the share root without holding an 11878 * open handle. Respond STATUS_PENDING + STATUS_NOTIFY_CLEANUP immediately; 11879 * without this, backupd aborts Time Machine setup on STATUS_FILE_CLOSED. 11880 */ 11881 if (req->VolatileFileId == SMB2_NO_FID && 11882 req->PersistentFileId == SMB2_NO_FID) { 11883 in_work = ksmbd_alloc_work_struct(); 11884 if (!in_work || allocate_interim_rsp_buf(in_work)) { 11885 if (in_work) 11886 ksmbd_free_work_struct(in_work); 11887 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 11888 smb2_set_err_rsp(work); 11889 return 0; 11890 } 11891 if (setup_async_work(work, NULL, NULL)) { 11892 ksmbd_free_work_struct(in_work); 11893 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 11894 smb2_set_err_rsp(work); 11895 return 0; 11896 } 11897 smb2_send_interim_resp(work, STATUS_PENDING); 11898 in_work->conn = work->conn; 11899 in_hdr = smb_get_msg(in_work->response_buf); 11900 memcpy(in_hdr, ksmbd_resp_buf_next(work), 11901 __SMB2_HEADER_STRUCTURE_SIZE); 11902 in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND; 11903 in_hdr->Id.AsyncId = cpu_to_le64(work->async_id); 11904 smb2_set_err_rsp(in_work); 11905 in_hdr->Status = STATUS_NOTIFY_CLEANUP; 11906 in_work->async_id = work->async_id; 11907 work->async_id = 0; 11908 release_async_work(work); 11909 if (smb2_send_interim_work(in_work, work, false)) 11910 ksmbd_debug(SMB, "failed to send notify cleanup\n"); 11911 ksmbd_free_work_struct(in_work); 11912 work->send_no_response = 1; 11913 return 0; 11914 } 11915 11916 /* 11917 * KSMBD does not implement a real change-notification backend. 11918 * Genuine SMB2 servers (and macOS smbfs) never complete a 11919 * CHANGE_NOTIFY spontaneously: it is satisfied only by a real 11920 * directory change, or with STATUS_NOTIFY_CLEANUP when the watched 11921 * handle is closed. Completing it early (e.g. on a timer) makes 11922 * Finder treat the cleanup as "directory changed" and re-enumerate 11923 * the directory forever, leaving items unopenable. Returning 11924 * STATUS_NOT_IMPLEMENTED here (like stock ksmbd) makes macOS smbfs 11925 * hard-freeze on unmount, so this must stay deferred. 11926 */ 11927 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId); 11928 if (!fp) { 11929 rsp->hdr.Status = STATUS_FILE_CLOSED; 11930 smb2_set_err_rsp(work); 11931 return 0; 11932 } 11933 11934 in_work = ksmbd_alloc_work_struct(); 11935 if (!in_work || allocate_interim_rsp_buf(in_work)) { 11936 if (in_work) 11937 ksmbd_free_work_struct(in_work); 11938 ksmbd_fd_put(work, fp); 11939 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 11940 smb2_set_err_rsp(work); 11941 return 0; 11942 } 11943 /* 11944 * in_work is synthetic (not from the normal request-receiving 11945 * pipeline), so it has no request_buf of its own. It gets registered 11946 * into conn->async_requests below, and smb2_cancel() unconditionally 11947 * computes smb_get_msg(iter->request_buf) for every entry in that 11948 * list while searching for a match -- give it its own small buffer 11949 * (not an alias of response_buf: ksmbd_free_work_struct() kvfree()s 11950 * both separately, so aliasing them would double-free) so that stays 11951 * a harmless read instead of a near-NULL dereference. 11952 */ 11953 in_work->request_buf = kzalloc(MAX_CIFS_SMALL_BUFFER_SIZE, KSMBD_DEFAULT_GFP); 11954 if (!in_work->request_buf) { 11955 ksmbd_free_work_struct(in_work); 11956 ksmbd_fd_put(work, fp); 11957 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 11958 smb2_set_err_rsp(work); 11959 return 0; 11960 } 11961 memcpy(smb_get_msg(in_work->request_buf), req, 11962 __SMB2_HEADER_STRUCTURE_SIZE); 11963 11964 if (setup_async_work(work, NULL, NULL)) { 11965 ksmbd_free_work_struct(in_work); 11966 ksmbd_fd_put(work, fp); 11967 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES; 11968 smb2_set_err_rsp(work); 11969 return 0; 11970 } 11971 11972 smb2_send_interim_resp(work, STATUS_PENDING); 11973 11974 /* Keep the async IDA alive until the deferred work is released. */ 11975 in_work->conn = ksmbd_conn_get(work->conn); 11976 in_work->owns_conn_ref = true; 11977 in_work->encrypted = work->encrypted; 11978 in_hdr = smb_get_msg(in_work->response_buf); 11979 memcpy(in_hdr, ksmbd_resp_buf_next(work), __SMB2_HEADER_STRUCTURE_SIZE); 11980 in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND; 11981 in_hdr->Id.AsyncId = cpu_to_le64(work->async_id); 11982 smb2_set_err_rsp(in_work); 11983 in_hdr->Status = STATUS_NOTIFY_CLEANUP; 11984 11985 /* 11986 * Transfer ownership of the async id to in_work; it stays reserved 11987 * until in_work is freed after the deferred response is sent on 11988 * close, so it can't be reused for an unrelated async response. 11989 */ 11990 in_work->async_id = work->async_id; 11991 work->async_id = 0; 11992 release_async_work(work); 11993 11994 /* 11995 * work itself is about to be recycled by the normal request-processing 11996 * pipeline, so it can't stay the target of a future CANCEL -- register 11997 * in_work instead, reusing the same async_id, so a client-sent CANCEL 11998 * for this notify actually finds something to cancel instead of 11999 * silently doing nothing until the handle eventually closes. 12000 */ 12001 in_work->asynchronous = true; 12002 in_work->cancel_argv = kmalloc_array(2, sizeof(void *), KSMBD_DEFAULT_GFP); 12003 if (in_work->cancel_argv) { 12004 in_work->cancel_argv[0] = in_work; 12005 in_work->cancel_argv[1] = fp; 12006 in_work->cancel_fn = smb2_notify_cancel_fn; 12007 } 12008 12009 if (!ksmbd_conn_link_async_request(work->conn, in_work)) { 12010 kfree(in_work->cancel_argv); 12011 in_work->cancel_argv = NULL; 12012 in_work->cancel_fn = NULL; 12013 in_work->asynchronous = false; 12014 ksmbd_fd_put(work, fp); 12015 if (smb2_send_interim_work(in_work, work, false)) 12016 ksmbd_debug(SMB, "failed to send notify cleanup\n"); 12017 ksmbd_free_work_struct(in_work); 12018 work->send_no_response = 1; 12019 return 0; 12020 } 12021 12022 spin_lock(&fp->f_lock); 12023 list_add_tail(&in_work->notify_entry, &fp->notify_pendings); 12024 spin_unlock(&fp->f_lock); 12025 12026 ksmbd_fd_put(work, fp); 12027 work->send_no_response = 1; 12028 return 0; 12029 } 12030 12031 /** 12032 * smb2_is_sign_req() - handler for checking packet signing status 12033 * @work: smb work containing notify command buffer 12034 * @command: SMB2 command id 12035 * 12036 * Return: true if packed is signed, false otherwise 12037 */ 12038 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command) 12039 { 12040 struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf); 12041 12042 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) && 12043 command != SMB2_NEGOTIATE_HE) 12044 return true; 12045 12046 return false; 12047 } 12048 12049 /** 12050 * smb2_check_sign_req() - handler for req packet sign processing 12051 * @work: smb work containing notify command buffer 12052 * 12053 * Return: 1 on success, 0 otherwise 12054 */ 12055 int smb2_check_sign_req(struct ksmbd_work *work) 12056 { 12057 struct smb2_hdr *hdr; 12058 char signature_req[SMB2_SIGNATURE_SIZE]; 12059 char signature[SMB2_HMACSHA256_SIZE]; 12060 struct kvec iov[1]; 12061 size_t len; 12062 12063 hdr = smb_get_msg(work->request_buf); 12064 if (work->next_smb2_rcv_hdr_off) 12065 hdr = ksmbd_req_buf_next(work); 12066 12067 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off) 12068 len = get_rfc1002_len(work->request_buf); 12069 else if (hdr->NextCommand) 12070 len = le32_to_cpu(hdr->NextCommand); 12071 else 12072 len = get_rfc1002_len(work->request_buf) - 12073 work->next_smb2_rcv_hdr_off; 12074 12075 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE); 12076 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE); 12077 12078 iov[0].iov_base = (char *)&hdr->ProtocolId; 12079 iov[0].iov_len = len; 12080 12081 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1, 12082 signature); 12083 12084 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) { 12085 pr_err("bad smb2 signature\n"); 12086 return 0; 12087 } 12088 12089 return 1; 12090 } 12091 12092 /** 12093 * smb2_get_sign_rsp_iov() - get the iovecs used to sign a response 12094 * @work: work that has the response iovecs 12095 * @hdr: SMB2 header of the response 12096 * @n_vec: set to the number of iovecs to sign 12097 * 12098 * Response data may be in another buffer. In this case, the response uses 12099 * more than one iovec. Find the iovec that starts with @hdr. Sign this 12100 * iovec and all iovecs after it. 12101 * 12102 * Return: The first iovec to sign. 12103 */ 12104 static struct kvec *smb2_get_sign_rsp_iov(struct ksmbd_work *work, 12105 struct smb2_hdr *hdr, int *n_vec) 12106 { 12107 int i; 12108 12109 /* 12110 * iov[0] has the RFC1002 message length. It is not part of the SMB2 12111 * message, so do not sign it. 12112 */ 12113 for (i = 1; i <= work->iov_idx; i++) { 12114 if (work->iov[i].iov_base == hdr) { 12115 *n_vec = work->iov_idx - i + 1; 12116 return &work->iov[i]; 12117 } 12118 } 12119 12120 WARN_ON_ONCE(1); 12121 *n_vec = 1; 12122 return &work->iov[work->iov_idx]; 12123 } 12124 12125 /** 12126 * smb2_set_sign_rsp() - handler for rsp packet sign processing 12127 * @work: smb work containing notify command buffer 12128 * 12129 */ 12130 void smb2_set_sign_rsp(struct ksmbd_work *work) 12131 { 12132 struct smb2_hdr *hdr; 12133 char signature[SMB2_HMACSHA256_SIZE]; 12134 struct kvec *iov; 12135 int n_vec; 12136 12137 hdr = ksmbd_resp_buf_curr(work); 12138 hdr->Flags |= SMB2_FLAGS_SIGNED; 12139 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE); 12140 12141 iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec); 12142 12143 ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec, 12144 signature); 12145 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE); 12146 } 12147 12148 /** 12149 * smb3_check_sign_req() - handler for req packet sign processing 12150 * @work: smb work containing notify command buffer 12151 * 12152 * Return: 1 on success, 0 otherwise 12153 */ 12154 int smb3_check_sign_req(struct ksmbd_work *work) 12155 { 12156 struct ksmbd_conn *conn = work->conn; 12157 char *signing_key; 12158 struct smb2_hdr *hdr; 12159 struct channel *chann; 12160 char signature_req[SMB2_SIGNATURE_SIZE]; 12161 char signature[SMB2_CMACAES_SIZE]; 12162 struct kvec iov[1]; 12163 size_t len; 12164 12165 hdr = smb_get_msg(work->request_buf); 12166 if (work->next_smb2_rcv_hdr_off) 12167 hdr = ksmbd_req_buf_next(work); 12168 12169 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off) 12170 len = get_rfc1002_len(work->request_buf); 12171 else if (hdr->NextCommand) 12172 len = le32_to_cpu(hdr->NextCommand); 12173 else 12174 len = get_rfc1002_len(work->request_buf) - 12175 work->next_smb2_rcv_hdr_off; 12176 12177 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) { 12178 signing_key = work->sess->smb3signingkey; 12179 } else { 12180 chann = lookup_chann_list(work->sess, conn); 12181 if (!chann) { 12182 if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE || 12183 !(hdr->Flags & SMB2_FLAGS_SIGNED)) 12184 return 0; 12185 signing_key = work->sess->smb3signingkey; 12186 } else { 12187 signing_key = chann->smb3signingkey; 12188 } 12189 } 12190 12191 if (!signing_key) { 12192 pr_err("SMB3 signing key is not generated\n"); 12193 return 0; 12194 } 12195 12196 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE); 12197 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE); 12198 iov[0].iov_base = (char *)&hdr->ProtocolId; 12199 iov[0].iov_len = len; 12200 12201 ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature); 12202 12203 if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) { 12204 pr_err("bad smb2 signature\n"); 12205 return 0; 12206 } 12207 12208 return 1; 12209 } 12210 12211 /** 12212 * smb3_set_sign_rsp() - handler for rsp packet sign processing 12213 * @work: smb work containing notify command buffer 12214 * 12215 */ 12216 void smb3_set_sign_rsp(struct ksmbd_work *work) 12217 { 12218 struct ksmbd_conn *conn = work->conn; 12219 struct smb2_hdr *hdr; 12220 struct channel *chann; 12221 char signature[SMB2_CMACAES_SIZE]; 12222 struct kvec *iov; 12223 u16 command = conn->ops->get_cmd_val(work); 12224 int n_vec; 12225 char *signing_key; 12226 12227 hdr = ksmbd_resp_buf_curr(work); 12228 12229 if (command == SMB2_SESSION_SETUP_HE && 12230 (!conn->binding || hdr->Status != STATUS_SUCCESS)) { 12231 signing_key = work->sess->smb3signingkey; 12232 } else { 12233 chann = lookup_chann_list(work->sess, work->conn); 12234 if (!chann) { 12235 return; 12236 } 12237 signing_key = chann->smb3signingkey; 12238 } 12239 12240 if (!signing_key) 12241 return; 12242 12243 hdr->Flags |= SMB2_FLAGS_SIGNED; 12244 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE); 12245 12246 iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec); 12247 12248 ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature); 12249 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE); 12250 } 12251 12252 /** 12253 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response 12254 * @work: smb work containing response buffer 12255 * 12256 */ 12257 void smb3_preauth_hash_rsp(struct ksmbd_work *work) 12258 { 12259 struct ksmbd_conn *conn = work->conn; 12260 struct ksmbd_session *sess = work->sess; 12261 struct smb2_hdr *req, *rsp; 12262 12263 if (conn->dialect != SMB311_PROT_ID) 12264 return; 12265 12266 WORK_BUFFERS(work, req, rsp); 12267 12268 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) { 12269 ksmbd_conn_lock(conn); 12270 if (conn->preauth_info) 12271 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf, 12272 conn->preauth_info->Preauth_HashValue); 12273 ksmbd_conn_unlock(conn); 12274 } 12275 12276 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) { 12277 ksmbd_conn_lock(conn); 12278 12279 if (conn->binding) { 12280 struct preauth_session *preauth_sess; 12281 12282 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id); 12283 if (preauth_sess) 12284 ksmbd_gen_preauth_integrity_hash(conn, 12285 work->response_buf, 12286 preauth_sess->Preauth_HashValue); 12287 } else if (sess->Preauth_HashValue) { 12288 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf, 12289 sess->Preauth_HashValue); 12290 } 12291 ksmbd_conn_unlock(conn); 12292 } 12293 } 12294 12295 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type) 12296 { 12297 struct smb2_transform_hdr *tr_hdr = tr_buf + 4; 12298 struct smb2_hdr *hdr = smb_get_msg(old_buf); 12299 unsigned int orig_len = get_rfc1002_len(old_buf); 12300 12301 /* tr_buf must be cleared by the caller */ 12302 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM; 12303 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len); 12304 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED); 12305 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM || 12306 cipher_type == SMB2_ENCRYPTION_AES256_GCM) 12307 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE); 12308 else 12309 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE); 12310 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8); 12311 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr)); 12312 inc_rfc1001_len(tr_buf, orig_len); 12313 } 12314 12315 int smb3_encrypt_resp(struct ksmbd_work *work) 12316 { 12317 struct kvec *iov = work->iov; 12318 int rc = -ENOMEM; 12319 void *tr_buf; 12320 12321 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP); 12322 if (!tr_buf) 12323 return rc; 12324 12325 /* fill transform header */ 12326 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type); 12327 12328 iov[0].iov_base = tr_buf; 12329 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4; 12330 work->tr_buf = tr_buf; 12331 12332 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1); 12333 } 12334 12335 bool smb3_is_transform_hdr(void *buf) 12336 { 12337 struct smb2_transform_hdr *trhdr = smb_get_msg(buf); 12338 12339 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM; 12340 } 12341 12342 int smb3_decrypt_req(struct ksmbd_work *work) 12343 { 12344 char *buf = work->request_buf; 12345 unsigned int pdu_length = get_rfc1002_len(buf); 12346 struct kvec iov[2]; 12347 unsigned int buf_data_size; 12348 struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf); 12349 unsigned int original_msg_size; 12350 int rc = 0; 12351 12352 if (pdu_length < sizeof(struct smb2_transform_hdr)) { 12353 pr_err("Transform message is too small (%u)\n", 12354 pdu_length); 12355 return -ECONNABORTED; 12356 } 12357 12358 buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr); 12359 original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize); 12360 if (buf_data_size < sizeof(struct smb2_compression_hdr) || 12361 original_msg_size < sizeof(struct smb2_compression_hdr)) { 12362 pr_err("Transform message is too small (%u)\n", 12363 pdu_length); 12364 return -ECONNABORTED; 12365 } 12366 12367 if (buf_data_size < original_msg_size) { 12368 pr_err("Transform message is broken\n"); 12369 return -ECONNABORTED; 12370 } 12371 12372 iov[0].iov_base = buf; 12373 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4; 12374 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4; 12375 iov[1].iov_len = buf_data_size; 12376 rc = ksmbd_crypt_message(work, iov, 2, 0); 12377 if (rc) 12378 return rc; 12379 12380 /* Drop the AEAD authentication tag from the inner RFC1002 frame. */ 12381 memmove(buf + 4, iov[1].iov_base, original_msg_size); 12382 *(__be32 *)buf = cpu_to_be32(original_msg_size); 12383 12384 return rc; 12385 } 12386 12387 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work) 12388 { 12389 struct ksmbd_conn *conn = work->conn; 12390 struct ksmbd_session *sess = work->sess; 12391 struct smb2_hdr *rsp = smb_get_msg(work->response_buf); 12392 12393 if (conn->dialect < SMB30_PROT_ID) 12394 return false; 12395 12396 if (work->next_smb2_rcv_hdr_off) 12397 rsp = ksmbd_resp_buf_next(work); 12398 12399 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && 12400 sess->user && !user_guest(sess->user) && 12401 rsp->Status == STATUS_SUCCESS) 12402 return true; 12403 return false; 12404 } 12405