Skip to contentSkip to conversation

ksmbd: decode and encode security descriptors in one place

PATCH Applied Ian Bridges 2 participants 4 messages Nov 25

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v2 cover ksmbd: decode and encode security descriptors in one place

ksmbd reads and writes NT security descriptors (SDs) in five places:
QUERY_INFO, CREATE, inheritance, SET_INFO, and the access check. Each walks the raw bytes with its own bounds checks, and those walks in smbacl.c have needed a long run of fixes. This series replaces them with one decoder and one encoder, so the bounds are checked in one place and the callers handle no SD bytes.

Patch 1 adds the decoder and the encoder with their KUnit suite, and nothing calls them yet. ksmbd_sd_decode() validates a whole self-relative SD and returns a struct ksmbd_sd in a single allocation. The struct is plain data that the callers read directly, and every pointer in it points at bytes the decoder has checked. ksmbd_sd_encode() checks a struct that a caller filled in and writes the SD to a buffer it allocates.

Patch 2 is the cutover of the existing code to the new codec. The functions in smbacl.c keep their names and their logic, and only the code that read or wrote the bytes of an SD is replaced. The decisions the callers make are meant to stay as they are. A decision changes only where the decoder reads an SD differently from the walk it replaces, or refuses one the walk accepted. Other changes to those decisions are left for later patches.

The earlier proposal [1] left the access check, smb_check_perm_dacl(), as it is. This series converts it with the others, because the loader of the stored SD now returns a decoded SD.

Changes since the RFC
=====================

v1 was an RFC [2]. Thanks to Namjae for the review of it. The second and third changes follow his answers.

- Rebased onto ksmbd-for-next b0bd2fe7715f. Patch 2 stopped applying when commit 3cfe35e0d26c ("smb/server: fix little-endian values in diagnostic messages") changed a debug line in parse_sec_desc() that the patch removes.
- A malformed owner or group SID no longer makes a stored SD malformed. The decoder leaves that SID out, as it does a malformed SACL, and ksmbd uses the DACL. An SD from a client with such a SID is still refused. The flag sacl_dropped is now part_dropped.
- CREATE succeeds when the SD built for the new file is too large to store. The file then has no stored SD.
- The codec and its tests stay in one patch.

Changes in behavior
===================

The message of patch 2 lists the changes, and the rules the decoder enforces are the sd_malformed() calls in patch 1, each reached by a KUnit case. The changes below are the ones I would like feedback on.

A malformed SD from a client is refused whole. A stored SD is refused whole if its header or its DACL is malformed, and a malformed owner SID, group SID, or SACL is left out of it. The walks have no common notion of a malformed SD. Some malformed SDs are refused by no walk today. Some are refused on one path and read on another. Some are cut short at the bad ACE, and the ACEs before it are still used. The decoder refuses an SD that breaks a structural rule of MS-DTYP. Most of the rules are bounds. The rules below go further. Each item says what the series refuses and what the walks do with it today.

1. The decoder refuses an ACL if it cannot read all AceCount ACEs within AclSize. Today SET_INFO and inheritance refuse a count above (AclSize - 8) / 18, and otherwise each walk uses the ACEs it can read. Using the ACEs that fit would enforce a part of an ACL.
2. The decoder accepts Revision 1 for an SD and for a SID, and AclRevision 2 or 4 for an ACL. It refuses any other value. Today no walk refuses another value, and the SD is stored and used. The revision says which layout follows.
3. MS-DTYP 2.4.4.1 requires AceSize to be a multiple of 4, and the decoder refuses an AceSize that is not. Today no walk checks it, and each steps by AceSize to the next ACE.
4. The decoder refuses an ACE type that MS-DTYP gives no layout. These are 0x03, 0x04, 0x08, 0x0E, 0x10, and anything above 0x13. Today every ACE is read as a plain ACE with its SID at byte 8, so an ACE of these types is stored, returned, and inherited. Without a layout the decoder cannot say where the SID is. This is stricter than MS-DTYP 2.4.5, which lists 0x03 and 0x08 among the types an ACL can hold.
5. In an object ACE, two bits of the Flags say which GUIDs come before the SID. The decoder refuses any other bit. Today the walks read the Flags as the start of the SID, and SET_INFO stores the ACE if those bytes pass for a SID.
6. The decoder refuses a nonzero OffsetDacl in a stored SD without DACL_PRESENT. Today QUERY_INFO, inheritance, and the access check use the DACL at that offset. SET_INFO already refuses this from a client. The two fields disagree about whether the SD has a DACL.

Not everything that MS-DTYP forbids is refused, for example a SACL ACE type in a DACL. Two things are let through for a reason. An SD without SELF_RELATIVE is read as self-relative, since ksmbd has stored SDs with the bit clear. A malformed owner SID, group SID, or SACL in a stored SD is left out so that the DACL remains usable. An SD from a client with any of the three malformed makes SET_INFO or the CREATE context fail.

A refused SD is handled as follows.

