Skip to content

Commit

Permalink
selinux: Avoid dynamic memory allocation for small context buffers
Browse files Browse the repository at this point in the history
Most context buffers are rather small and can fit on the stack,
eliminating the need to allocate them dynamically. Reserve a 4 KiB
stack buffer for this purpose to avoid the overhead of dynamic
memory allocation.

Signed-off-by: Sultan Alsawaf <sultan@kerneltoast.com>
  • Loading branch information
kerneltoast committed Aug 5, 2019
1 parent ee74c7f commit 7599a41
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions security/selinux/hooks.c
Expand Up @@ -1272,9 +1272,9 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
{
struct superblock_security_struct *sbsec = NULL;
struct inode_security_struct *isec = inode->i_security;
char context_onstack[SZ_4K] __aligned(sizeof(long));
u32 sid;
struct dentry *dentry;
#define INITCONTEXTLEN 255
char *context = NULL;
unsigned len = 0;
int rc = 0;
Expand Down Expand Up @@ -1329,19 +1329,11 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
goto out_unlock;
}

len = INITCONTEXTLEN;
context = kmalloc(len+1, GFP_NOFS);
if (!context) {
rc = -ENOMEM;
dput(dentry);
goto out_unlock;
}
context[len] = '\0';
context_onstack[ARRAY_SIZE(context_onstack) - 1] = '\0';
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
context, len);
context_onstack,
ARRAY_SIZE(context_onstack));
if (rc == -ERANGE) {
kfree(context);

/* Need a larger buffer. Query for the right size. */
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
NULL, 0);
Expand All @@ -1360,14 +1352,17 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
rc = inode->i_op->getxattr(dentry,
XATTR_NAME_SELINUX,
context, len);
} else {
context = context_onstack;
}
dput(dentry);
if (rc < 0) {
if (rc != -ENODATA) {
printk(KERN_WARNING "SELinux: %s: getxattr returned "
"%d for dev=%s ino=%ld\n", __func__,
-rc, inode->i_sb->s_id, inode->i_ino);
kfree(context);
if (context != context_onstack)
kfree(context);
goto out_unlock;
}
/* Map ENODATA to the default file SID */
Expand All @@ -1391,13 +1386,15 @@ static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dent
"returned %d for dev=%s ino=%ld\n",
__func__, context, -rc, dev, ino);
}
kfree(context);
if (context != context_onstack)
kfree(context);
/* Leave with the unlabeled SID */
rc = 0;
break;
}
}
kfree(context);
if (context != context_onstack)
kfree(context);
isec->sid = sid;
break;
case SECURITY_FS_USE_TASK:
Expand Down

0 comments on commit 7599a41

Please sign in to comment.