From fd69d4a4099ae973ad9ca5ab57d8456fc0f300e4 Mon Sep 17 00:00:00 2001 From: Kenneth Shaw Date: Thu, 5 Nov 2026 05:59:05 +0700 Subject: [PATCH] Fix two crashes in Decode and bound the output of a Printf format Andrei Beshkov found these with fuzzing, in pull request 7 and a comment on it. Each fix follows ncurses 6.6 (D3): - Decode refuses a negative count in the main header, as _nc_read_termtype does. Before, a negative count panicked. - canonicalizeAscChars follows repair_acsc. An unpaired last byte stays at the end, and when a source character repeats, the last pair wins. Before, an odd length panicked, and the first pair won. - scanFormatFn follows parse_format. Before the verb, it accepts only the flags, a width and a precision. A width or precision over 10000 drops the flags, and %c ignores the format. Before, "%:%%999999XX" returned 1 MB. The expected values of the new Printf tests are the output of tput. FuzzDecode and FuzzPrintf check that neither function panics. Co-Authored-By: Claude Opus 5.5 --- dec.go | 33 ++++++++++++++-------- dec_test.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++- param.go | 78 +++++++++++++++++++++++++++++++-------------------- param_test.go | 33 ++++++++++++++++++++-- 4 files changed, 171 insertions(+), 45 deletions(-) diff --git a/dec.go b/dec.go index d2caf8d..7d15f7d 100644 --- a/dec.go +++ b/dec.go @@ -33,9 +33,15 @@ const ( fieldExtTableSize ) -// hasInvalidCaps determines if the capabilities in h are invalid. +// hasInvalidCaps determines if the capabilities in h are invalid. As +// _nc_read_termtype in ncurses does, it refuses a negative count. func hasInvalidCaps(h []int) bool { - return h[fieldBoolCount] > CapCountBool || + return h[fieldNameSize] < 0 || + h[fieldBoolCount] < 0 || + h[fieldNumCount] < 0 || + h[fieldStringCount] < 0 || + h[fieldTableSize] < 0 || + h[fieldBoolCount] > CapCountBool || h[fieldNumCount] > CapCountNum || h[fieldStringCount] > CapCountString } @@ -127,7 +133,7 @@ type decoder struct { // readBytes reads the next n bytes of buf, incrementing pos by n. func (d *decoder) readBytes(n int) ([]byte, error) { - if d.n < d.pos+n { + if n < 0 || d.n < d.pos+n { return nil, ErrUnexpectedFileEnd } n, d.pos = d.pos, d.pos+n @@ -245,22 +251,25 @@ func (d *decoder) readStrings(n, sz int) (map[int][]byte, map[int]bool, error) { return strs, strsM, nil } -// canonicalizeAscChars reorders chars to be unique, in order. -// -// See repair_acsc in ncurses-6.6/progs/dump_entry.c. +// canonicalizeAscChars orders the pairs in z by their first byte, as +// repair_acsc in ncurses-6.6/progs/dump_entry.c does. When a first byte +// repeats, the last pair wins. An unpaired last byte stays at the end. func canonicalizeAscChars(z []byte) []byte { var c []byte enc := make(map[byte]byte, len(z)/2) - for i := 0; i < len(z); i += 2 { + for i := 0; i+1 < len(z); i += 2 { if _, ok := enc[z[i]]; !ok { - a, b := z[i], z[i+1] - c, enc[a] = append(c, a), b + c = append(c, z[i]) } + enc[z[i]] = z[i+1] } slices.Sort(c) - r := make([]byte, 2*len(c)) - for i := range c { - r[i*2], r[i*2+1] = c[i], enc[c[i]] + var r []byte + for _, a := range c { + r = append(r, a, enc[a]) + } + if len(z)%2 == 1 { + r = append(r, z[len(z)-1]) } return r } diff --git a/dec_test.go b/dec_test.go index c12c620..66f7c1d 100644 --- a/dec_test.go +++ b/dec_test.go @@ -2,6 +2,8 @@ package terminfo import ( "bytes" + "errors" + "os" "slices" "testing" ) @@ -13,10 +15,15 @@ func TestCanonicalizeAscChars(t *testing.T) { }{ {"mapped", []byte("q-xl"), []byte("q-xl")}, {"sort by source", []byte("x|q-"), []byte("q-x|")}, - {"duplicate source", []byte("q-q=x|"), []byte("q-x|")}, + {"duplicate source", []byte("q-q=x|"), []byte("q=x|")}, + {"duplicate source after another", []byte("x-q-x+"), []byte("q-x+")}, {"shared destination", []byte("x-q-"), []byte("q-x-")}, {"identity", []byte("xxqq"), []byte("qqxx")}, {"empty", nil, nil}, + {"unpaired byte", []byte("q-x"), []byte("q-x")}, + {"unpaired byte after a repair", []byte("x-q"), []byte("x-q")}, + {"unpaired byte after sorted pairs", []byte("x|q-y"), []byte("q-x|y")}, + {"single byte", []byte("q"), []byte("q")}, } { t.Run(test.name, func(t *testing.T) { if got := canonicalizeAscChars(test.input); !bytes.Equal(got, test.want) { @@ -88,3 +95,66 @@ func buildExtended(t *testing.T, names string, idx []int, data string, used int) } return append(buf, data...) } + +func TestDecodeMalformedHeader(t *testing.T) { + for _, test := range []struct { + name string + counts [5]int + }{ + {"negative name size", [5]int{-1, 0, 0, 0, 0}}, + {"negative bool count", [5]int{2, -1, 0, 0, 0}}, + {"negative num count", [5]int{2, 0, -25300, 0, 0}}, + {"negative string count", [5]int{2, 0, 0, -1, 0}}, + {"negative table size", [5]int{2, 0, 0, 0, -1}}, + } { + t.Run(test.name, func(t *testing.T) { + buf := buildMain(t, test.counts, make([]byte, 64)) + if _, err := Decode(buf); !errors.Is(err, ErrInvalidHeader) { + t.Errorf("expected %v, got: %v", ErrInvalidHeader, err) + } + }) + } +} + +func TestDecodeUnpairedAcsChars(t *testing.T) { + // the string table holds acs_chars only, with an unpaired last byte + idx := make([]byte, 2*(AcsChars+1)) + for i := range AcsChars { + idx[2*i], idx[2*i+1] = 0xff, 0xff + } + names, table := []byte("t\x00"), []byte("x-q\x00") + body := slices.Concat(names, idx, table) + ti, err := Decode(buildMain(t, [5]int{len(names), 0, 0, AcsChars + 1, len(table)}, body)) + if err != nil { + t.Fatalf("expected no error, got: %v", err) + } + if exp, got := "x-q", string(ti.Strings[AcsChars]); got != exp { + t.Errorf("expected acs_chars %q, got: %q", exp, got) + } +} + +// FuzzDecode checks that Decode returns an error, and does not panic, on a +// damaged entry. +func FuzzDecode(f *testing.F) { + for _, name := range []string{"/usr/share/terminfo/x/xterm-256color", "/usr/share/terminfo/l/linux"} { + if buf, err := os.ReadFile(name); err == nil { + f.Add(buf) + } + } + f.Add(buildMain(f, [5]int{2, 0, 0, 0, 0}, []byte("t\x00"))) + f.Fuzz(func(_ *testing.T, buf []byte) { + _, _ = Decode(buf) + }) +} + +// buildMain builds a terminfo file from the counts of the main header, which +// are the name size, the bool count, the num count, the string count and the +// table size, and the bytes that follow the header. +func buildMain(tb testing.TB, counts [5]int, body []byte) []byte { + tb.Helper() + var buf []byte + for _, v := range append([]int{magic}, counts[:]...) { + buf = append(buf, byte(v), byte(v>>8)) //nolint:gosec // the low 16 bits, little endian + } + return append(buf, body...) +} diff --git a/param.go b/param.go index 09d5621..fe5bbfd 100644 --- a/param.go +++ b/param.go @@ -113,16 +113,7 @@ func (p *parametizer) scanCodeFn() stateFn { //nolint:gocyclo // one case for ea switch ch { case '%': p.buf.WriteByte('%') - case ':': - // this character is used to avoid interpreting "%-" and "%+" as operators. - // the next character is where the format really begins. - p.pos++ - _, err = p.peek() - if err != nil { - return nil - } - return p.scanFormatFn - case '#', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': + case ':', '#', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': return p.scanFormatFn case 'o': p.buf.WriteString(strconv.FormatInt(int64(p.s.popInt()), 8)) @@ -227,34 +218,61 @@ func (p *parametizer) scanCodeFn() stateFn { //nolint:gocyclo // one case for ea return p.scanTextFn } +// maxFormatWidth is the largest width or precision that a format can ask +// for. parse_format in ncurses drops the flags of a format over it. +const maxFormatWidth = 10000 + +// scanFormatFn reads a format, such as "%:-5d", as parse_format in ncurses +// does. Before the verb, it accepts only the flags '#', ' ' and, after a ':', +// '-', a width and a precision. Any other byte ends the format, and is read as +// a code. A width or precision over maxFormatWidth, or a second '.', drops +// every flag, so that a short string cannot ask for a long output. func (p *parametizer) scanFormatFn() stateFn { - // the character was already read, so no need to check the error. - ch, _ := p.peek() - // 6 should be the maximum length of a format string, for example "%:-9.9d". - f := make([]byte, 2, 6) - f[0], f[1] = '%', ch - var err error + f := []byte{'%'} + var minus, dot, drop bool + var n int for { - p.pos++ - ch, err = p.peek() + ch, err := p.peek() if err != nil { return nil } - f = append(f, ch) - switch ch { - case 'o', 'd', 'x', 'X': - fmt.Fprintf(p.buf, string(f), p.s.popInt()) - p.pos++ - return p.scanTextFn - case 's': - fmt.Fprintf(p.buf, string(f), p.s.popString()) - p.pos++ - return p.scanTextFn - case 'c': - fmt.Fprintf(p.buf, string(f), p.s.popByte()) + switch { + case ch == 'o' || ch == 'd' || ch == 'x' || ch == 'X' || ch == 's' || ch == 'c': + if drop { + f = f[:1] + } + p.writeFormat(append(f, ch)) p.pos++ return p.scanTextFn + case ch == ':': + minus = true + case ch == '#', ch == ' ', ch == '-' && minus: + f = append(f, ch) + case ch == '.': + drop, dot, n = drop || dot, true, 0 + f = append(f, ch) + case isDigit(ch): + if n = n*10 + int(ch-'0'); n > maxFormatWidth { + drop, n = true, maxFormatWidth + } + f = append(f, ch) + default: + return p.scanCodeFn } + p.pos++ + } +} + +// writeFormat pops a value and writes it with the format f, which ends with +// its verb. As ncurses does, %c writes the byte and ignores the format. +func (p *parametizer) writeFormat(f []byte) { + switch f[len(f)-1] { + case 'c': + p.buf.WriteByte(p.s.popByte()) + case 's': + fmt.Fprintf(p.buf, string(f), p.s.popString()) + default: + fmt.Fprintf(p.buf, string(f), p.s.popInt()) } } diff --git a/param_test.go b/param_test.go index a062028..6028477 100644 --- a/param_test.go +++ b/param_test.go @@ -1,6 +1,9 @@ package terminfo -import "testing" +import ( + "strings" + "testing" +) func TestPrintfFormattedValues(t *testing.T) { for _, test := range []struct { @@ -13,7 +16,20 @@ func TestPrintfFormattedValues(t *testing.T) { {"%p1%02d;%p2%03d!", []any{3, 4}, "03;004!"}, {"%p1%:04x", []any{15}, "000f"}, {"%p1%:-4s!", []any{"ab"}, "ab !"}, - {"%p1%3c!", []any{byte('a')}, " a!"}, + {"%p1%3c!", []any{byte('a')}, "a!"}, + // the values below are the output of tput in ncurses 6.6 + {"%p1%:-4d!", []any{97}, "97 !"}, + {"%p1%:#-5x!", []any{97}, "0x61 !"}, + {"%p1%#o!", []any{97}, "0141!"}, + {"%p1%#x!", []any{97}, "0x61!"}, + {"%p1% d!", []any{97}, " 97!"}, + {"%p1%.3d!", []any{97}, "097!"}, + {"%p1%:+d!", []any{97}, "d!"}, + {"%p1%-d!", []any{97}, "d!"}, + {"%p1%5.2.3d!", []any{97}, "97!"}, + {"%p1%10001d!", []any{97}, "97!"}, + {"%p1%10000d!", []any{97}, strings.Repeat(" ", 9998) + "97!"}, + {"%p1%:%%999999XX", []any{97}, "%61X"}, } { t.Run(test.format, func(t *testing.T) { if got := Printf([]byte(test.format), test.params...); got != test.want { @@ -22,3 +38,16 @@ func TestPrintfFormattedValues(t *testing.T) { }) } } + +// FuzzPrintf checks that Printf does not panic, and that a width cannot make +// the output much longer than ncurses allows. +func FuzzPrintf(f *testing.F) { + for _, z := range []string{"%p1%d", "%p1%:-4d", "%:%%999999XX", "%p1%p2%+%d", "%?%p1%t;%e%;"} { + f.Add(z) + } + f.Fuzz(func(t *testing.T, z string) { + if got := Printf([]byte(z), 97, "ab"); len(got) > 10000*len(z) { + t.Errorf("Printf(%q) returned %d bytes", z, len(got)) + } + }) +}