7. From a client, in SET_INFO or a CREATE context, parse_sec_desc() returns -EINVAL, as it does for the SDs it refuses today. Nothing is mapped and nothing is stored. The file that a CREATE made stays, as it does today when the SD is refused.
8. QUERY_INFO of a malformed stored SD fails with STATUS_INVALID_SECURITY_DESCR. Today the reply holds the ACEs ahead of the malformed one, or a NULL DACL if the header of the DACL is malformed. An open that runs the access check is denied first (change 9). So this is what a handle that was open already gets, or one opened with FILE_DELETE_ON_CLOSE, for which smb2_open() does not call smb_check_perm_dacl().
9. The access check denies every request against a malformed stored SD. Today it decides on the ACEs ahead of the malformed one, and it makes no check if the header of the DACL is malformed. A DACL that cannot be read whole cannot be enforced, and the part that was not read may hold its deny ACEs. The same check hides such a file from a directory listing on a share with hide unreadable set. The cost is that such a file cannot be repaired through an open that runs the check, since WRITE_DAC is denied as well. A handle that already has WRITE_DAC can still set a new SD.
10. Inheritance does not inherit from a parent whose stored SD is malformed. The new file gets the SD built from its inode, as when the parent has none. Today that happens for some of these SDs, and for others the file inherits the ACEs ahead of the malformed one. A parent whose stored SD has only a malformed owner or group SID is inherited from, and the stored SD of the new file is without that SID. Today inheritance refuses such a parent if the SID is out of bounds or has more than 15 sub-authorities.

A stored SD can be malformed because a client sent a malformed SD to a ksmbd that stored it unchecked, or because the SD inside the xattr was damaged. ksmbd has also written two kinds of malformed SD itself, both when a file inherited from its parent. I have found no others. In the first kind, the parent had an inheritable object ACE, and inheritance wrote that ACE without its GUIDs. The DACL of such an SD is malformed, so the access check denies.

In the second kind, the DACL is intact. Before commit 4616bbc5389a ("ksmbd: build an inherited security descriptor with its own offsets"), inheritance wrote the child's SD at the parent's offsets. If the parent stored its DACL before its owner and group, and the child's DACL came out larger than the parent's, the larger DACL overwrote the child's owner or group. In v1 the overwritten SID made the access check deny. In v2 the decoder leaves that SID out and the check uses the DACL.

One change is not about malformed SDs.

11. A DACL that would pass 65535 bytes fails with -E2BIG, and QUERY_INFO returns STATUS_INSUFFICIENT_RESOURCES. Today the POSIX ACL entries that do not fit are left out. build_sec_desc() fails with -ENOMEM if an allocation fails while the POSIX ACL entries are mapped. Today the rest of that POSIX ACL is left out. A DACL cut short reads as the whole DACL, to a client and to the access check. An inherited DACL that is too large is handled as it is today, and the new file gets the SD built from its inode. Inherited ACEs now keep their data, so a child DACL can pass the limit where it did not before.

A default ACL too large for a DACL takes about 1800 named users for a file and about 700 for a directory. CREATE under such a default ACL succeeds, and the new file or directory has no stored SD. The POSIX ACL it inherited is in place. In v1 the CREATE failed after it had made the file.

Tests
=====

Tested on ksmbd-for-next b0bd2fe7715f. Every test below was run again for v2.
- Each patch builds with W=1 and no warnings (GCC 14, x86_64 with KASAN), and sparse reports nothing in fs/smb/server. With both patches applied, fs/smb/server and its tests also build for 32-bit x86 with GCC 14 and clang 22, W=1 and no warnings.
- KUnit under UML passes at each patch with GCC 14 and with clang 22, which enforces __counted_by. With both patches that is ksmbd-smbacl 5 of 5 and ksmbd_secdesc 6 of 6, 38 cases with their parameters. Patch 2 adds the fifth ksmbd-smbacl case.
- The same KUnit suites pass under qemu on 32-bit x86 (GCC 14), on x86_64 with KMSAN (clang 22), on big-endian s390 (clang 22), and on 32-bit big-endian PowerPC (clang 22).
- checkpatch --strict reports nothing but the note about MAINTAINERS for the new files.
- smbtorture smb2.acls, smb2.setinfo, smb2.getinfo, smb2.create, smb2.sdread, smb2.maximum_allowed, smb2.winattr, smb2.delete-on-close-perms, smb2.dosmode, and smb2.rename give the same results before and after the series, on a KASAN kernel booted with kasan_multi_shot. The one exception is mkdir-dup in smb2.create, which is a race. It passed 19 of 60 runs on the base and 24 of 60 with the series. There is no KASAN report or warning, and the kernel stays untainted.
- Scripts that query, set, and inherit SDs of many shapes over SMB were run before and after the series. Every QUERY_INFO reply is the same but for an inherited callback ACE, which keeps its application data. One SET_INFO that was accepted is now refused. Its object ACE has an undefined bit in its Flags. The stored SDs differ in their bytes, since each is now the one the encoder writes.
- I damaged two stored SDs by hand. I raised the AceCount of the first by one and cut the second short inside its header. The base uses the first SD and treats the second as missing. With the series, an open that runs the access check is denied for either file, and ksmbd logs a warning. QUERY_INFO returns STATUS_INVALID_SECURITY_DESCR on a handle opened before the damage and on a handle opened with FILE_DELETE_ON_CLOSE. SET_INFO on the handle opened before the damage repairs the file.
- I changed the revision of the owner SID in the stored SD of a file and of a directory, and did the same with the group SID. Every open and every QUERY_INFO reply is the same as before the change, with the series and on the base. A file created in the directory inherits its DACL. With the series, the stored SD of that file is without the SID.
- On a tmpfs, under a directory whose default ACL names 1900 users, CREATE succeeds with the series. The new file has its POSIX ACL and no stored SD.
- With slab allocations under the decoder and the encoder made to fail one time in five (failslab), smb2.acls, smb2.create, smb2.setinfo, smb2.getinfo, and the scripts leave no KASAN report, no warning, and nothing for kmemleak.
- Out of tree, the converted functions of smbacl.c were run in userspace under ASan and UBSan against upstream's functions compiled verbatim. That was about 1.1 million comparisons over generated and hand-written SDs for the QUERY_INFO reply, SET_INFO, and inheritance. Every difference from upstream is one the series lists. The QUERY_INFO comparisons do not cover a stored SD that the decoder refuses. That refusal is in smb2pdu.c and no reply is built.

The 32-bit, KMSAN, and big-endian runs are of the KUnit suites only. A live server was tested on x86_64 alone.

The proposal mentioned CBMC proofs of the decoder and the encoder. They were run on an earlier revision of the codec and not since it changed, so the series makes no claim from them.

This series was developed with LLM assistance.

[1] https://lore.kernel.org/linux-cifs/[email protected]/
[2] https://lore.kernel.org/linux-cifs/[email protected]/

Ian Bridges (2):
ksmbd: add a security descriptor decoder and encoder
ksmbd: use the security descriptor codec in callers

 fs/smb/server/Makefile              |    2 +-
 fs/smb/server/secdesc.c             |  783 ++++++++++++++++++++
 fs/smb/server/secdesc.h             |   66 ++
 fs/smb/server/smb2pdu.c             |   96 ++-
 fs/smb/server/smbacl.c              | 1021 ++++++++-------------------
 fs/smb/server/smbacl.h              |   11 +-
 fs/smb/server/tests/Makefile        |    3 +
 fs/smb/server/tests/secdesc_kunit.c |  899 +++++++++++++++++++++++
 fs/smb/server/tests/smbacl_kunit.c  |   42 ++
 fs/smb/server/vfs.c                 |   50 +-
 fs/smb/server/vfs.h                 |   10 +-
 11 files changed, 2154 insertions(+), 829 deletions(-)
 create mode 100644 fs/smb/server/secdesc.c
 create mode 100644 fs/smb/server/secdesc.h
 create mode 100644 fs/smb/server/tests/secdesc_kunit.c

base-commit: b0bd2fe7715f01d1796fca4bf7d22f7bbbe392ec

Signature · 1 line
2.47.3
#1 lore raw

PATCH v2 1/2 ksmbd: add a security descriptor decoder and encoder

ksmbd currently reads and writes security descriptors (SDs) by walking the wire format. Each walk repeats the bounds checks for the offsets, the ACL sizes, the ACE sizes, and the SID lengths.

Add one decoder and one encoder for the self-relative SD defined in MS-DTYP 2.4.6, with struct ksmbd_sd between them. ksmbd_sd_decode() validates a whole SD and returns it as a single allocation. The owner, the group, and the SID of each ACE are pointers to bytes it has checked. ksmbd_sd_encode() checks the struct a caller filled in, works out the size, and writes the SD to a buffer it allocates.

The decoder returns -EBADMSG for an SD whose header or DACL breaks a structural rule of MS-DTYP. It keeps what it does not interpret. An ACE of any type that MS-DTYP gives a structure is kept with its object GUIDs and its application data. The SACL is kept as bytes. Every Control bit is kept except SELF_RELATIVE, DACL_PRESENT, and SACL_PRESENT, which the encoder sets from the SD it writes.

A malformed owner SID, group SID, or SACL does not fail the decode. The decoder leaves that part out and sets part_dropped, and the caller decides whether to use the rest of the SD.

Nothing calls the two functions yet. The KUnit suite has cases for what the decoder accepts and refuses and for what the encoder refuses.

---
 fs/smb/server/Makefile              |   2 +-
 fs/smb/server/secdesc.c             | 783 ++++++++++++++++++++++++
 fs/smb/server/secdesc.h             |  66 ++
 fs/smb/server/tests/Makefile        |   3 +
 fs/smb/server/tests/secdesc_kunit.c | 899 ++++++++++++++++++++++++++++
 5 files changed, 1752 insertions(+), 1 deletion(-)
 create mode 100644 fs/smb/server/secdesc.c
 create mode 100644 fs/smb/server/secdesc.h
 create mode 100644 fs/smb/server/tests/secdesc_kunit.c
fs/smb/server/Makefile +1 -1
index 9bc87695a53c..a1b988212a0a 100644
@@ -8,7 +8,7 @@ ksmbd-y :=	unicode.o auth.o vfs.o vfs_cache.o server.o ndr.o \
 		misc.o oplock.o connection.o ksmbd_work.o crypto_ctx.o \
 		mgmt/ksmbd_ida.o mgmt/user_config.o mgmt/share_config.o \
 		mgmt/tree_connect.o mgmt/user_session.o smb_common.o \
-		transport_tcp.o transport_ipc.o smbacl.o smb2pdu.o \
+		transport_tcp.o transport_ipc.o smbacl.o secdesc.o smb2pdu.o \
 		smb2ops.o smb2misc.o ksmbd_spnego_negtokeninit.asn1.o \
 		ksmbd_spnego_negtokentarg.asn1.o asn1.o compress.o
 
