| Age | Commit message (Collapse) | Author |
|
This is another run of the Coccinelle script for converting kmalloc()
family of allocations to kmalloc_obj() via the existing rules in
scripts/coccinelle/api/kmalloc_objs.cocci
This catches both the set of kmalloc() uses added since the first
kmalloc_obj() conversions in v7.0 and adds a large group missed in the
first pass due to Coccinelle not interacting well with the cleanup.h
scoped_...() family of macros[1]. I worked around this with spatch's
"--macro-file" argument to a file with all the scoped_...() macros mapped
to Coccinelle's YACFE_ITERATOR[2] as that was the closest viable control
flow indicator I could find.
Build tested allmodconfig on x86, arm64, arm, loongarch, mips, powerpc,
riscv, and s390 with no new warnings.
Link: https://lore.kernel.org/lkml/202609021314.8A9C0B8@keescook/ [1]
Link: https://github.com/coccinelle/coccinelle/blob/master/standard.h [2]
Signed-off-by: Kees Cook <kees+treewide@kernel.org>
|
|
ksmbd_tree_conn_connect() publishes a new tree connection in
sess->tree_conns with a single reference and returns its pointer to
smb2_tree_connect(). The handler continues to initialize the object and
build the response after publication. A concurrent session logoff can
erase the connection and drop that reference, freeing the object while
the handler still uses it.
BUG: KASAN: slab-use-after-free in smb2_tree_connect+0xe3d/0xf90
smb2_tree_connect (fs/smb/server/smb2pdu.c:2872)
handle_ksmbd_work
process_one_work
worker_thread
kthread
After xa_store() succeeds, take a second reference before releasing
tree_conns_lock. The original reference belongs to the xarray entry and
the second belongs to the creating smb2_tree_connect() handler.
Keep the references balanced in every path:
- On normal exit or an error after publication, smb2_tree_connect()
drops its creator reference. Error cleanup also calls
ksmbd_tree_conn_disconnect(), which drops the xarray reference only if
it removes the exact entry.
- SMB2 TREE_DISCONNECT uses the same helper to remove the entry and drop
its xarray reference. The request's existing lookup reference remains
owned by the request and is released by the existing cleanup.
- Session LOGOFF removes each entry and drops its xarray reference. If
it wins the race, later cleanup sees that the entry is gone and does
not drop that reference again.
To enforce this ownership, claim the disconnected state and erase the
exact entry atomically under tree_conns_lock. This guarantees one drop
for the xarray reference and one drop by each in-flight user, regardless
of which teardown path wins. If logoff removes the entry before
initialization completes, fail the connect instead of marking the
detached object TREE_CONNECTED.
Fixes: 33b235a6e6eb ("ksmbd: fix race condition between tree conn lookup and disconnect")
Reported-by: Xiang Mei (Microsoft) <xmei5@asu.edu>
Cc: AutonomousCodeSecurity@microsoft.com
Cc: stable@vger.kernel.org
Signed-off-by: Cen Zhang (Microsoft Security FORGE Labs) <cenzhang@linux.microsoft.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
ksmbd_vfs_copy_file_ranges() rejects negative source offsets in the
copy loop, but it does not validate target offsets. It also calculates
lock and overlap endpoints before ensuring that either range fits within
MAX_LFS_FILESIZE.
When the target is an alternate data stream, the buffered path passes a
negative target offset to ksmbd_vfs_stream_write(). Let n be Length and
let -d be TargetOffset, where 0 < d < n <= XATTR_SIZE_MAX. For an empty
stream, the writer allocates n - d bytes, then copies n bytes starting d
bytes before the allocation. An authenticated SMB client can control d
and the source data, overwrite kernel heap memory, and crash the host.
Validate both ranges before lock, overlap, or I/O calculations.
Fixes: 8482150a0743 ("ksmbd: support copychunk for alternate data streams")
Assisted-by: Antiproof:GPT-5.6-Sol
Signed-off-by: Alon Shakevsky <shakevsky@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
smb2_oplock_break_noti() reads opinfo->conn without any lock and
dereferences it after two allocations which may sleep. When the
durable handle owning the oplock is disconnected, session_fd_check()
clears opinfo->conn and drops its conn reference under ci->m_lock, and
the last ksmbd_conn_put() frees the connection. A break triggered by
another connection that races with the teardown can then resurrect the
freed connection: ksmbd_conn_get() is a plain atomic_inc, and the
queued break work later dereferences the stale conn via
ksmbd_conn_write(), a use-after-free reachable by any authenticated
client holding a durable batch oplock.
Thread the caller's inode into the notification path instead of taking
a new reference on it. Every caller of oplock_break() already holds a
live ksmbd_file (or an explicit ksmbd_inode_lookup_lock() reference,
in the parent lease break paths) on the inode that owns the break
target's oplock list, so ci cannot be freed during the call, and its
lock can be taken without dereferencing opinfo->o_fp, which a
concurrent close may free. Select and pin the connection under
ci->m_lock, the same lock session_fd_check() and
ksmbd_reopen_durable_fd() use to update opinfo->conn, so a concurrent
detach either loses the race to the clear or keeps the connection
alive until the notification work releases it. Transfer the reference
to the work item and release it on allocation failures.
Fixes: b003086d7696 ("ksmbd: fix NULL-deref of opinfo->conn in oplock/lease break notifiers")
Cc: stable@vger.kernel.org
Signed-off-by: Abdifatah Suruur <suruurism@gmail.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Use an unsigned int for the work state so xchg() uses a supported
4-byte operation on sparc.
Fixes: d12168084c8c ("ksmbd: safely drain sessions during logoff")
Reported-by: kernel test robot <lkp@intel.com>
Closes: https://lore.kernel.org/oe-kbuild-all/202609021157.8f7Wx34I-lkp@intel.com/
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
FILE_NORMALIZED_NAME_INFORMATION converts the open file path to UTF-16.
smb2_allocate_rsp_buf() leaves these responses in the 448-byte small
buffer, and get_file_normalized_name_info() converts the path without
checking the remaining space.
An authenticated client can query a long path and make
smbConvertToUTF16() write beyond work->response_buf.
Use the large response buffer for normalized-name queries. Before
conversion, verify that the response has room for the worst-case UTF-16
output and its terminator.
Fixes: 10aeff72ab82 ("ksmbd: support normalized name information")
Assisted-by: Antiproof:GPT-5.6-Sol
Signed-off-by: Alon Shakevsky <shakevsky@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
The listener thread exits when its listening socket is shutdown. The
netdevice notifier shuts down the socket before calling kthread_stop(), so
the task_struct can be freed before kthread_stop() gets its reference.
Create the listener in a stopped state and hold an extra task_struct
reference until kthread_stop_put() completes. Also stop and release
listeners before freeing their interface records during TCP teardown.
Fixes: 3316a8fc840d ("ksmbd: server: avoid busy polling in accept loop")
Reported-by: Farhad Alemi <farhad.alemi@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Validate IPC share configuration payload sizes before consuming
variable-length fields. Bound veto list parsing and account for
the separator byte when deriving the path length.
Fixes: a677ebd8ca2f ("ksmbd: validate payload size in ipc response")
Reported-by: Kanishka De Silva <kpskanna1915@gmail.com>
Reported-by: Farhad Alemi <farhad.alemi@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
A client can include many structurally valid but unmapped SIDs in a DACL.
Logging every mapping failure lets one request generate hundreds of kernel
error messages.
Rate limit the message to prevent an authenticated client from flooding
the kernel log.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
parse_dacl() silently accepts truncated ACEs and allocation failures,
allowing set_info_sec() to continue with an incomplete ACL conversion.
Return parsing and allocation errors to parse_sec_desc() so malformed
security descriptors are rejected before inode attributes or ACL xattrs
are updated.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Compound response handling extends the last response iov to an eight-byte
boundary.
smb2_read_pipe() allocates only the payload size, so the alignment padding
can expose up to seven bytes of uninitialized kernel heap memory.
Allocate the aligned size and clear the unused tail before pinning the
response buffer.
Fixes: e2b76ab8b5c9 ("ksmbd: add support for read compound")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
SMB3 multichannel allows requests for one session to run on multiple
connections. Wait for all channels bound to a session before freeing
shared session objects.
A deferred byte-range lock remains counted as a running request and only
wakes when its file closes. Wake blocked locks during the drain without
unpublishing or modifying their file objects. Synchronous CANCEL requests
must invoke their cancellation callback to wake pending operations, while
CHANGE_NOTIFY completion remains specific to the asynchronous path.
Serialize session teardown with channel registration and previous-session
cleanup, and use atomic work-state transitions so LOGOFF, CANCEL, and
connection teardown invoke cancellation callbacks only once.
Fixes: 76e98a158b20 ("ksmbd: fix race condition between destroy_previous_session() and smb2 operations()")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
smb2_get_info_filesystem() reports 56 bytes for FS_POSIX_INFORMATION,
that is the whole of FILE_SYSTEM_POSIX_INFO, but never assigns
FileSysIdentifier. Those eight bytes go to the client as they are found
in the response buffer.
The buffer is zeroed on allocation, so a standalone request leaks
nothing. A compound request can leak: the offset of the next response
is advanced by the length pinned for the previous one, so a reply that
was written into the buffer and then dropped in favour of the short
error response of smb2_set_err_rsp() stays there, and the next reply is
laid over it with only the header cleared.
Report the file system id statfs() returned, which is what the field is
for. FileSysIdentifier is __le64 and f_fsid is a pair of ints, so
assemble the value first, val[0] as the low half, and convert it on the
way out.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
smb2_get_info_filesystem() reports 48 bytes for FS_CONTROL_INFORMATION,
that is the whole of struct smb2_fs_control_info, but never assigns
FileSystemControlFlags. Those four bytes go to the client as they are
found in the response buffer.
The buffer is zeroed on allocation, so a standalone request leaks
nothing. A compound request can leak: the offset of the next response
is advanced by the length pinned for the previous one, so a reply that
was written into the buffer and then dropped in favour of the short
error response of smb2_set_err_rsp() stays there, and the next reply is
laid over it with only the header cleared.
ksmbd does not implement quota tracking, so report no control flags.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
smb2_get_info_filesystem() reports 64 bytes for FS_OBJECT_ID_INFORMATION,
that is the whole of struct object_id_info, but writes only 46 of them:
- objid[] is 16 bytes, and when the volume UUID is not available only
sizeof(stfs.f_fsid) (8) bytes are copied into it;
- extended_info.version_string[] is STRING_LENGTH (28) bytes, and only
strlen("1.1.0") (5) bytes are copied into it.
The response buffer is zeroed on allocation (kvzalloc() in
smb2_allocate_rsp_buf()), so for a standalone request the remaining 31
bytes are zero. In a compound request they need not be. The offset of
the next response is advanced by the length pinned for the previous one,
so if a preceding command wrote its reply into the buffer and then
failed, smb2_set_err_rsp() pins only the short error response and the
next reply lands inside the area that has already been written. Only
the header is cleared there:
memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
The client then receives up to 31 bytes of a response it was not meant
to see, including one that failed with an access denied error.
Clear the structure before filling it in. As a side effect
version_string is now NUL terminated.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Suggested-by: ChenXiaoSong <chenxiaosong@chenxiaosong.com>
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb
Pull smb server updates from Namjae Jeon:
"This contains server updates focused on SMB2 command sequencing, SMB3
request replay and encryption, Apple Time Machine interoperability,
protocol-compatibility fixes validated with smbtorture, security
hardening, SMB Direct transport support, connection reliability, and
other correctness improvements.
New features:
- Implement the SMB2 command sequence window
Enforce the credit-based MessageId range for each connection,
rejecting out-of-window, duplicate, and wrapped sequence numbers.
This prevents invalid requests and same-channel replays from being
processed
- Add SMB3 request replay support
SMB3 clients may resend requests with SMB2_FLAGS_REPLAY_OPERATION
after a channel disconnect when the original response was lost.
Track the required channel and open state to safely handle durable
CREATE replays and make oplock, lease, and lock replays idempotent,
avoiding duplicate state changes and improving multichannel
reconnect reliability
- Add opt-in Apple Time Machine support
Implement the AAPL negotiation and related Finder, stream,
COPYCHUNK, sparse-file, CHANGE_NOTIFY, and RPC compatibility
required for Time Machine shares, allowing macOS backupd to use
ksmbd for backups
- Add per-share SMB3 encryption support
Allow individual shares to require SMB3 encryption by advertising
SMB2_SHAREFLAG_ENCRYPT_DATA in TREE_CONNECT responses and rejecting
unencrypted tree connects and plaintext requests for protected
shares
- Add SMB Direct RDMA encryption support
Extend SMB Direct to support SMB3 encrypted payloads over RDMA,
with transform negotiation and encryption/decryption for RDMA
READ/WRITE
Other changes:
- Parse and retain AppInstanceVersion contexts, enforce version
ordering, close older active handles for newer takeovers, and
reject invalid or unversioned opens according to the SMB2 semantics
- Accept durable reconnect requests that omit VolatileFileId when the
persistent ID and reconnect context identify the handle, while
continuing to reject explicit volatile-ID mismatches
- Fix SMB2/SMB3 protocol validation and security issues, including
request offsets, file and object IDs, IPC responses, output buffer
sizes, SMB3.1.1 binding validation, signing-required handling,
durable handles, ACLs, maximal access, and security information
- Fix heap out-of-bounds accesses, use-after-free bugs, memory leaks,
invalid pointer dereferences, and sensitive-data lifetime issues in
authentication, Kerberos, preauthentication, sessions, connections,
and module teardown
- Correct alternate-data-stream and named-stream handling, COPYCHUNK
behavior, sparse-file and compression attributes, allocated-range
queries, file trimming, duplicate extents, DOS attributes,
snapshots, normalized names, and partial information responses
- Fix locking, lease, oplock, durable reconnect, async request, and
CHANGE_NOTIFY races, including deferred-lock rollback, parent
directory lease notifications, and connection teardown lifetime
bugs
- Fix SMB3 encryption handling for compressed requests, expired
encrypted sessions, interim responses, bound multichannel
connections, and decryption failures
- Fix SMB3 multichannel session lookup and session state transitions
so changes are scoped to the correct bound connections and cannot
revive connections that are already shutting down
- Fix DACL access checks so ACE walks are bounded by the declared
DACL size, preventing data beyond the DACL boundary from being
interpreted during access validation
- Fix session accounting and lifetime issues, including session
counter updates during publication and removal, session leaks on
registration failure, and procfs creation diagnostics
- Improve TCP connection reliability by enabling TCP keepalive for
accepted connections and preserving TCP timers for kernel sockets,
preventing silent peers from holding connections indefinitely
- Fix smbdirect RDMA cleanup ordering for completion queues, QPs,
child sockets, and listener locking
- Improve async response framing, multi-iovec signing, RPC pipe
status handling, and ksmbd procfs monitoring for server, share,
connection, session, and open-file state
- Remove the obsolete DES crypto header and Kconfig dependency now
that NTLMv1 support has been removed
- Update the ksmbd repository URL in MAINTAINERS and add an
additional KSMBD reviewer"
* tag 'ksmbd-for-7.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb: (142 commits)
MAINTAINERS: update ksmbd repository URL
MAINTAINERS: add myself as KSMBD reviewer
smb: server: remove unused DES crypto header
smb: server: Remove obsolete "select CRYPTO_LIB_DES" from Kconfig file
ksmbd: keep TCP timers alive for kernel sockets
ksmbd: enable TCP keepalive for accepted connections
smb/server: fix session counter on session removal
smb/server: update session counter under sessions table lock
smb/server: fix session leak in ksmbd_session_register()
smb/server: warn if ksmbd_proc_create() fails
ksmbd: bound smb_check_perm_dacl() ACE walks by DACL size
ksmbd: make RDMA encryption diagnostics conditional
ksmbd: add SMB Direct RDMA encryption transform
ksmbd: handle encrypted compressed requests
ksmbd: decrypt requests from expired encrypted sessions
ksmbd: disconnect on SMB3 decryption failure
ksmbd: encrypt interim responses to encrypted requests
ksmbd: scope session state changes to bound connections
ksmbd: fix encrypted request lookup on bound channels
ksmbd: add per-share SMB3 encryption enforcement
...
|
|
The DES crypto header is no longer used after the removal of NTLMv1
authentication. Remove it now that the server no longer selects
CRYPTO_LIB_DES.
Fixes: ce812992f239 ("ksmbd: remove NTLMv1 authentication")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
The DES encryption in the smb server code has been removed in 2021
with the removal of the insecure NTLMv1 authentication code. Thus
we don't need this "select" statement here anymore.
Fixes: ce812992f239f ("ksmbd: remove NTLMv1 authentication")
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
ksmbd creates its listening socket with sock_create_kern(). Kernel
sockets do not hold a network namespace reference by default. Accepted
sockets inherit this state.
When an accepted socket is released, tcp_close() clears its pending TCP
timers for a kernel socket after the socket enters an orphaned state. If
the peer is unreachable while ksmbd sends a FIN, this can leave a
FIN-WAIT-1 orphan without a retransmission timer.
Upgrade the listening socket's network namespace reference before
kernel_listen(). Accepted sockets inherit the reference, so the TCP
stack can keep the retransmission timer active and apply its normal
orphan retry policy.
Preserve the existing graceful shutdown behavior.
Link: https://github.com/openwrt/openwrt/issues/24744
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
A client that disappears without sending a FIN or RST can leave its
ksmbd connection in ESTABLISHED indefinitely. ksmbd sets a socket
receive timeout, but the connection receive loop retries timeout errors
without a limit, so the connection remains in conn_list and consumes the
per-IP connection quota.
Enable SO_KEEPALIVE on accepted TCP sockets so the TCP stack can detect a
silent peer failure. The keepalive idle time, interval, and probe count
remain controlled by the existing TCP sysctl settings.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
git://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux
Pull crypto library updates from Eric Biggers:
"Add library APIs for most AES encryption modes that are used in the
kernel (ECB, CBC, CBC-CTS, CTR, XCTR, XTS, GCM, CCM).
These AES modes have many in-kernel users that are currently using the
crypto_skcipher or crypto_aead APIs. These existing APIs are difficult
to use and inefficient. Until now, the lack of proper library support
for these has been the main gap in the crypto library.
This set of changes is the next stage of addressing it:
- Implement the new APIs on top of the existing support for
single-block AES in the library.
- Fully document the new APIs.
- Migrate the only user of the old AES-GCM library API to the new,
more flexible API; then remove the old API and its implementation.
- Wire up the new APIs to the traditional crypto API by adding
crypto_skcipher and crypto_aead algorithms.
This makes the new APIs be covered by the traditional crypto API's
self-tests. It also makes them be already used for real on systems
that don't have architecture-optimized code for these modes.
But most importantly, this is a prerequisite for migrating the
architecture-optimized code for these AES modes (i.e.
arch/*/crypto/aes*) into the library, which as usual will eliminate
a lot of redundant "glue" code.
Note that unlike some of the other algorithms that have been migrated
to the library, e.g. SHA-512, for these AES modes there was too much
to get done in one cycle. Nor did it make sense to handle these modes
one at a time, because they tend to be coupled together or depend on
each other, especially in the architecture-optimized AES code.
Thus, most of the benefits (reductions in lines of code, performance
improvements, etc.) will follow in later cycles when
architecture-optimized code is migrated into the library and users of
crypto_skcipher and crypto_aead are updated to use the new APIs.
The design of the new APIs was informed by writing proof-of-concept
patches for many kernel subsystems currently accessing these same
algorithms via crypto_skcipher or crypto_aead (patches 18-33 of
https://lore.kernel.org/r/20260707053503.209874-1-ebiggers@kernel.org/).
While those patches will be resent for real later, the total diffstat
for them was negative 1905 lines. So clearly the new APIs are quite a
bit easier to use and align better with what users actually need.
Besides the new AES encryption APIs, there are also a few changes for
improved AES-CMAC key and context zeroization"
* tag 'libcrypto-updates-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux:
mac80211: fils_aead: Use __cleanup() instead of memzero_explicit()
Bluetooth: SMP: clear the aes_cmac_key when done
smb: clear the aes_cmac_key and aes_cmac_ctx when done
lib/crypto: aes-cmac: Add zeroization functions
lib/crypto: aesgcm: Remove old AES-GCM library
x86/sev: Remove obsolete virtual address check
x86/sev: Use new AES-GCM library
crypto: aes - Add CCM support using library
crypto: aes - Add GCM support using library
crypto: aes - Add XTS support using library
crypto: aes - Add CTR and XCTR support using library
crypto: aes - Add CBC and CBC-CTS support using library
crypto: aes - Add ECB support using library
lib/crypto: aes: Add CCM support
lib/crypto: aes: Add GCM support
lib/crypto: aes: Add XTS support
lib/crypto: aes: Add CTR and XCTR support
lib/crypto: aes: Add CBC and CBC-CTS support
lib/crypto: aes: Add ECB support
crypto: xts - Split out __xts_verify_key() helper
|
|
git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs
Pull kthread vfs updates from Christian Brauner:
"This stops kernel threads from sharing filesystem state with
userspace. This work is about 3 cycles old and has been in -next
for about that time.
When the kernel boots init_task creates PID 1 and then kthreadd. From
that point every kthread and PID 1 share the same fs_struct. That is
why pivot_root() has to rewrite the fs_struct of all kthreads. The
rewriting exists so that kthreads can use init's filesystem state when
they want to. It also means userspace can move the ground out from
under the kernel.
PID 1 now gets a completely separate fs_struct. All kthreads are
anchored in a private SB_KERNMOUNT instance of nullfs that cannot be
mounted on and cannot be used to follow other mounts. Userspace init
can no longer affect kthread filesystem state and kthreads can no
longer affect userspace fs state without explicit opting in to that.
Path lookup from a kthread now fails by default. It makes it
deliberately hard to offload security sensitive operations into init's
filesystem state from a kthread.
Places that legitimately need to look something up there opt in
through the new scoped_with_init_fs() which temporarily overrides the
caller's fs_struct with init's. usermodehelpers remain the only kernel
tasks that genuinely share init's filesystem state, since they execute
random binaries in the root filesystem (excellent...).
The visible result is that /proc/2/root is a nullfs with an empty
mountinfo while /proc/1/root is the real root"
* tag 'vfs-7.3-rc1.kthread' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs: (26 commits)
initramfs_test: use test init/exit hooks to override init fs
fs: stop rewriting paths for PF_EXITING | PF_DUMPCORE
fs: stop rewriting kthread fs structs
fs: start all kthreads in nullfs
nullfs: make nullfs multi-instance
devtmpfs: create private mount namespace
fs: add umh argument to struct kernel_clone_args
fs: stop sharing fs_struct between init_task and pid 1
af_unix: use scoped_with_init_fs() for coredump socket lookup
initramfs: use scoped_with_init_fs() for rootfs unpacking
pnfs/blocklayout: use scoped_with_init_fs() for SCSI device lookup
ksmbd: use scoped_with_init_fs() for VFS path operations
ksmbd: use scoped_with_init_fs() for filesystem info path lookup
ksmbd: use scoped_with_init_fs() for share path resolution
fs: use scoped_with_init_fs() for kernel_read_file_from_path_initns()
coredump: use scoped_with_init_fs() for coredump path resolution
btrfs: use scoped_with_init_fs() for update_dev_time()
scsi: target: use scoped_with_init_fs() for APTPL metadata
scsi: target: use scoped_with_init_fs() for ALUA metadata
crypto: ccp: use scoped_with_init_fs() for SEV file access
...
|
|
See the procedure below:
smb2_sess_setup
ksmbd_smb2_session_create
__session_create
hash_add(sessions_table, &sess->hlist, sess->id)
ksmbd_counter_inc(KSMBD_COUNTER_SESSIONS)
ksmbd_conn_handler_loop
ksmbd_server_terminate_conn
ksmbd_sessions_deregister
hash_del(&sess->hlist)
// do not decrement KSMBD_COUNTER_SESSIONS
KSMBD_COUNTER_SESSIONS tracks sessions published in sessions_table, but
session removal does not decrement it. The value therefore keeps growing
after sessions are expired, rejected during registration, or removed on
the last channel disconnect.
Fixes: b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
Signed-off-by: Ze Tan <tanze@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
KSMBD_COUNTER_SESSIONS tracks sessions published in sessions_table.
Increment it while holding sessions_table_lock so publishing a session and
updating the counter happen together.
Fixes: b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
Signed-off-by: Ze Tan <tanze@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
See the procedure below:
smb2_sess_setup
ksmbd_smb2_session_create
__session_create
atomic_set(&sess->refcnt, 2)
hash_add(sessions_table, &sess->hlist, sess->id)
ksmbd_session_register
xa_store(&conn->sessions, sess->id, sess) // fail
ksmbd_user_session_put
atomic_dec(&sess->refcnt) // refcnt is 1, session is not freed
Remove the session from sessions_table and drop its table reference if
xa_store() fails.
Fixes: f5c779b7ddbd ("ksmbd: fix racy issue from session setup and logoff")
Signed-off-by: Ze Tan <tanze@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Print a warning if the sessions procfs entry cannot be created.
Signed-off-by: Ze Tan <tanze@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
smb_check_perm_dacl() validates that the DACL fits inside the NT
security descriptor, but then bounds its two ACE walks by the
remaining NTSD length (acl_size) rather than the DACL's declared
size (pdacl_size).
When pdacl->size is smaller than the trailing NTSD buffer, bytes
after the declared DACL boundary - still inside the stored security
descriptor - are parsed as ACEs during access checks. A crafted
DACL can place an access-granting ACE beyond pdacl->size, and the
current code accepts it during SMB2_CREATE access validation, while
parse_dacl() and smb_inherit_dacl() stop at pdacl_size.
Bound both ACE walks by pdacl_size to match the DACL boundary
semantics used elsewhere in the server.
Validation:
- semantic KUnit harness shows the post-boundary ACE is selected
before the fix and rejected (EACCES) after it
- linux master (7.2-rc6), x86_64
Fixes: 8f0541186e9a ("ksmbd: fix heap-based overflow in set_ntacl_dacl()")
Signed-off-by: Hang Nan <2122295973@qq.com>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
The temporary RDMA encryption diagnostics logged every SMB3 request
and successful payload operation with pr_err(), which made normal
traffic too noisy.
Keep only negotiation, RDMA READ preparation, RDMA WRITE transform
metadata, crypto completion, and final transfer completion messages as
KSMBD_DEBUG_RDMA diagnostics. Keep error reports for malformed metadata,
crypto, RDMA transfer, and file write failures at error level.
This preserves the diagnostics needed to verify RDMA transform
operation without flooding the kernel error log during normal I/O.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Port SMB Direct RDMA payload encryption support to the current ksmbd tree.
The current tree already supports all-state lookup for encrypted expired
sessions, so the overlapping lookup hunk from the original patch is
intentionally omitted.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
SMB3 permits a message to be compressed before it is encrypted. After
decrypting such a request, ksmbd must trim the AEAD tag using
OriginalMessageSize, decompress the nested compression transform, and
validate the resulting SMB2 PDU.
Share the decompression helper between the connection receive path and
the post-decryption work path so unencrypted and encrypted compressed
requests follow the same validation.
Fixes: a08de24c2b85 ("ksmbd: negotiate and decode SMB2 compression")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Previous-session replacement marks the old session expired but retains its
SMB3 encryption key. An in-flight encrypted request can still arrive on
that connection. Rejecting the expired session before decryption made ksmbd
treat the request as a key failure and abort the transport, causing
reconnect failures.
Allow key lookup for expired sessions that have encryption enabled. Keep
the session reference during validation so the normal
STATUS_USER_SESSION_DELETED response is encrypted with the old key. The
session remains expired and no command is executed.
Fixes: fa9415d4024f ("ksmbd: mark SMB2_SESSION_EXPIRED to session when destroying previous session")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
MS-SMB2 requires the server to disconnect a connection when an
encrypted transform cannot be associated with a session or fails
authenticated decryption. This includes an encrypted request that
still carries a SessionId invalidated through PreviousSessionId.
Move the connection to EXITING and shut down its transport when
decrypt_req() fails. Add the missing TCP shutdown callback so a receive
blocked in kernel_recvmsg() is released; SMB Direct already provides
the corresponding callback.
Plaintext requests using an invalidated SessionId do not take this
path and continue to receive STATUS_USER_SESSION_DELETED.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
The normal response path applies an SMB3 transform when the request was
encrypted. Async interim responses, completed compound prefixes and two
CHANGE_NOTIFY cleanup paths write their synthetic response work directly,
bypassing that encryption step.
A packet capture shows FE SMB2 STATUS_PENDING, CREATE and CHANGE_NOTIFY
responses following FD SMB3 requests. The client resets the connection
immediately after receiving those plaintext responses.
Send synthetic interim work through a common helper that applies the
session encryption transform first. A compound prefix shares the original
work's response iov, which encryption would replace in place, so flatten it
into an independently owned work before encrypting and sending it.
Fixes: 64bfa9d49026 ("smb/server: use MSG_EOR for async interim response")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
ksmbd_all_conn_set_status() treats every connection whose transient
binding flag is set as belonging to the target SessionId. A logoff or
session replacement can consequently move an unrelated connection to
NEED_RECONNECT or NEED_SETUP.
Pass the target session itself and select connections using either the
connection-local session xarray or the session's permanent channel list.
Use the same association test while waiting for requests to drain.
Serialize session-wide status changes under request_lock and do not
overwrite EXITING or RELEASING. Protect the shutdown transition with the
same lock so a concurrent session update cannot revive a closing
connection.
Fixes: f5a544e3bab7 ("ksmbd: add support for SMB3 multichannel")
Fixes: abcc506a9a71 ("ksmbd: fix racy issue from smb2 close and logoff with multichannel")
Fixes: c444139cb747 ("ksmbd: rewrite stop_sessions() with restartable iteration")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
An SMB3 multichannel binding registers the secondary connection in the
session channel list, but does not insert the session into the secondary
connection's session xarray.
The decryption path only searches the connection-local xarray. As a
result, every encrypted request received on a bound channel fails with
"Could not get decryption key".
Use the channel-aware session lookup for decryption. Also stop using the
temporary conn->binding flag to decide whether the global lookup is
allowed. Validate the permanent channel association under chann_lock
instead.
Fixes: f5a544e3bab7 ("ksmbd: add support for SMB3 multichannel")
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Add a share flag for requiring SMB3 encryption on an individual share.
Advertise SMB2_SHAREFLAG_ENCRYPT_DATA in TREE_CONNECT responses and
reject both unencrypted TREE_CONNECT attempts and plaintext requests for
shares carrying the flag.
Keep BIT(19) reserved for the existing ksmbd-tools WIDE_LINKS flag and
use BIT(20) for the new netlink ABI flag.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
BVT_DirectoryLeasing_ReadWriteHandleCaching requires a parent directory
lease break notification when another client creates a child in the
leased directory. A child CREATE without a lease context did not notify
the parent lease holders because the notification path expected a
non-NULL lease context.
Allow the parent lease notification helper to handle a NULL child lease
context and notify matching parent leases. Invoke it after a child is
created without a lease context while preserving the existing lease-key
filtering for requests that provide one.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
BVT_AppInstanceVersion_SMB311_GreaterVersion,
BVT_AppInstanceVersion_SMB311_SameVersion,
BVT_AppInstanceVersion_SMB311_LowerAppInstanceVersionHigh, and
BVT_AppInstanceVersion_SMB311_LowerAppInstanceVersionLow exercise
ordered opens using the same AppInstanceId. ksmbd tracked the
AppInstanceId, but did not parse the version context or enforce the
version ordering, so versioned opens returned incorrect sharing
violations.
Parse and retain the 24-byte AppInstanceVersion context with each open.
Reject a version that is lower than or equal to the active version with
STATUS_FILE_FORCED_CLOSED, reject an unversioned open against a versioned
handle, and close the previous handle for a newer takeover. Do not apply
the takeover check to durable reconnect or replay requests.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
BVT_DurableHandleV1_Reconnect_WithBatchOplock,
BVT_DurableHandleV1_Reconnect_WithLeaseV1,
BVT_DurableHandleV2_Reconnect_WithBatchOplock, and
BVT_DurableHandleV2_Reconnect_WithLeaseV1 fail to reconnect a durable
handle when the request leaves VolatileFileId unset.
A durable reconnect request may omit VolatileFileId by setting it to
zero. Treating zero as an ID makes ksmbd reject the request whenever the
saved volatile ID is nonzero.
Only compare the saved and requested volatile IDs when the request
contains a nonzero value. Explicit mismatches continue to be rejected.
This allows SMB2 durable handle V1 and V2 reconnects that identify the
handle through the persistent ID and reconnect context.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
See the procedure below:
smb2_tree_connect
ksmbd_tree_conn_connect
xa_store(&sess->tree_conns, tree_conn->id, tree_conn)
ksmbd_counter_inc(KSMBD_COUNTER_TREE_CONNS)
ksmbd_share_tree_conn_inc(sc)
ksmbd_iov_pin_rsp // fail
status.ret = KSMBD_TREE_CONN_STATUS_NOMEM
// do not disconnect tree_conn
Disconnect the new tree connection if ksmbd_iov_pin_rsp() fails.
Fixes: e2b76ab8b5c9 ("ksmbd: add support for read compound")
Signed-off-by: Ze Tan <tanze@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
A cancelled SMB2 CHANGE_NOTIFY request is completed from system_wq. The
deferred work keeps a reference to the connection, but it is not included
in the connection's r_count. During connection teardown,
ksmbd_conn_transport_destroy() can therefore finish the connection handler
and destroy session proc entries before the deferred response runs.
Account for the deferred cancellation work in r_count. The connection
handler now waits for the deferred response to finish before it
deregisters sessions and removes their proc entries.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Reproducer (Link[1]):
1. Build kernel with CONFIG_KASAN=y
2. server: systemctl start ksmbd
3. client: mount -t cifs //localhost/export /mnt
4. client: umount /mnt
5. server: modprobe -r ksmbd
The error message is as follows:
==================================================================
BUG: KASAN: slab-use-after-free in proc_remove+0x3e/0x80
Read of size 8 at addr ffff88810654e098 by task modprobe/785
...
Call Trace:
<TASK>
__dump_stack+0x19/0x30
dump_stack_lvl+0x49/0x60
print_address_description+0x7b/0x200
print_report+0x5b/0x70
kasan_report+0xed/0x130
__asan_report_load8_noabort+0x18/0x20
proc_remove+0x3e/0x80
ksmbd_conn_transport_destroy+0x2b/0x320 [ksmbd]
cleanup_module+0x33/0xe00 [ksmbd]
__se_sys_delete_module+0x276/0x400
__x64_sys_delete_module+0x5f/0x70
x64_sys_call+0x2675/0x3030
do_syscall_64+0xf0/0x3b0
entry_SYSCALL_64_after_hwframe+0x76/0x7e
RIP: 0033:0x7f5b56d2b02b
...
</TASK>
Allocated by task 159:
kasan_save_track+0x2f/0x70
kasan_save_alloc_info+0x40/0x50
__kasan_slab_alloc+0x52/0x70
kmem_cache_alloc_noprof+0x168/0x3e0
__proc_create+0x20b/0x710
proc_create_single_data+0x78/0x150
ksmbd_proc_create+0x24/0x30 [ksmbd]
ksmbd_conn_transport_init+0x4f/0x80 [ksmbd]
server_ctrl_handle_work+0x64/0x2c0 [ksmbd]
process_scheduled_works+0x788/0xec0
worker_thread+0x894/0xc10
kthread+0x2e5/0x3c0
ret_from_fork+0x168/0x4f0
ret_from_fork_asm+0x1a/0x30
Freed by task 785:
kasan_save_track+0x2f/0x70
kasan_save_free_info+0x4a/0x60
__kasan_slab_free+0x47/0x70
kmem_cache_free+0x122/0x410
pde_put+0xfd/0x160
remove_proc_subtree+0x365/0x540
proc_remove+0x6a/0x80
ksmbd_proc_cleanup+0x1f/0x60 [ksmbd]
cleanup_module+0x18/0xe00 [ksmbd]
__se_sys_delete_module+0x276/0x400
__x64_sys_delete_module+0x5f/0x70
x64_sys_call+0x2675/0x3030
do_syscall_64+0xf0/0x3b0
entry_SYSCALL_64_after_hwframe+0x76/0x7e
==================================================================
Reported-by: Kyenghwan Hwang <obnred@gmail.com>
Link[1]: https://lore.kernel.org/linux-cifs/8ea028f5-90f4-4d21-b1ac-a343f0f04d88@chenxiaosong.com/
Signed-off-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
A file_lock retained by ksmbd for byte-range lock bookkeeping can still
be part of the VFS blocked-request graph. In particular, the VFS can
chain a new waiter below an already blocked request through
flc_blocked_requests. The ksmbd_file reference count does not cover that
graph.
Both __ksmbd_close_fd() and the cross-request unlock path free these
retained file_lock objects directly. If a dependent waiter is still
attached, locks_release_private() hits
BUG_ON(!list_empty(&flc->flc_blocked_requests)). The same lifetime
mismatch can leave a freed ksmbd_lock reachable through its request-local
llist.
Detach the file_lock from the blocked-request graph before freeing it in
the close, cross-request unlock, and rollback paths. locks_delete_block()
also wakes requests chained below the object. Remove llist when a
completed lock is published so a globally visible ksmbd_lock no longer
points into the submitting worker's stack.
Fixes: d63528eb0d43 ("ksmbd: free ksmbd_lock when file is closed")
Reported-by: Kyenghwan Hwang <obnred@gmail.com>
Tested-by: Kyenghwan Hwang <obnred@gmail.com>
Tested-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
struct preauth_session contains the Preauth_HashValue[] array that
might contain sensitive data. Use kfree_sensitive() to clear it
before returning the memory to the heap.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
struct ksmbd_conn contains an embedded struct ntlmssp_auth with the
ciphertext[] and cryptkey[] arrays, so to avoid leaking this information
via the heap, it should be freed with kfree_sensitive().
While we're at it, also use kfree_sensitive() for freeing preauth_info
in ksmbd_conn_free() to avoid that the Preauth_HashValue[] could leak
via the heap here, too.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
struct ksmbd_session contains some arrays with sensitive information, like
sess_key, smb3encryptionkey, smb3decryptionkey and smb3signingkey. Thus
let's make sure that this information cannot leak via the heap and use
kfree_sensitive() to free it.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Use kfree_sensitive() to free the user->passkey (and the struct
ksmbd_login_response in ksmbd_login_user() that contains the same
information) to avoid that this information could leak somewhere
else via the heap.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Sensitive data like keys that are stored in stack-local arrays could be
leaked via the stack to the calling functions, or via the heap when using
only normal kfree() functions. There is no known vulnaribility for this
right now, but it's good security style to explicitly zeroize this
sensitive matieral as soon as possible to avoid that it could be exploited
together with other bugs later.
In calc_ntlmv2_hash(), the struct hmac_md5_ctx is normally cleared during
hmac_md5_final() already, but in case of errors, this function is skipped
and ctx is never zeroized, so add a memzero_explicit(&ctx, sizeof(ctx))
there to fix the problem.
In ksmbd_krb5_authenticate(), the ksmbd_spnego_authen_response contains
the session key in the payload. It's currently freed with plain kvfree().
Let's better use kvfree_sensitive() instead.
In generate_key(), the prfhash[] array is used to calculate the key,
but it's never cleared, so it leaks on the stack. Thus clear this with
a memzero_explicit(), too.
In ksmbd_crypt_message(), the sign[] and key[] arrays are leaked via
the stack, too. Make sure to clear them via memzero_explicit() at the
end.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
In krb5_authenticate(), out_len is calculated to determine available
headroom in response_buf for the incoming Kerberos AP-REP token. However,
when SMB2_SESSION_SETUP is processed as a non-first element of a compounded
SMB2 request, the calculation omits work->next_smb2_rsp_hdr_off.
This causes out_len to overstate remaining buffer headroom by
the cumulative size of prior responses in the compound chain. Consequently,
the length check in ksmbd_krb5_authenticate()
(*out_len <= resp->spnego_blob_len) passes erroneously, allowing memcpy()
to write the AP-REP blob past the end of response_buf into adjacent kernel
heap memory.
Fix this by subtracting work->next_smb2_rsp_hdr_off when computing out_len,
ensuring it accurately reflects physical remaining buffer space.
Signed-off-by: Ilan Dudnik <ilan.dudnik@safebreach.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|
|
Reproducer:
1. server: systemctl start ksmbd
2. client: mount without `posix` option
mount -t cifs //${server_ip}/export /mnt
3. client: touch /mnt/file1 /mnt/file2
4. client: C program: int fd = open("/mnt/file2", O_RDONLY);
5. client: C program: rename("/mnt/file1", "/mnt/file2");
6. client: C program: struct stat stbuf; fstat(fd, &stbuf);
stbuf.st_nlink is 1, should be 0
This patch fixes xfstests generic/035 when mounted without `posix` option.
Suggested-by: Namjae Jeon <linkinjeon@kernel.org>
Signed-off-by: ChenXiaoSong <chenxiaosong@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
|