internal/protocol/tokenize.go
86 lines · 2227 bytes
2 symbols in this file
1package protocol
2
3import (
4 "errors"
5 "fmt"
6 "strings"
7)
8
9// Tokenize splits an SSH exec command string into argv using POSIX
10// shell-word rules: whitespace separates words; single quotes preserve
11// everything literally; double quotes preserve everything except backslash
12// before \, ", or $; a bare backslash escapes the next character. There is
13// no expansion of any kind — no globbing, variables, or substitution. The
14// client's shell has already applied one layer of quoting before the string
15// reaches us.
16func Tokenize(s string) ([]string, error) {
17 var argv []string
18 var cur strings.Builder
19 inWord := false
20
21 i := 0
22 for i < len(s) {
23 c := s[i]
24 switch {
25 case c == ' ' || c == '\t' || c == '\n':
26 if inWord {
27 argv = append(argv, cur.String())
28 cur.Reset()
29 inWord = false
30 }
31 i++
32 case c == '\'':
33 inWord = true
34 end := strings.IndexByte(s[i+1:], '\'')
35 if end < 0 {
36 return nil, errors.New("unterminated single quote")
37 }
38 cur.WriteString(s[i+1 : i+1+end])
39 i += end + 2
40 case c == '"':
41 inWord = true
42 var err error
43 if i, err = doubleQuoted(s, i, &cur); err != nil {
44 return nil, err
45 }
46 case c == '\\':
47 if i+1 >= len(s) {
48 return nil, errors.New("trailing backslash")
49 }
50 inWord = true
51 cur.WriteByte(s[i+1])
52 i += 2
53 case strings.IndexByte("$`;&|<>()*?[#~", c) >= 0:
54 // Unquoted shell metacharacters are rejected outright rather
55 // than passed through: there is no shell here, and silently
56 // treating them as literals would mask client quoting bugs.
57 return nil, fmt.Errorf("unquoted shell metacharacter %q", c)
58 default:
59 inWord = true
60 cur.WriteByte(c)
61 i++
62 }
63 }
64 if inWord {
65 argv = append(argv, cur.String())
66 }
67 return argv, nil
68}
69
70// doubleQuoted writes the double-quoted string opening at s[i] to cur,
71// unescaping \\, \", \$ and \`, and returns the index past its closing
72// quote.
73func doubleQuoted(s string, i int, cur *strings.Builder) (int, error) {
74 for i++; i < len(s); i++ {
75 c := s[i]
76 if c == '"' {
77 return i + 1, nil
78 }
79 if c == '\\' && i+1 < len(s) && strings.IndexByte("\\\"$`", s[i+1]) >= 0 {
80 i++
81 c = s[i]
82 }
83 cur.WriteByte(c)
84 }
85 return i, errors.New("unterminated double quote")
86}