fs/smb/server/secdesc.c new file +783 -0

783 lines not on this page · raw message

fs/smb/server/secdesc.h new file +66 -0

66 lines not on this page · raw message

fs/smb/server/tests/Makefile +3 -0
index 8738ab0b0667..753b09cde4a7 100644
@@ -2,3 +2,6 @@
 # Copyright (C) 2026 Hang Nan <[email protected]>
 
 obj-$(CONFIG_SMB_SERVER_KUNIT_TESTS) += smbacl_kunit.o
+
+ksmbd_secdesc_kunit-y := secdesc_kunit.o
+obj-$(CONFIG_SMB_SERVER_KUNIT_TESTS) += ksmbd_secdesc_kunit.o
fs/smb/server/tests/secdesc_kunit.c new file +899 -0

899 lines not on this page · raw message

Signature · 1 line
2.47.3
#2 lore raw

PATCH v2 2/2 ksmbd: use the security descriptor codec in callers

In reply to Ian Bridges

Replace each walk of a raw security descriptor (SD) with ksmbd_sd_decode() and each place that writes one with ksmbd_sd_encode(). The functions keep their names and their logic. Only the code that read or wrote the bytes of an SD changes.

ksmbd_vfs_get_sd_xattr() decodes the stored SD and returns a struct ksmbd_sd, so the access check, inheritance, and QUERY_INFO no longer check offsets and sizes themselves. parse_sec_desc() decodes the SD a client sent, and set_info_sec() encodes what it stores. build_sec_desc() and smb_inherit_dacl() fill in a struct ksmbd_sd and encode it. build_sec_desc() allocates its reply, which removes smb_acl_sec_desc_scratch_len() and the size arithmetic in its callers. dacl_add_ace_size(), parse_sid(), smb_set_ace(), and smb_validate_ntsd_sid() are removed with the walks they served.

The changes in behavior follow.

A malformed SD is refused whole, and the decoder refuses more than the walks did. For example, it refuses a DACL whose AceCount is larger than the ACEs it holds.

- parse_sec_desc() returns -EINVAL for a malformed SD from a client, even if only the owner, the group, or the SACL is malformed. It now checks the owner and the group when DACL_PRESENT is clear. Before, it checked only OffsetDacl in that case.
- A stored SD is malformed if its header or its DACL is. The loader returns -EBADMSG for it and logs a rate-limited warning. QUERY_INFO returns STATUS_INVALID_SECURITY_DESCR. The access check denies the request. Inheritance falls back to the SD built from the child's inode.
- A stored SD with a malformed owner SID, group SID, or SACL is used without that part. A file that inherits from such a parent gets a stored SD without that SID. Before, inheritance refused a parent whose owner or group SID was out of bounds or had more than 15 sub-authorities.
- A stored SD shorter than its header is malformed too. Before, it counted as no stored SD.

The other changes follow.

- The SID of an object ACE is read after its GUIDs. Before, its Flags were read as the SID. parse_dacl() still refuses a DACL with an object ACE, and QUERY_INFO still leaves the ACE out. The access check now skips an object ACE. It still records an object ACE that denies, unless the ACE is inherit-only.
- Inheritance copies an ACE whole. Before, a callback ACE lost its data and an object ACE lost its GUIDs.
- Inheritance accepts a parent DACL of 16-byte ACEs. Before, it refused an AceCount above (AclSize - 8) / 18.
- A DACL that holds an object ACE is written with revision 4.
- A DACL over 65535 bytes fails with -E2BIG. Before, the POSIX ACL entries that did not fit were left out. QUERY_INFO of a file with such a DACL returns STATUS_INSUFFICIENT_RESOURCES. A CREATE whose new file would get such a DACL succeeds, and the file has no stored SD.
- build_sec_desc() fails with -ENOMEM if it cannot allocate the SIDs of the POSIX ACL entries. Before, the remaining entries were left out.
- Every stored SD is the one the encoder writes, with SELF_RELATIVE set. Before, SET_INFO stored the buffer the client sent. The format of the xattr does not change.
- A refused SD from a client is logged with ksmbd_debug(). The pr_err() lines of the walks are gone.

The fixture in smbacl_kunit.c counts two ACEs in its DACL, and only one fits inside AclSize. That SD is now refused whole, so the case for maximal access expects a denial, as the other case already did. A new case sets AceCount to one and checks that maximal access includes read and excludes write.

---
 fs/smb/server/smb2pdu.c            |   96 ++-
 fs/smb/server/smbacl.c             | 1021 ++++++++--------------------
 fs/smb/server/smbacl.h             |   11 +-
 fs/smb/server/tests/smbacl_kunit.c |   42 ++
 fs/smb/server/vfs.c                |   50 +-
 fs/smb/server/vfs.h                |   10 +-
 6 files changed, 402 insertions(+), 828 deletions(-)
fs/smb/server/smb2pdu.c +40 -56
index 82afd32a0246..1bd5eaff6215 100644
@@ -5245,47 +5245,30 @@ int smb2_open(struct ksmbd_work *work)
 					struct smb_fattr fattr;
 					struct smb_ntsd *pntsd;
 					int pntsd_size;
