git: 634675067867 - main - cred: groupmember() and co.: Sanity check cred's groups (INVARIANTS)

From: Olivier Certner <olce_at_FreeBSD.org>
Date: Sat, 02 Nov 2024 20:39:33 UTC
The branch main has been updated by olce:

URL: https://cgit.FreeBSD.org/src/commit/?id=634675067867090e538b08e62ff9b14d3ffae5a3

commit 634675067867090e538b08e62ff9b14d3ffae5a3
Author:     Olivier Certner <olce@FreeBSD.org>
AuthorDate: 2024-11-01 15:11:23 +0000
Commit:     Olivier Certner <olce@FreeBSD.org>
CommitDate: 2024-11-02 20:37:42 +0000

    cred: groupmember() and co.: Sanity check cred's groups (INVARIANTS)
    
    Leverage the normalization check functions introduced in the previous
    commit in all public-facing groups search functions to catch programming
    errors early.
    
    Approved by:    markj (mentor)
    MFC after:      3 days
---
 sys/kern/kern_prot.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/sys/kern/kern_prot.c b/sys/kern/kern_prot.c
index d87d008e0bc2..a1dd3e934c35 100644
--- a/sys/kern/kern_prot.c
+++ b/sys/kern/kern_prot.c
@@ -1358,6 +1358,8 @@ bool
 group_is_supplementary(const gid_t gid, const struct ucred *const cred)
 {
 
+	groups_check_normalized(cred->cr_ngroups, cred->cr_groups);
+
 	/*
 	 * Perform a binary search of the supplementary groups.  This is
 	 * possible because we sort the groups in crsetgroups().
@@ -1381,6 +1383,8 @@ groupmember(gid_t gid, const struct ucred *cred)
 	if (cred->cr_ngroups == 0)
 		return (false);
 
+	groups_check_positive_len(cred->cr_ngroups);
+
 	if (gid == cred->cr_groups[0])
 		return (true);
 
@@ -1394,6 +1398,14 @@ groupmember(gid_t gid, const struct ucred *cred)
 bool
 realgroupmember(gid_t gid, const struct ucred *cred)
 {
+	/*
+	 * Although the equality test on 'cr_rgid' below doesn't access
+	 * 'cr_groups', we check for the latter's length here as we assume that,
+	 * if 'cr_ngroups' is 0, the passed 'struct ucred' is invalid, and
+	 * 'cr_rgid' may not have been filled.
+	 */
+	groups_check_positive_len(cred->cr_ngroups);
+
 	if (gid == cred->cr_rgid)
 		return (true);