]> git.ipfire.org Git - thirdparty/systemd.git/commit
tree-wide: check memstream buffer after closing the handle 27770/head
authorFrantisek Sumsal <frantisek@sumsal.cz>
Wed, 24 May 2023 11:29:52 +0000 (13:29 +0200)
committerFrantisek Sumsal <frantisek@sumsal.cz>
Wed, 24 May 2023 19:59:10 +0000 (21:59 +0200)
commitf392dfb5a1286184189233a84f6d6871bd4f7ade
tree5ff4a2348b7157f6049544f7c30c2899e8652352
parent08a8fd6e8de82a664762e7dd16df47227f75e2be
tree-wide: check memstream buffer after closing the handle

When closing the FILE handle attached to a memstream, it may attempt to
do a realloc() that may fail during OOM situations, in which case we are
left with the buffer pointer pointing to NULL and buffer size > 0. For
example:

```
    #include <errno.h>
    #include <stdio.h>
    #include <stdlib.h>

    void *realloc(void *ptr, size_t size) {
        return NULL;
    }

    int main(int argc, char *argv[])
    {
        FILE *f;
        char *buf;
        size_t sz = 0;

        f = open_memstream(&buf, &sz);
        if (!f)
            return -ENOMEM;

        fputs("Hello", f);

        fflush(f);
        printf("buf: 0x%lx, sz: %lu, errno: %d\n",
                    (unsigned long) buf, sz, errno);
        fclose(f);
        printf("buf: 0x%lx, sz: %lu, errno: %d\n",
                    (unsigned long) buf, sz, errno);

        return 0;
    }
```

```
$ gcc -o main main.c
$ ./main
buf: 0x74d4a0, sz: 5, errno: 0
buf: 0x0, sz: 5, errno: 0
```

This might do unexpected things if the underlying code expects a valid
pointer to the memstream buffer after closing the handle.

Found by Nallocfuzz.
17 files changed:
src/basic/string-util.c
src/busctl/busctl.c
src/core/manager-dump.c
src/coredump/coredump.c
src/journal/journalctl.c
src/libsystemd/sd-bus/bus-introspect.c
src/libsystemd/sd-bus/bus-match.c
src/network/generator/network-generator.c
src/oom/oomd-manager.c
src/oom/oomd-util.c
src/resolve/resolved-dns-dnssec.c
src/resolve/resolved-manager.c
src/shared/bus-util.c
src/shared/calendarspec.c
src/shared/elf-util.c
src/shared/format-table.c
src/shared/json.c