-					size_t scratch_len;
 
 					rc = ksmbd_acls_fattr(&fattr, idmap, inode);
 					if (rc)
 						goto err_out;
 
-					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
-							NULL, 0,
-							OWNER_SECINFO | GROUP_SECINFO |
-							DACL_SECINFO);
-					if (!scratch_len || scratch_len == SIZE_MAX) {
-						rc = -EFBIG;
-						posix_acl_release(fattr.cf_acls);
-						posix_acl_release(fattr.cf_dacls);
-						goto err_out;
-					}
-
-					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
-					if (!pntsd) {
-						rc = -ENOMEM;
-						posix_acl_release(fattr.cf_acls);
-						posix_acl_release(fattr.cf_dacls);
-						goto err_out;
-					}
-
 					rc = build_sec_desc(idmap,
-							    pntsd, NULL, 0,
+							    &pntsd, NULL,
 							    OWNER_SECINFO |
 							    GROUP_SECINFO |
 							    DACL_SECINFO,
 							    &pntsd_size, &fattr);
 					posix_acl_release(fattr.cf_acls);
 					posix_acl_release(fattr.cf_dacls);
-					if (rc) {
-						kvfree(pntsd);
-						goto err_out;
-					}
-
-					ksmbd_vfs_set_sd_xattr(conn, idmap, &path,
-							       pntsd, pntsd_size);
+					/*
+					 * A DACL too large for an SD is not
+					 * stored. The file keeps the POSIX
+					 * ACL it inherited.
+					 */
+					if (!rc)
+						ksmbd_vfs_set_sd_xattr(conn, idmap, &path,
+								       pntsd, pntsd_size);
 					kvfree(pntsd);
+					if (rc && rc != -E2BIG)
+						goto err_out;
 				}
 			}
 		}
@@ -8437,14 +8420,14 @@ static int smb2_get_info_sec(struct ksmbd_work *work,
 {
 	struct ksmbd_file *fp;
 	const struct mnt_idmap *idmap;
-	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
+	struct smb_ntsd *pntsd = NULL;
+	struct ksmbd_sd *ppntsd = NULL;
 	struct smb_fattr fattr = {{0}};
 	struct inode *inode;
 	__u32 secdesclen = 0;
 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
 	int addition_info = le32_to_cpu(req->AdditionalInformation);
-	int rc = 0, ppntsd_size = 0, max_len;
-	size_t scratch_len = 0;
+	int rc = 0, max_len;
 
 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
 			      PROTECTED_DACL_SECINFO |
@@ -8496,11 +8479,13 @@ static int smb2_get_info_sec(struct ksmbd_work *work,
 
 	if (test_share_config_flag(work->tcon->share_conf,
 				   KSMBD_SHARE_FLAG_ACL_XATTR)) {
-		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
-						     fp->filp->f_path.dentry,
-						     &ppntsd);
-		if (ppntsd_size < 0 && !smb_no_stored_sd(ppntsd_size)) {
-			rc = ppntsd_size == -ENOMEM ? -ENOMEM : -EIO;
+		rc = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
+					    fp->filp->f_path.dentry, &ppntsd);
+		if (rc && !smb_no_stored_sd(rc)) {
+			if (rc == -EBADMSG)
+				rsp->hdr.Status = STATUS_INVALID_SECURITY_DESCR;
+			else if (rc != -ENOMEM)
+				rc = -EIO;
 			goto release_acl;
 		}
 	}
@@ -8514,32 +8499,18 @@ static int smb2_get_info_sec(struct ksmbd_work *work,
 		goto release_acl;
 	}
 
-	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
-			ppntsd_size, addition_info);
-	if (!scratch_len || scratch_len > SIZE_MAX - 7) {
-		rc = -EFBIG;
-		goto release_acl;
-	}
-
-	/* A compound response pads the descriptor to 8 bytes in this buffer */
-	scratch_len = ALIGN(scratch_len, 8);
-	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
-	if (!pntsd) {
-		rc = -ENOMEM;
-		goto release_acl;
-	}
-
-	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
-			addition_info, &secdesclen, &fattr);
+	rc = build_sec_desc(idmap, &pntsd, ppntsd, addition_info, &secdesclen,
+			    &fattr);
+	/* The DACL is too large for an SD */
+	if (rc == -E2BIG)
+		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
 
 release_acl:
 	posix_acl_release(fattr.cf_acls);
 	posix_acl_release(fattr.cf_dacls);
-	kfree(ppntsd);
+	kvfree(ppntsd);
 	ksmbd_fd_put(work, fp);
 
-	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
-		rc = -EFBIG;
 	if (rc)
 		goto err_out;
 
@@ -8550,6 +8521,19 @@ static int smb2_get_info_sec(struct ksmbd_work *work,
 	if (rc)
 		goto err_out;
 
+	/* A compound response pads the descriptor to 8 bytes in this buffer */
+	if (!IS_ALIGNED(secdesclen, 8)) {
+		void *padded = kvrealloc(pntsd, ALIGN(secdesclen, 8),
+					 KSMBD_DEFAULT_GFP);
+
+		if (!padded) {
+			rc = -ENOMEM;
+			goto err_out;
+		}
+		memset(padded + secdesclen, 0, ALIGN(secdesclen, 8) - secdesclen);
+		pntsd = padded;
+	}
+
 	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
 			offsetof(struct smb2_query_info_rsp, Buffer),
 			pntsd, secdesclen);
