diff --git a/docs/changelog.rst b/docs/changelog.rst index 40e661fd2..730b93da8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -135,6 +135,8 @@ Detailed list of changes - Unicode input kitten: Fix searching by name not finding some characters such as the pound sign (:iss:`10862`) +- choose-files kitten: Sanitize file names, archive member names, ebook metadata and previewer output everywhere they are displayed so they cannot inject escape codes into the terminal + - :doc:`Custom shaders `: Add ``screen-shake`` shaders that shake a window on bell and new events and uniforms for command start/finish and alternate screen enter/exit diff --git a/kittens/choose_files/archive.go b/kittens/choose_files/archive.go index e36720d65..b65741f0d 100644 --- a/kittens/choose_files/archive.go +++ b/kittens/choose_files/archive.go @@ -48,7 +48,7 @@ type archive_preview struct { func displayFilename(s string) string { if isPrintableUTF8(s) { - return s + return sanitize_name(s) } return fmt.Sprintf("%X", utils.UnsafeStringToBytes(s)) } @@ -95,12 +95,7 @@ func (p *archive_preview) render(output chan<- *MessagePreview, base *MessagePre if err == nil || errors.Is(err, zip.ErrInsecurePath) { defer r.Close() for _, f := range r.File { - if f.NonUTF8 { - names = append(names, displayFilename(f.Name)) - } else { - names = append(names, f.Name) - } - + names = append(names, displayFilename(f.Name)) } } case ".rar": diff --git a/kittens/choose_files/archive_test.go b/kittens/choose_files/archive_test.go index 1aed35f5f..a12491394 100644 --- a/kittens/choose_files/archive_test.go +++ b/kittens/choose_files/archive_test.go @@ -13,15 +13,18 @@ import ( var _ = fmt.Print -func new_test_archive_preview(t *testing.T) (*archive_preview, *MessagePreview) { +func new_test_archive_preview(t *testing.T, names ...string) (*archive_preview, *MessagePreview) { t.Helper() + if len(names) == 0 { + names = []string{"a.txt", "dir/b.txt"} + } path := filepath.Join(t.TempDir(), "test.zip") f, err := os.Create(path) if err != nil { t.Fatal(err) } zw := zip.NewWriter(f) - for _, name := range []string{"a.txt", "dir/b.txt"} { + for _, name := range names { w, err := zw.Create(name) if err != nil { t.Fatal(err) @@ -100,3 +103,19 @@ func TestArchivePreviewWorkerPanic(t *testing.T) { t.Fatalf("archive preview does not report the panic: %#v", result.trailers) } } + +// Names of archive members are untrusted and must not be able to inject +// escape codes into the terminal. +func TestArchivePreviewSanitizesNames(t *testing.T) { + evil := "x\x1b]52;c;aGFja2Vk\x07\ny.txt" + p, base := new_test_archive_preview(t, evil) + result := run_archive_preview_worker(t, p, base) + for _, line := range result.trailers { + if strings.ContainsAny(line, "\x1b\x07\n") { + t.Fatalf("archive preview contains unsanitized name: %#v", line) + } + } + if expected := "x␛]52;c;aGFja2Vk␇␤y.txt"; !slices.Contains(result.trailers, expected) { + t.Fatalf("archive preview does not list %#v: %#v", expected, result.trailers) + } +} diff --git a/kittens/choose_files/calibre.go b/kittens/choose_files/calibre.go index a88a241b4..3f63aa447 100644 --- a/kittens/choose_files/calibre.go +++ b/kittens/choose_files/calibre.go @@ -362,18 +362,18 @@ func (c calibre_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) { offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center) } } - ext := filepath.Ext(s.abspath) + ext := sanitize_name(filepath.Ext(s.abspath)) text := fmt.Sprintf("%s: %s", ext, humanize.Bytes(uint64(s.metadata.Size()))) icon := icons.IconForPath(s.abspath) w(icon+" "+text, true) r := s.custom_metadata.custom.(*CalibreResponse) - w("Title: "+r.Metadata.Title, false) - w("Authors: "+strings.Join(r.Metadata.Authors, " & "), false) + w("Title: "+sanitize(r.Metadata.Title), false) + w("Authors: "+sanitize(strings.Join(r.Metadata.Authors, " & ")), false) if r.Metadata.Series != "" { - w(fmt.Sprintf("Series: Book %g of %s", r.Metadata.Series_index, r.Metadata.Series), false) + w(fmt.Sprintf("Series: Book %g of %s", r.Metadata.Series_index, sanitize(r.Metadata.Series)), false) } if len(r.Metadata.Tags) > 0 { - w("Tags: "+strings.Join(r.Metadata.Tags, ", "), false) + w("Tags: "+sanitize(strings.Join(r.Metadata.Tags, ", ")), false) } return } diff --git a/kittens/choose_files/cmd_preview.go b/kittens/choose_files/cmd_preview.go index c86ef2ae8..364da61cd 100644 --- a/kittens/choose_files/cmd_preview.go +++ b/kittens/choose_files/cmd_preview.go @@ -90,13 +90,13 @@ func (c cmd_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) { offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center) } } - ext := filepath.Ext(s.abspath) + ext := sanitize_name(filepath.Ext(s.abspath)) r := s.custom_metadata.custom.(*CmdResult) - text := fmt.Sprintf("%s: %s%s", ext, humanize.Bytes(uint64(s.metadata.Size())), r.TitleExtra) + text := fmt.Sprintf("%s: %s%s", ext, humanize.Bytes(uint64(s.metadata.Size())), keep_only_sgr(r.TitleExtra)) icon := icons.IconForPath(s.abspath) w(icon+" "+text, true) for _, line := range r.Lines { - w(line, false) + w(keep_only_sgr(line), false) } h.lp.QueueWriteString("\x1b[m") // reset SGR attributes return diff --git a/kittens/choose_files/ffmpeg.go b/kittens/choose_files/ffmpeg.go index 3025c079f..2a6154c64 100644 --- a/kittens/choose_files/ffmpeg.go +++ b/kittens/choose_files/ffmpeg.go @@ -154,7 +154,7 @@ func (c ffmpeg_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) { offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center) } } - ext := filepath.Ext(s.abspath) + ext := sanitize_name(filepath.Ext(s.abspath)) text := fmt.Sprintf("%s: %s", ext, humanize.Bytes(uint64(s.metadata.Size()))) r := s.custom_metadata.custom.(*FFMpegMetadata) icon := icons.IconForPath(s.abspath) diff --git a/kittens/choose_files/footer.go b/kittens/choose_files/footer.go index 90f484011..7fe08350c 100644 --- a/kittens/choose_files/footer.go +++ b/kittens/choose_files/footer.go @@ -91,7 +91,7 @@ func (h *Handler) draw_footer() (num_lines int, err error) { if rel, rerr := filepath.Rel(h.state.CurrentDir(), s); rerr == nil { text = rel } - w(" ", text, nil, s, func(abspath string) { h.state.ToggleSelection(abspath) }) + w(" ", sanitize_name(text), nil, s, func(abspath string) { h.state.ToggleSelection(abspath) }) if len(lines)-before > 2 && len(h.state.selections)-i-1 > 3 { w(" ", fmt.Sprintf("and %d more…", len(h.state.selections)-1-i), nil, "", nil) break diff --git a/kittens/choose_files/preview.go b/kittens/choose_files/preview.go index 71dfb362f..65e49f437 100644 --- a/kittens/choose_files/preview.go +++ b/kittens/choose_files/preview.go @@ -44,11 +44,10 @@ type PreviewManager struct { highlighter highlight.Highlighter } -func NewPreviewManager(err_chan chan error, settings Settings, WakeupMainThread func() bool) (ans *PreviewManager) { - defer func() { sanitize = ans.highlighter.Sanitize }() +func NewPreviewManager(err_chan chan error, settings Settings, WakeupMainThread func() bool) *PreviewManager { return &PreviewManager{ report_errors: err_chan, settings: settings, WakeupMainThread: WakeupMainThread, - cache: make(map[string]Preview), highlighter: highlight.NewHighlighter(nil), + cache: make(map[string]Preview), highlighter: highlight.NewHighlighter(sanitize), } } @@ -116,27 +115,25 @@ func (p MessagePreview) Render(h *Handler, x, y, width, height int) { func NewErrorPreview(err error) Preview { sctx := style.Context{AllowEscapeCodes: true} - text := fmt.Sprintf("%s: %s", sctx.SprintFunc("fg=red")("Error"), err) + text := fmt.Sprintf("%s: %s", sctx.SprintFunc("fg=red")("Error"), sanitize(err.Error())) return &MessagePreview{msg: text} } -var sanitize func(string) string - func write_file_metadata(abspath string, metadata fs.FileInfo, entries []fs.DirEntry) (header string, trailers []string) { buf := strings.Builder{} buf.Grow(4096) add := func(key, val string) { fmt.Fprintf(&buf, "%s: %s\n", key, val) } ftype := metadata.Mode().Type() const file_icon = " " - fmt.Fprintln(&buf, filepath.Base(abspath)) + fmt.Fprintln(&buf, sanitize_name(filepath.Base(abspath))) switch ftype { case 0: add("Size", humanize.Bytes(uint64(metadata.Size()))) case fs.ModeSymlink: if tgt, err := os.Readlink(abspath); err == nil { - add("Target", sanitize(tgt)) + add("Target", sanitize_name(tgt)) } else { - add("Target", err.Error()) + add("Target", sanitize(err.Error())) } case fs.ModeDir: num_files, num_dirs := 0, 0 @@ -164,7 +161,7 @@ func write_file_metadata(abspath string, metadata fs.FileInfo, entries []fs.DirE slices.SortFunc(names, func(a, b string) int { return strings.Compare(type_map[a].lname, type_map[b].lname) }) fmt.Fprintln(&buf, "Contents:") for _, n := range names { - trailers = append(trailers, icons.IconForFileWithMode(n, type_map[n].ftype, false)+" "+sanitize(n)) + trailers = append(trailers, icons.IconForFileWithMode(n, type_map[n].ftype, false)+" "+sanitize_name(n)) } } return buf.String(), trailers @@ -181,7 +178,7 @@ func NewDirectoryPreview(abspath string, metadata fs.FileInfo) Preview { } func NewFileMetadataPreview(abspath string, metadata fs.FileInfo) *MessagePreview { - ext := filepath.Ext(abspath) + ext := sanitize_name(filepath.Ext(abspath)) if ext == "" { ext = "File" } @@ -191,14 +188,14 @@ func NewFileMetadataPreview(abspath string, metadata fs.FileInfo) *MessagePrevie } func NewFileMetadataPreviewWithError(abspath string, metadata fs.FileInfo, err error) *MessagePreview { - ext := filepath.Ext(abspath) + ext := sanitize_name(filepath.Ext(abspath)) if ext == "" { ext = "File" } title := icons.IconForFileWithMode(filepath.Base(abspath), metadata.Mode().Type(), false) + " " + ext h, t := write_file_metadata(abspath, metadata, nil) ans := &MessagePreview{title: title, msg: h, trailers: t} - lines := style.WrapTextAsLines(err.Error(), 30, style.WrapOptions{}) + lines := style.WrapTextAsLines(sanitize(err.Error()), 30, style.WrapOptions{}) ans.trailers = append(ans.trailers, "") ans.trailers = append(ans.trailers, lines...) return ans @@ -246,7 +243,7 @@ func (p *TextFilePreview) Render(h *Handler, x, y, width, height int) { s := utils.NewLineScanner(text) buf := strings.Builder{} buf.Grow(1024 * height) - title := icons.IconForPath(p.path) + " " + filepath.Base(p.path) + fmt.Sprintf(" %s", humanize.Bytes(uint64(p.metadata.Size()))) + title := icons.IconForPath(p.path) + " " + sanitize_name(filepath.Base(p.path)) + fmt.Sprintf(" %s", humanize.Bytes(uint64(p.metadata.Size()))) for num := 1 + h.render_wrapped_text_in_region(title, x, y, width, height, true); s.Scan() && num < height; num++ { line := s.Text() truncated := wcswidth.TruncateToVisualLength(line, width) diff --git a/kittens/choose_files/results.go b/kittens/choose_files/results.go index f31841d22..41c5c17a5 100644 --- a/kittens/choose_files/results.go +++ b/kittens/choose_files/results.go @@ -25,7 +25,7 @@ func (h *Handler) draw_results_title() { if strings.HasPrefix(text, home) { text = "~" + text[len(home):] } - text = sanitize(text) + text = sanitize_name(text) available_width := h.screen_size.width - 9 if available_width < 2 { return @@ -154,7 +154,7 @@ func (h *Handler) draw_column_of_matches(matches ResultsType, current_idx int, x } else { icon = icon_for(filepath.Join(root_dir, m.text), m.ftype) } - text := sanitize(m.text) + text := sanitize_name(m.text) add_ellipsis := false width := wcswidth.Stringwidth(text) if width > available_width-3 { diff --git a/kittens/choose_files/sanitize.go b/kittens/choose_files/sanitize.go new file mode 100644 index 000000000..e4781f168 --- /dev/null +++ b/kittens/choose_files/sanitize.go @@ -0,0 +1,97 @@ +// License: GPLv3 Copyright: 2026, Kovid Goyal, + +package choose_files + +import ( + "strings" + "unicode/utf8" + + "github.com/kovidgoyal/kitty/tools/utils" + "github.com/kovidgoyal/kitty/tools/wcswidth" +) + +// replace_c1_controls replaces the UTF-8 encoded C1 control characters +// (U+0080 to U+009F) with U+FFFD. Some terminals interpret these as escape +// code introducers, for example U+009B as CSI. Each control is replaced by +// exactly one rune so that rune offsets into the text remain valid. +func replace_c1_controls(text string) string { + // All C1 controls are encoded as 0xc2 followed by a byte in 0x80-0x9f + idx := strings.IndexByte(text, 0xc2) + if idx < 0 { + return text + } + var buf strings.Builder + for idx > -1 { + if idx+1 < len(text) && text[idx+1] >= 0x80 && text[idx+1] <= 0x9f { + if buf.Cap() == 0 { + buf.Grow(len(text) + 16) + } + buf.WriteString(text[:idx]) + buf.WriteRune(utf8.RuneError) + text = text[idx+2:] + idx = strings.IndexByte(text, 0xc2) + } else if n := strings.IndexByte(text[idx+1:], 0xc2); n > -1 { + idx += n + 1 + } else { + break + } + } + if buf.Cap() == 0 { + return text + } + buf.WriteString(text) + return buf.String() +} + +// sanitize replaces control codes in untrusted multi-line text, such as file +// contents, before it is written to the terminal. Newlines are preserved. +func sanitize(text string) string { + return replace_c1_controls(utils.ReplaceControlCodes(text, " ", "\n")) +} + +// sanitize_name replaces control codes, including newlines and tabs, in +// untrusted text that must occupy a single line, such as file names. Every +// control character is replaced by exactly one rune, so rune offsets into the +// original text, such as match positions, remain valid. +func sanitize_name(text string) string { + return replace_c1_controls(utils.ReplaceControlCodes(text, "␉", "␤")) +} + +// keep_only_sgr removes all escape codes other than SGR (formatting) codes +// from a single line of untrusted text, and sanitizes the remaining text. +func keep_only_sgr(text string) string { + var buf, pending strings.Builder + buf.Grow(len(text)) + flush := func() { + if pending.Len() > 0 { + buf.WriteString(sanitize_name(pending.String())) + pending.Reset() + } + } + p := wcswidth.EscapeCodeParser{ReplaceInvalidUtf8Bytes: true} + p.HandleRune = func(ch rune) error { + pending.WriteRune(ch) + return nil + } + p.HandleCSI = func(data []byte) error { + if len(data) == 0 || data[len(data)-1] != 'm' { + return nil + } + for _, b := range data[:len(data)-1] { + if !(b >= '0' && b <= '9') && b != ';' && b != ':' { + return nil + } + } + flush() + buf.WriteString("\x1b[") + buf.Write(data) + return nil + } + if err := p.ParseString(text); err != nil { + // The callbacks never fail, so this cannot happen, but be safe and + // drop any escape codes entirely. + return sanitize_name(wcswidth.StripEscapeCodes(text)) + } + flush() + return buf.String() +} diff --git a/kittens/choose_files/sanitize_test.go b/kittens/choose_files/sanitize_test.go new file mode 100644 index 000000000..9afe293c6 --- /dev/null +++ b/kittens/choose_files/sanitize_test.go @@ -0,0 +1,95 @@ +package choose_files + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf8" +) + +var _ = fmt.Print + +func TestFileMetadataPreviewSanitizesNames(t *testing.T) { + dir := t.TempDir() + evil := "x\x1b]52;c;aGFja2Vk\x07\ny" + path := filepath.Join(dir, evil) + if err := os.Mkdir(path, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(path, evil+".\x1b[31m"), nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(evil, filepath.Join(path, "link")); err != nil { + t.Fatal(err) + } + const sanitized = "x␛]52;c;aGFja2Vk␇␤y" + check := func(mp *MessagePreview) { + t.Helper() + for _, text := range append([]string{mp.title, mp.msg}, mp.trailers...) { + if strings.ContainsAny(text, "\x1b\x07") { + t.Fatalf("preview contains unsanitized name: %#v", text) + } + } + if all := mp.title + mp.msg + strings.Join(mp.trailers, "\n"); !strings.Contains(all, sanitized) { + t.Fatalf("preview does not contain the sanitized name %#v: %#v", sanitized, all) + } + } + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + check(NewDirectoryPreview(path, st).(*MessagePreview)) + for _, name := range []string{evil + ".\x1b[31m", "link"} { + fp := filepath.Join(path, name) + st, err = os.Lstat(fp) + if err != nil { + t.Fatal(err) + } + check(NewFileMetadataPreview(fp, st)) + check(NewFileMetadataPreviewWithError(fp, st, fmt.Errorf("failed for %s", fp))) + } +} + +func TestSanitize(t *testing.T) { + for _, tc := range []struct{ input, name, multiline string }{ + {"plain.txt", "plain.txt", "plain.txt"}, + {"a\x1b[31mb\x07", "a␛[31mb␇", "a␛[31mb␇"}, + {"a\tb\nc\x7f", "a␉b␤c␡", "a b\nc␡"}, + {"a›31mb52;c;eAœ", "a�31mb�52;c;eA�", "a�31mb�52;c;eA�"}, + {"頀", "é �", "é �"}, + } { + if actual := sanitize_name(tc.input); actual != tc.name { + t.Fatalf("sanitize_name(%#v) = %#v, expected %#v", tc.input, actual, tc.name) + } + if actual := sanitize(tc.input); actual != tc.multiline { + t.Fatalf("sanitize(%#v) = %#v, expected %#v", tc.input, actual, tc.multiline) + } + } + // match positions are rune offsets, so sanitize_name must preserve them + input := "a\tb\nc\x1b›d" + if a, b := utf8.RuneCountInString(input), utf8.RuneCountInString(sanitize_name(input)); a != b { + t.Fatalf("sanitize_name changed the number of runes from %d to %d", a, b) + } +} + +func TestKeepOnlySGR(t *testing.T) { + for input, expected := range map[string]string{ + "plain": "plain", + "\x1b[1;31mred\x1b[m": "\x1b[1;31mred\x1b[m", + "\x1b[38:5:1mx": "\x1b[38:5:1mx", + "a\x1b]52;c;aGFja2Vk\x07b": "ab", + "a\x1b]52;c;aGFja2Vk\x1b\\b": "ab", + "a\x1bP+q\x1b\\b": "ab", + "a\x1b[2Jb\x1b[?1049hc": "abc", + "a\x1b[>1mb": "ab", + "a\u009d52;c;eA\u009cb": "ab", + "a\nb\x07": "a␤b␇", + "a\x1b[200~\x1b]52;c;eA\x07\x1b[201~": "a␛]52;c;eA␇", + } { + if actual := keep_only_sgr(input); actual != expected { + t.Fatalf("keep_only_sgr(%#v) = %#v, expected %#v", input, actual, expected) + } + } +} diff --git a/kittens/choose_files/save-file.go b/kittens/choose_files/save-file.go index 540a847d5..c6be58e62 100644 --- a/kittens/choose_files/save-file.go +++ b/kittens/choose_files/save-file.go @@ -136,6 +136,11 @@ func (h *Handler) initialize_save_file_name(fname string) { } } } + if sanitize_name(fname) != fname { + // Do not pre-fill names containing control codes as the readline + // would write them to the terminal unsanitized. + fname = "" + } h.rl.SetText(fname) } @@ -146,7 +151,7 @@ func (h *Handler) draw_save_file_name_screen() (err error) { h.lp.Println(h.state.WindowTitle()) } h.lp.Println("Enter the name of the", desc, "below, relative to:") - h.lp.Println(h.lp.SprintStyled("fg=green", h.state.CurrentDir())) + h.lp.Println(h.lp.SprintStyled("fg=green", sanitize_name(h.state.CurrentDir()))) if h.state.mode.AllowsMultipleSelection() { h.lp.Println("Use shift+enter (or whatever you mapped the select action to) to enter multiple filenames") }