Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [day] [month] [year] [list]
Message-ID: <CAJoZT2gv_e5fz-KXBfajf7fjvqaUWCFEQ5-JKzg_O-Y_dF+TwQ@mail.gmail.com>
Date: Thu, 3 Dec 2026 15:52:39 +0800
From: Wenkai Xing <wenkaixing12@...il.com>
To: musl@...ts.openwall.com
Subject: printf: positional precision (%.*N$) reads uninitialized nl_arg

Hi,

    printf_core() runs twice. The first pass (f == 0) records the types of
    positional arguments and, at its end, pops their values into nl_arg[].
    That final loop is only reached when l10n is set.

    The width form %*N$ sets l10n, but the precision form %.*N$ does not:

        if (isdigit(s[2]) && s[3]=='$') {
                if (!f) nl_type[s[2]-'0'] = INT, p = 0;
                else p = nl_arg[s[2]-'0'].i;
                s+=4;
        }

    So when a positional precision is the only positional reference in the
    format, the first pass returns early at "if (!l10n) return 0;" without
    filling nl_arg[], and the second pass reads an uninitialized slot.

    Reproducer (musl 1.2.4 and 1.2.5, x86_64):

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

    int main(void)
    {
        errno = ENOENT;
        printf("[%.*1$m]", 3);
        errno = ENOENT;
        printf("%1$d", 5);
        printf("[%.*1$m]", 3);
        return 0;
    }

    Expected "[No ]5[No ]", i.e. strerror(ENOENT) cut to 3 characters; glibc
    prints that. Observed: "[]5[No su]". The first call prints "[]" because
    the precision read is 0; the last one prints "[No su]" because the
    previous printf("%1$d", 5) call left 5 in its nl_arg[1] on the stack.

    %m is the natural trigger because it consumes no argument of its own,
    which lets the precision be the only positional reference.

    7d358599d4c8 ("prevent invalid reads of nl_arg in printf_core") made the
    first pass stop reading nl_arg here, on the premise that it "gets
    initialized at the end of the first run". That does not hold in this
    case. The code is unchanged in master.

    Possible fix (not tested): set l10n in this branch, as the width branch
    does.

        if (isdigit(s[2]) && s[3]=='$') {
                l10n=1;
                if (!f) nl_type[s[2]-'0'] = INT, p = 0;
                else p = nl_arg[s[2]-'0'].i;
                s+=4;
        }

    This should also make gaps such as %.*2$m fail with EINVAL, like other
    positional formats. From reading the code, wprintf_core() has the same
    missing l10n=1.

    Thanks,
    KevinX

Content of type "text/html" skipped

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.