fs/smb/server/smbacl.c +282 -739

1,489 lines not on this page · raw message

fs/smb/server/smbacl.h +5 -6
index b51a8c6c1d4e..b14bbae6ab48 100644
@@ -38,6 +38,7 @@
 #define SELF_RELATIVE		0x8000
 
 struct ksmbd_conn;
+struct ksmbd_sd;
 
 struct smb_fattr {
 	kuid_t	cf_uid;
@@ -83,9 +84,9 @@ struct posix_acl_state {
 };
 
 int parse_sec_desc(const struct mnt_idmap *idmap, struct smb_ntsd *pntsd,
-		   int acl_len, struct smb_fattr *fattr);
-int build_sec_desc(const struct mnt_idmap *idmap, struct smb_ntsd *pntsd,
-		   struct smb_ntsd *ppntsd, int ppntsd_size, int addition_info,
+		   int acl_len, struct smb_fattr *fattr, struct ksmbd_sd **psd);
+int build_sec_desc(const struct mnt_idmap *idmap, struct smb_ntsd **pntsd,
+		   const struct ksmbd_sd *ppntsd, int addition_info,
 		   __u32 *secdesclen, struct smb_fattr *fattr);
 int init_acl_state(struct posix_acl_state *state, u16 cnt);
 void free_acl_state(struct posix_acl_state *state);
@@ -95,7 +96,7 @@ int compare_sids(const struct smb_sid *ctsid, const struct smb_sid *cwsid);
 bool smb_inherit_flags(int flags, bool is_dir);
 int smb_inherit_dacl(struct ksmbd_conn *conn, const struct path *path,
 		     unsigned int uid, unsigned int gid);
-/* Missing, unsupported, malformed or stale SDs retain the POSIX fallback */
+/* Missing, unsupported, unreadable, or stale SDs retain the POSIX fallback */
 static inline bool smb_no_stored_sd(int rc)
 {
 	return rc == -ENODATA || rc == -EOPNOTSUPP || rc == -EINVAL;
@@ -110,8 +111,6 @@ int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		 bool dacl_requested);
 void id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid);
 void ksmbd_init_domain(u32 *sub_auth);
-size_t smb_acl_sec_desc_scratch_len(struct smb_fattr *fattr,
-		struct smb_ntsd *ppntsd, int ppntsd_size, int addition_info);
 
 static inline uid_t posix_acl_uid_translate(const struct mnt_idmap *idmap,
 					    struct posix_acl_entry *pace)
fs/smb/server/tests/smbacl_kunit.c +42 -0

54 lines not on this page · raw message

fs/smb/server/vfs.c +28 -22

90 lines not on this page · raw message

