Skip to content

Fixed one-byte stack overflow in ChrootSymlinkDeep() - #6531

Open
Dhanu-dynamic wants to merge 1 commit into
cfengine:masterfrom
Dhanu-dynamic:chroot-symlink-readlink-nul
Open

Dhanu-dynamic wants to merge 1 commit into
cfengine:masterfrom
Dhanu-dynamic:chroot-symlink-readlink-nul

Conversation

@Dhanu-dynamic

Copy link
Copy Markdown
Contributor

ChrootSymlinkDeep() sizes target from the st_size that PrepareChangesChroot() got from lstat(), plus one for the NUL, but passed the full size to readlink(). readlink() does not terminate and returns up to bufsiz bytes, so if the link is swapped for a longer one between the lstat() and the readlink(), target[ret] = '\0' lands one byte past the VLA. cf-agent --simulate=diff/manifest runs this as root and PrepareChangesChroot() recurses into every entry of the promised tree, so a user who owns a directory in it can retry the swap with rename() in a loop. readlink() now gets target_size - 1, like the other callers in the tree; a link that grew is truncated instead. checked with a model of the function built with zig cc's ubsan: "index 2 out of bounds for type 'char[2]'" before, clean after.

The target buffer is sized from the st_size of the caller's lstat(),
plus one for the terminator, but readlink() was given the whole buffer.
If the link is replaced with a longer one in between, readlink() fills
the buffer and the NUL is written one byte past it. This runs as root
in --simulate mode while walking the promised tree.

Changelog: Title
Signed-off-by: Dhanraj E <dhanraj@labs.digiscrypt.com>

@larsewi larsewi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A better fix would be to stop if truncation is detected, rather than proceeding with a truncated buffer.

ssize_t ret = readlink(path, target, target_size);
if (ret < 0 || (size_t) ret >= target_size)
{
    /* Error, or the link changed since lstat() and was truncated. */
    return;
}
target[ret] = '\0';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants