From 0cf8d597dbd5b2ae35fcd2659bd282d1f3c3e9e9 Mon Sep 17 00:00:00 2001 From: valoq Date: Sun, 10 May 2026 04:25:54 +0200 Subject: [PATCH] fix: sanitize sixel previews (#2542) * fix sixel filter * improve sixel filter * simplify sixel byte filter * cleanup --- misc.go | 12 ++++++++---- misc_test.go | 8 ++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/misc.go b/misc.go index 5f04dd35..8c069a58 100644 --- a/misc.go +++ b/misc.go @@ -526,12 +526,15 @@ func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, currState = stateNormal } case stateSixel: - // Accept printable bytes (0x20-0x7E) and ESC inside the - // DCS frame. Reject everything else (C0, DEL, 0x80+). + // Inside the DCS frame, accept only printable bytes. Tolerate + // '\r'/'\n' (some encoders insert them for readability) by + // silently dropping them. Anything else aborts the frame so + // that an attacker cannot smuggle CSI/OSC/DCS through it. switch { case b == '\033': buf.WriteByte(b) currState = stateSixelEsc + case b == '\r' || b == '\n': case b >= 0x20 && b <= 0x7E: buf.WriteByte(b) default: @@ -539,13 +542,14 @@ func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, currState = stateNormal } case stateSixelEsc: - buf.WriteByte(b) if b == '\\' { + buf.WriteByte(b) flush(true) sixel = true currState = stateNormal } else { - currState = stateSixel + buf.Reset() + currState = stateNormal } } } diff --git a/misc_test.go b/misc_test.go index 13793127..5474fbae 100644 --- a/misc_test.go +++ b/misc_test.go @@ -530,8 +530,8 @@ func TestReadLines(t *testing.T) { {"\033P\033\\", 10, []string{"\033P\033\\"}, false, true}, {"\033Pq\"1;1;1;1#0@\033\\", 10, []string{"\033Pq\"1;1;1;1#0@\033\\"}, false, true}, {"\033P\000\033\\", 10, []string{"\033\\"}, false, false}, - {"\033P\n\033\\", 10, []string{"\033\\"}, false, false}, - {"\033P\r\n\033\\", 10, []string{"", "\033\\"}, false, false}, + {"\033P\n\033\\", 10, []string{"\033P\033\\"}, false, true}, + {"\033P\r\n\033\\", 10, []string{"\033P\033\\"}, false, true}, {"\033P\033\\\033P\033\\", 10, []string{"\033P\033\\", "\033P\033\\"}, false, true}, {"foo\033P\033\\bar", 10, []string{"foo", "\033P\033\\", "bar"}, false, true}, {"foo\033P\033\\bar\033P\033\\baz", 10, []string{"foo", "\033P\033\\", "bar", "\033P\033\\", "baz"}, false, true}, @@ -541,6 +541,10 @@ func TestReadLines(t *testing.T) { {"foo\nbar\nbaz", 3, []string{"foo", "bar", "baz"}, false, false}, {"foo\nbar\nbaz\n", 3, []string{"foo", "bar", "baz"}, false, false}, {"foo\nbar\033P\033\\", 3, []string{"foo", "bar", "\033P\033\\"}, false, true}, + // Inside the DCS body, ESC must be followed by '\\' (ST) for the + // frame to be accepted. Any other byte aborts, so an attacker + // cannot embed CSI/OSC/nested-DCS through the sixel path. + {"\033P\033]52;c;x\033\\", 10, []string{"52;c;x\033\\"}, false, false}, } for _, test := range tests {