fs/smb/server/vfs.h +5 -5
index fb184546d26b..a6a42e979022 100644
@@ -164,11 +164,11 @@ int ksmbd_vfs_remove_sd_xattrs(const struct mnt_idmap *idmap, const struct path
 int ksmbd_vfs_set_sd_xattr(struct ksmbd_conn *conn,
 			   const struct mnt_idmap *idmap,
 			   const struct path *path,
-			   const struct smb_ntsd *pntsd, int len);
-int ksmbd_vfs_get_sd_xattr(struct ksmbd_conn *conn,
-			   const struct mnt_idmap *idmap,
-			   struct dentry *dentry,
-			   struct smb_ntsd **pntsd);
+			   const void *pntsd, int len);
+int __must_check ksmbd_vfs_get_sd_xattr(struct ksmbd_conn *conn,
+					const struct mnt_idmap *idmap,
+					struct dentry *dentry,
+					struct ksmbd_sd **sd);
 int ksmbd_vfs_set_dos_attrib_xattr(const struct mnt_idmap *idmap,
 				   const struct path *path,
 				   struct xattr_dos_attrib *da,
Signature · 1 line
2.47.3
maintainer Applied
#3 lore raw
In reply to Ian Bridges
Quoted 230 lines · Ian Bridges

ksmbd reads and writes NT security descriptors (SDs) in five places:
QUERY_INFO, CREATE, inheritance, SET_INFO, and the access check. Each walks the raw bytes with its own bounds checks, and those walks in smbacl.c have needed a long run of fixes. This series replaces them with one decoder and one encoder, so the bounds are checked in one place and the callers handle no SD bytes.

Patch 1 adds the decoder and the encoder with their KUnit suite, and nothing calls them yet. ksmbd_sd_decode() validates a whole self-relative SD and returns a struct ksmbd_sd in a single allocation. The struct is plain data that the callers read directly, and every pointer in it points at bytes the decoder has checked. ksmbd_sd_encode() checks a struct that a caller filled in and writes the SD to a buffer it allocates.

Patch 2 is the cutover of the existing code to the new codec. The functions in smbacl.c keep their names and their logic, and only the code that read or wrote the bytes of an SD is replaced. The decisions the callers make are meant to stay as they are. A decision changes only where the decoder reads an SD differently from the walk it replaces, or refuses one the walk accepted. Other changes to those decisions are left for later patches.

The earlier proposal [1] left the access check, smb_check_perm_dacl(), as it is. This series converts it with the others, because the loader of the stored SD now returns a decoded SD.

Changes since the RFC
=====================

v1 was an RFC [2]. Thanks to Namjae for the review of it. The second and third changes follow his answers.

- Rebased onto ksmbd-for-next b0bd2fe7715f. Patch 2 stopped applying when commit 3cfe35e0d26c ("smb/server: fix little-endian values in diagnostic messages") changed a debug line in parse_sec_desc() that the patch removes.
- A malformed owner or group SID no longer makes a stored SD malformed. The decoder leaves that SID out, as it does a malformed SACL, and ksmbd uses the DACL. An SD from a client with such a SID is still refused. The flag sacl_dropped is now part_dropped.
- CREATE succeeds when the SD built for the new file is too large to store. The file then has no stored SD.
- The codec and its tests stay in one patch.

Changes in behavior
===================

The message of patch 2 lists the changes, and the rules the decoder enforces are the sd_malformed() calls in patch 1, each reached by a KUnit case. The changes below are the ones I would like feedback on.

A malformed SD from a client is refused whole. A stored SD is refused whole if its header or its DACL is malformed, and a malformed owner SID, group SID, or SACL is left out of it. The walks have no common notion of a malformed SD. Some malformed SDs are refused by no walk today. Some are refused on one path and read on another. Some are cut short at the bad ACE, and the ACEs before it are still used. The decoder refuses an SD that breaks a structural rule of MS-DTYP. Most of the rules are bounds. The rules below go further. Each item says what the series refuses and what the walks do with it today.

1. The decoder refuses an ACL if it cannot read all AceCount ACEs within AclSize. Today SET_INFO and inheritance refuse a count above (AclSize - 8) / 18, and otherwise each walk uses the ACEs it can read. Using the ACEs that fit would enforce a part of an ACL.
2. The decoder accepts Revision 1 for an SD and for a SID, and AclRevision 2 or 4 for an ACL. It refuses any other value. Today no walk refuses another value, and the SD is stored and used. The revision says which layout follows.
3. MS-DTYP 2.4.4.1 requires AceSize to be a multiple of 4, and the decoder refuses an AceSize that is not. Today no walk checks it, and each steps by AceSize to the next ACE.
4. The decoder refuses an ACE type that MS-DTYP gives no layout. These are 0x03, 0x04, 0x08, 0x0E, 0x10, and anything above 0x13. Today every ACE is read as a plain ACE with its SID at byte 8, so an ACE of these types is stored, returned, and inherited. Without a layout the decoder cannot say where the SID is. This is stricter than MS-DTYP 2.4.5, which lists 0x03 and 0x08 among the types an ACL can hold.
5. In an object ACE, two bits of the Flags say which GUIDs come before the SID. The decoder refuses any other bit. Today the walks read the Flags as the start of the SID, and SET_INFO stores the ACE if those bytes pass for a SID.
6. The decoder refuses a nonzero OffsetDacl in a stored SD without DACL_PRESENT. Today QUERY_INFO, inheritance, and the access check use the DACL at that offset. SET_INFO already refuses this from a client. The two fields disagree about whether the SD has a DACL.

Not everything that MS-DTYP forbids is refused, for example a SACL ACE type in a DACL. Two things are let through for a reason. An SD without SELF_RELATIVE is read as self-relative, since ksmbd has stored SDs with the bit clear. A malformed owner SID, group SID, or SACL in a stored SD is left out so that the DACL remains usable. An SD from a client with any of the three malformed makes SET_INFO or the CREATE context fail.

A refused SD is handled as follows.

7. From a client, in SET_INFO or a CREATE context, parse_sec_desc() returns -EINVAL, as it does for the SDs it refuses today. Nothing is mapped and nothing is stored. The file that a CREATE made stays, as it does today when the SD is refused.
8. QUERY_INFO of a malformed stored SD fails with STATUS_INVALID_SECURITY_DESCR. Today the reply holds the ACEs ahead of the malformed one, or a NULL DACL if the header of the DACL is malformed. An open that runs the access check is denied first (change 9). So this is what a handle that was open already gets, or one opened with FILE_DELETE_ON_CLOSE, for which smb2_open() does not call smb_check_perm_dacl().
9. The access check denies every request against a malformed stored SD. Today it decides on the ACEs ahead of the malformed one, and it makes no check if the header of the DACL is malformed. A DACL that cannot be read whole cannot be enforced, and the part that was not read may hold its deny ACEs. The same check hides such a file from a directory listing on a share with hide unreadable set. The cost is that such a file cannot be repaired through an open that runs the check, since WRITE_DAC is denied as well. A handle that already has WRITE_DAC can still set a new SD.
10. Inheritance does not inherit from a parent whose stored SD is malformed. The new file gets the SD built from its inode, as when the parent has none. Today that happens for some of these SDs, and for others the file inherits the ACEs ahead of the malformed one. A parent whose stored SD has only a malformed owner or group SID is inherited from, and the stored SD of the new file is without that SID. Today inheritance refuses such a parent if the SID is out of bounds or has more than 15 sub-authorities.

A stored SD can be malformed because a client sent a malformed SD to a ksmbd that stored it unchecked, or because the SD inside the xattr was damaged. ksmbd has also written two kinds of malformed SD itself, both when a file inherited from its parent. I have found no others. In the first kind, the parent had an inheritable object ACE, and inheritance wrote that ACE without its GUIDs. The DACL of such an SD is malformed, so the access check denies.

In the second kind, the DACL is intact. Before commit 4616bbc5389a ("ksmbd: build an inherited security descriptor with its own offsets"), inheritance wrote the child's SD at the parent's offsets. If the parent stored its DACL before its owner and group, and the child's DACL came out larger than the parent's, the larger DACL overwrote the child's owner or group. In v1 the overwritten SID made the access check deny. In v2 the decoder leaves that SID out and the check uses the DACL.

One change is not about malformed SDs.

11. A DACL that would pass 65535 bytes fails with -E2BIG, and QUERY_INFO returns STATUS_INSUFFICIENT_RESOURCES. Today the POSIX ACL entries that do not fit are left out. build_sec_desc() fails with -ENOMEM if an allocation fails while the POSIX ACL entries are mapped. Today the rest of that POSIX ACL is left out. A DACL cut short reads as the whole DACL, to a client and to the access check. An inherited DACL that is too large is handled as it is today, and the new file gets the SD built from its inode. Inherited ACEs now keep their data, so a child DACL can pass the limit where it did not before.

A default ACL too large for a DACL takes about 1800 named users for a file and about 700 for a directory. CREATE under such a default ACL succeeds, and the new file or directory has no stored SD. The POSIX ACL it inherited is in place. In v1 the CREATE failed after it had made the file.

Tests
=====

Tested on ksmbd-for-next b0bd2fe7715f. Every test below was run again for v2.
- Each patch builds with W=1 and no warnings (GCC 14, x86_64 with KASAN), and sparse reports nothing in fs/smb/server. With both patches applied, fs/smb/server and its tests also build for 32-bit x86 with GCC 14 and clang 22, W=1 and no warnings.
- KUnit under UML passes at each patch with GCC 14 and with clang 22, which enforces __counted_by. With both patches that is ksmbd-smbacl 5 of 5 and ksmbd_secdesc 6 of 6, 38 cases with their parameters. Patch 2 adds the fifth ksmbd-smbacl case.
- The same KUnit suites pass under qemu on 32-bit x86 (GCC 14), on x86_64 with KMSAN (clang 22), on big-endian s390 (clang 22), and on 32-bit big-endian PowerPC (clang 22).
- checkpatch --strict reports nothing but the note about MAINTAINERS for the new files.
- smbtorture smb2.acls, smb2.setinfo, smb2.getinfo, smb2.create, smb2.sdread, smb2.maximum_allowed, smb2.winattr, smb2.delete-on-close-perms, smb2.dosmode, and smb2.rename give the same results before and after the series, on a KASAN kernel booted with kasan_multi_shot. The one exception is mkdir-dup in smb2.create, which is a race. It passed 19 of 60 runs on the base and 24 of 60 with the series. There is no KASAN report or warning, and the kernel stays untainted.
- Scripts that query, set, and inherit SDs of many shapes over SMB were run before and after the series. Every QUERY_INFO reply is the same but for an inherited callback ACE, which keeps its application data. One SET_INFO that was accepted is now refused. Its object ACE has an undefined bit in its Flags. The stored SDs differ in their bytes, since each is now the one the encoder writes.
- I damaged two stored SDs by hand. I raised the AceCount of the first by one and cut the second short inside its header. The base uses the first SD and treats the second as missing. With the series, an open that runs the access check is denied for either file, and ksmbd logs a warning. QUERY_INFO returns STATUS_INVALID_SECURITY_DESCR on a handle opened before the damage and on a handle opened with FILE_DELETE_ON_CLOSE. SET_INFO on the handle opened before the damage repairs the file.
- I changed the revision of the owner SID in the stored SD of a file and of a directory, and did the same with the group SID. Every open and every QUERY_INFO reply is the same as before the change, with the series and on the base. A file created in the directory inherits its DACL. With the series, the stored SD of that file is without the SID.
- On a tmpfs, under a directory whose default ACL names 1900 users, CREATE succeeds with the series. The new file has its POSIX ACL and no stored SD.
- With slab allocations under the decoder and the encoder made to fail one time in five (failslab), smb2.acls, smb2.create, smb2.setinfo, smb2.getinfo, and the scripts leave no KASAN report, no warning, and nothing for kmemleak.
- Out of tree, the converted functions of smbacl.c were run in userspace under ASan and UBSan against upstream's functions compiled verbatim. That was about 1.1 million comparisons over generated and hand-written SDs for the QUERY_INFO reply, SET_INFO, and inheritance. Every difference from upstream is one the series lists. The QUERY_INFO comparisons do not cover a stored SD that the decoder refuses. That refusal is in smb2pdu.c and no reply is built.

The 32-bit, KMSAN, and big-endian runs are of the KUnit suites only. A live server was tested on x86_64 alone.

The proposal mentioned CBMC proofs of the decoder and the encoder. They were run on an earlier revision of the codec and not since it changed, so the series makes no claim from them.

Quoted 8 lines

This series was developed with LLM assistance.

[1] https://lore.kernel.org/linux-cifs/[email protected]/
[2] https://lore.kernel.org/linux-cifs/[email protected]/

Ian Bridges (2):
ksmbd: add a security descriptor decoder and encoder
ksmbd: use the security descriptor codec in callers

Applied them to #ksmbd-for-next.
Thanks!