Skip to content

Commit 4c6ac08

Browse files
authored
Completely quote AppPath and CustomConf paths (#12955)
* Completely quote AppPath and CustomConf paths Properly handle spaces in AppPath and CustomConf within hooks and authorized_keys. Unfortunately here we don't seem to be able to get away with using go-shellquote as it appears that Windows doesn't play too well with singlequote quoting - therefore we will avoid singlequote quoting unless we absolutely cannot get away without it, e.g. \n or !. Fix #10813 Signed-off-by: Andrew Thornton <[email protected]> * missing change Signed-off-by: Andrew Thornton <[email protected]> * fix Test_CmdKeys Signed-off-by: Andrew Thornton <[email protected]>
1 parent 5cfc1f5 commit 4c6ac08

File tree

5 files changed

+200
-8
lines changed

5 files changed

+200
-8
lines changed

integrations/cmd_keys_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ import (
1010
"io"
1111
"net/url"
1212
"os"
13-
"strconv"
1413
"testing"
1514

1615
"code.gitea.io/gitea/cmd"
1716
"code.gitea.io/gitea/modules/setting"
17+
"code.gitea.io/gitea/modules/util"
1818

1919
"github.com/urfave/cli"
2020
)
@@ -32,7 +32,7 @@ func Test_CmdKeys(t *testing.T) {
3232
{"with_key",
3333
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
3434
false,
35-
"# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + strconv.Quote(strconv.Quote(setting.CustomConf))[1:len(strconv.Quote(strconv.Quote(setting.CustomConf)))-1] + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",
35+
"# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",
3636
},
3737
{"invalid", []string{"keys", "--not-a-flag=git"}, true, "Incorrect Usage: flag provided but not defined: -not-a-flag\n\n"},
3838
}

models/ssh_key.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ import (
3838

3939
const (
4040
tplCommentPrefix = `# gitea public key`
41-
tplCommand = "%s --config=%q serv key-%d"
42-
tplPublicKey = tplCommentPrefix + "\n" + `command=%q,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
41+
tplCommand = "%s --config=%s serv key-%d"
42+
tplPublicKey = tplCommentPrefix + "\n" + `command=%s,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
4343
)
4444

4545
var sshOpLocker sync.Mutex
@@ -84,7 +84,7 @@ func (key *PublicKey) OmitEmail() string {
8484

8585
// AuthorizedString returns formatted public key string for authorized_keys file.
8686
func (key *PublicKey) AuthorizedString() string {
87-
return fmt.Sprintf(tplPublicKey, fmt.Sprintf(tplCommand, setting.AppPath, setting.CustomConf, key.ID), key.Content)
87+
return fmt.Sprintf(tplPublicKey, util.ShellEscape(fmt.Sprintf(tplCommand, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf), key.ID)), key.Content)
8888
}
8989

9090
func extractTypeFromBase64Key(key string) (string, error) {

modules/repository/hooks.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ func getHookTemplates() (hookNames, hookTpls, giteaHookTpls []string) {
2828
fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
2929
}
3030
giteaHookTpls = []string{
31-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
32-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
33-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
31+
fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s pre-receive\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
32+
fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s update $1 $2 $3\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
33+
fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s post-receive\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
3434
}
3535
return
3636
}

modules/util/shellquote.go

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package util
6+
7+
import "strings"
8+
9+
// Bash has the definition of a metacharacter:
10+
// * A character that, when unquoted, separates words.
11+
// A metacharacter is one of: " \t\n|&;()<>"
12+
//
13+
// The following characters also have addition special meaning when unescaped:
14+
// * ‘${[*?!"'`\’
15+
//
16+
// Double Quotes preserve the literal value of all characters with then quotes
17+
// excepting: ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.
18+
// The backslash retains its special meaning only when followed by one of the
19+
// following characters: ‘$’, ‘`’, ‘"’, ‘\’, or newline.
20+
// Backslashes preceding characters without a special meaning are left
21+
// unmodified. A double quote may be quoted within double quotes by preceding
22+
// it with a backslash. If enabled, history expansion will be performed unless
23+
// an ‘!’ appearing in double quotes is escaped using a backslash. The
24+
// backslash preceding the ‘!’ is not removed.
25+
//
26+
// -> This means that `!\n` cannot be safely expressed in `"`.
27+
//
28+
// Looking at the man page for Dash and ash the situation is similar.
29+
//
30+
// Now zsh requires that ‘}’, and ‘]’ are also enclosed in doublequotes or escaped
31+
//
32+
// Single quotes escape everything except a ‘'’
33+
//
34+
// There's one other gotcha - ‘~’ at the start of a string needs to be expanded
35+
// because people always expect that - of course if there is a special character before '/'
36+
// this is not going to work
37+
38+
const (
39+
tildePrefix = '~'
40+
needsEscape = " \t\n|&;()<>${}[]*?!\"'`\\"
41+
needsSingleQuote = "!\n"
42+
)
43+
44+
var doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`)
45+
var singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`)
46+
var singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`)
47+
48+
// ShellEscape will escape the provided string.
49+
// We can't just use go-shellquote here because our preferences for escaping differ from those in that we want:
50+
//
51+
// * If the string doesn't require any escaping just leave it as it is.
52+
// * If the string requires any escaping prefer double quote escaping
53+
// * If we have ! or newlines then we need to use single quote escaping
54+
func ShellEscape(toEscape string) string {
55+
if len(toEscape) == 0 {
56+
return toEscape
57+
}
58+
59+
start := 0
60+
61+
if toEscape[0] == tildePrefix {
62+
// We're in the forcibly non-escaped section...
63+
idx := strings.IndexRune(toEscape, '/')
64+
if idx < 0 {
65+
idx = len(toEscape)
66+
} else {
67+
idx++
68+
}
69+
if !strings.ContainsAny(toEscape[:idx], needsEscape) {
70+
// We'll assume that they intend ~ expansion to occur
71+
start = idx
72+
}
73+
}
74+
75+
// Now for simplicity we'll look at the rest of the string
76+
if !strings.ContainsAny(toEscape[start:], needsEscape) {
77+
return toEscape
78+
}
79+
80+
// OK we have to do some escaping
81+
sb := &strings.Builder{}
82+
_, _ = sb.WriteString(toEscape[:start])
83+
84+
// Do we have any characters which absolutely need to be within single quotes - that is simply ! or \n?
85+
if strings.ContainsAny(toEscape[start:], needsSingleQuote) {
86+
// We need to single quote escape.
87+
sb2 := &strings.Builder{}
88+
_, _ = sb2.WriteRune('\'')
89+
_, _ = singleQuoteEscaper.WriteString(sb2, toEscape[start:])
90+
_, _ = sb2.WriteRune('\'')
91+
_, _ = singleQuoteCoalescer.WriteString(sb, sb2.String())
92+
return sb.String()
93+
}
94+
95+
// OK we can just use " just escape the things that need escaping
96+
_, _ = sb.WriteRune('"')
97+
_, _ = doubleQuoteEscaper.WriteString(sb, toEscape[start:])
98+
_, _ = sb.WriteRune('"')
99+
return sb.String()
100+
}

modules/util/shellquote_test.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package util
6+
7+
import "testing"
8+
9+
func TestShellEscape(t *testing.T) {
10+
tests := []struct {
11+
name string
12+
toEscape string
13+
want string
14+
}{
15+
{
16+
"Simplest case - nothing to escape",
17+
"a/b/c/d",
18+
"a/b/c/d",
19+
}, {
20+
"Prefixed tilde - with normal stuff - should not escape",
21+
"~/src/go/gitea/gitea",
22+
"~/src/go/gitea/gitea",
23+
}, {
24+
"Typical windows path with spaces - should get doublequote escaped",
25+
`C:\Program Files\Gitea v1.13 - I like lots of spaces\gitea`,
26+
`"C:\\Program Files\\Gitea v1.13 - I like lots of spaces\\gitea"`,
27+
}, {
28+
"Forward-slashed windows path with spaces - should get doublequote escaped",
29+
"C:/Program Files/Gitea v1.13 - I like lots of spaces/gitea",
30+
`"C:/Program Files/Gitea v1.13 - I like lots of spaces/gitea"`,
31+
}, {
32+
"Prefixed tilde - but then a space filled path",
33+
"~git/Gitea v1.13/gitea",
34+
`~git/"Gitea v1.13/gitea"`,
35+
}, {
36+
"Bangs are unforutunately not predictable so need to be singlequoted",
37+
"C:/Program Files/Gitea!/gitea",
38+
`'C:/Program Files/Gitea!/gitea'`,
39+
}, {
40+
"Newlines are just irritating",
41+
"/home/git/Gitea\n\nWHY-WOULD-YOU-DO-THIS\n\nGitea/gitea",
42+
"'/home/git/Gitea\n\nWHY-WOULD-YOU-DO-THIS\n\nGitea/gitea'",
43+
}, {
44+
"Similarly we should nicely handle mutiple single quotes if we have to single-quote",
45+
"'!''!'''!''!'!'",
46+
`\''!'\'\''!'\'\'\''!'\'\''!'\''!'\'`,
47+
}, {
48+
"Double quote < ...",
49+
"~/<gitea",
50+
"~/\"<gitea\"",
51+
}, {
52+
"Double quote > ...",
53+
"~/gitea>",
54+
"~/\"gitea>\"",
55+
}, {
56+
"Double quote and escape $ ...",
57+
"~/$gitea",
58+
"~/\"\\$gitea\"",
59+
}, {
60+
"Double quote {...",
61+
"~/{gitea",
62+
"~/\"{gitea\"",
63+
}, {
64+
"Double quote }...",
65+
"~/gitea}",
66+
"~/\"gitea}\"",
67+
}, {
68+
"Double quote ()...",
69+
"~/(gitea)",
70+
"~/\"(gitea)\"",
71+
}, {
72+
"Double quote and escape `...",
73+
"~/gitea`",
74+
"~/\"gitea\\`\"",
75+
}, {
76+
"Double quotes can handle a number of things without having to escape them but not everything ...",
77+
"~/<gitea> ${gitea} `gitea` [gitea] (gitea) \"gitea\" \\gitea\\ 'gitea'",
78+
"~/\"<gitea> \\${gitea} \\`gitea\\` [gitea] (gitea) \\\"gitea\\\" \\\\gitea\\\\ 'gitea'\"",
79+
}, {
80+
"Single quotes don't need to escape except for '...",
81+
"~/<gitea> ${gitea} `gitea` (gitea) !gitea! \"gitea\" \\gitea\\ 'gitea'",
82+
"~/'<gitea> ${gitea} `gitea` (gitea) !gitea! \"gitea\" \\gitea\\ '\\''gitea'\\'",
83+
},
84+
}
85+
for _, tt := range tests {
86+
t.Run(tt.name, func(t *testing.T) {
87+
if got := ShellEscape(tt.toEscape); got != tt.want {
88+
t.Errorf("ShellEscape(%q):\nGot: %s\nWanted: %s", tt.toEscape, got, tt.want)
89+
}
90+
})
91+
}
92+
}

0 commit comments

Comments
 (0)