gunk-dev/the-valley

shell.go

source5f0229dc1066main's published tip history
7.4 KiB
1package main
2
3import (
4 "bufio"
5 "errors"
6 "flag"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "syscall"
15)
16
17// The git user's login shell. sshd runs it for every session as
18// `shell -c "<the client's command>"`, and it runs git-shell after three
19// things that make the push boundary hold whatever sshd was configured to
20// pass through.
21//
22// The principal is derived here, from the key sshd authenticated, and from
23// nowhere else. With ExposeAuthInfo on, sshd names that key in the file
24// SSH_USER_AUTH points at. The key is looked up in the same files sshd
25// authorized it from, in the same order, and the principal is the tag on
26// the first entry naming it. A VALLEY_PRINCIPAL the session arrived with is
27// dropped, so no client environment, sshd setting or ~/.ssh/environment can
28// name a principal.
29//
30// Every GIT_ variable the session arrived with is dropped too. git reads
31// configuration, hook locations and object directories from them, and none
32// of that is the client's to choose.
33//
34// A push is refused until the host has converged. valley-init records the
35// configuration it converged on in a file only it writes, and a push is let
36// through only while that record names the configuration this shell was
37// rendered for. A valley-init that failed, or has not yet run since a
38// switch, therefore leaves no write path open, whatever hooks the
39// repositories hold. The operator can hold pushes too, for as long as a
40// file the shell is told about exists, whatever valley-init has recorded.
41// Fetches stay open either way.
42
43const shellUsage = `usage: valleyhook shell [flags] -- [-c COMMAND]
44
45The valley git user's login shell: derives the pushing principal from the
46key sshd authenticated, drops the GIT_ environment a session arrived with,
47refuses a push until valley-init has converged on this configuration, and
48then runs git-shell.
49
50flags:
51 --converged FILE the record valley-init writes when it converges
52 --expect ID the configuration that record has to name
53 --hold FILE a file whose existence holds every push
54 --authorized-keys FILE a file sshd authorizes the git user's keys from, in
55 the order sshd reads them. Repeatable.
56`
57
58// tagged is the principal option on a key's entry.
59var tagged = regexp.MustCompile(`environment="VALLEY_PRINCIPAL=([^"]*)"`)
60
61func shell(args []string, stderr io.Writer) int {
62 fs := flag.NewFlagSet("shell", flag.ContinueOnError)
63 fs.SetOutput(stderr)
64 fs.Usage = func() { fmt.Fprint(stderr, shellUsage) }
65 converged := fs.String("converged", "", "the record valley-init writes when it converges")
66 expect := fs.String("expect", "", "the configuration that record has to name")
67 hold := fs.String("hold", "", "a file whose existence holds every push")
68 var keyFiles []string
69 fs.Func("authorized-keys", "a file the git user's keys are authorized from; repeatable", func(path string) error {
70 keyFiles = append(keyFiles, path)
71 return nil
72 })
73 if err := fs.Parse(args); err != nil {
74 return 2
75 }
76 if *converged == "" || *expect == "" {
77 fmt.Fprint(stderr, shellUsage)
78 return 2
79 }
80 rest := fs.Args()
81
82 if len(rest) == 2 && rest[0] == "-c" && isPush(rest[1]) {
83 if *hold != "" {
84 if _, err := os.Lstat(*hold); !errors.Is(err, os.ErrNotExist) {
85 fmt.Fprintln(stderr, "valley: pushes to this host are held by its operator; fetching is open")
86 return 1
87 }
88 }
89 if !hasConverged(*converged, *expect) {
90 fmt.Fprintln(stderr, "valley: pushes to this host are paused until valley-init converges on its configuration; fetching is open")
91 return 1
92 }
93 }
94
95 env := sessionEnvironment(os.Environ())
96 if principal := authenticatedPrincipal(os.Getenv("SSH_USER_AUTH"), keyFiles); principal != "" {
97 env = append(env, "VALLEY_PRINCIPAL="+principal)
98 }
99
100 gitShell, err := gitShellPath()
101 if err != nil {
102 fmt.Fprintf(stderr, "valley: %v\n", err)
103 return 1
104 }
105 err = syscall.Exec(gitShell, append([]string{"git-shell"}, rest...), env)
106 fmt.Fprintf(stderr, "valley: could not run git-shell: %v\n", err)
107 return 1
108}
109
110// isPush reports whether a command git-shell would run is receive-pack.
111// git-shell reads "git" followed by whitespace as "git-", and runs a
112// command whose name is followed by a space or nothing; anything that
113// could read as receive-pack is treated as one.
114func isPush(command string) bool {
115 if len(command) > 3 && strings.HasPrefix(command, "git") && strings.ContainsRune(" \t\n\r\v\f", rune(command[3])) {
116 command = "git-" + command[4:]
117 }
118 return strings.HasPrefix(command, "git-receive-pack")
119}
120
121// hasConverged reads valley-init's record. Anything but a record naming
122// the expected configuration — no file, an unreadable one, another
123// configuration's — is not converged.
124func hasConverged(path, expect string) bool {
125 f, err := os.Open(path)
126 if err != nil {
127 return false
128 }
129 defer f.Close()
130 line, err := bufio.NewReaderSize(io.LimitReader(f, 256), 256).ReadString('\n')
131 if err != nil && !errors.Is(err, io.EOF) {
132 return false
133 }
134 return strings.TrimSpace(line) == expect
135}
136
137// sessionEnvironment is the session's environment less every GIT_
138// variable and any principal it arrived with.
139func sessionEnvironment(inherited []string) []string {
140 var env []string
141 for _, kv := range inherited {
142 name, _, _ := strings.Cut(kv, "=")
143 if strings.HasPrefix(name, "GIT_") || name == "VALLEY_PRINCIPAL" {
144 continue
145 }
146 env = append(env, kv)
147 }
148 return env
149}
150
151// authenticatedPrincipal is the principal the authenticated key acts as:
152// the tag on the first entry naming that key, in the files sshd read, in
153// order. A session sshd names no key for — no SSH_USER_AUTH, or no public
154// key in it — and a key no file names, act as nobody.
155func authenticatedPrincipal(authFile string, keyFiles []string) string {
156 key := authenticatedKey(authFile)
157 if key == "" {
158 return ""
159 }
160 for _, path := range keyFiles {
161 data, err := os.ReadFile(path)
162 if err != nil {
163 continue
164 }
165 for _, line := range strings.Split(string(data), "\n") {
166 if keyBlob(line) != key {
167 continue
168 }
169 if m := tagged.FindStringSubmatch(line); m != nil {
170 return m[1]
171 }
172 return ""
173 }
174 }
175 return ""
176}
177
178// authenticatedKey is the public key sshd says authenticated the session.
179// ExposeAuthInfo writes one line per method that succeeded; a public key
180// line is "publickey <type> <base64>". Two public keys naming different
181// keys are refused as no key at all.
182func authenticatedKey(path string) string {
183 if path == "" {
184 return ""
185 }
186 f, err := os.Open(path)
187 if err != nil {
188 return ""
189 }
190 defer f.Close()
191 data, err := io.ReadAll(io.LimitReader(f, 64<<10))
192 if err != nil {
193 return ""
194 }
195 found := ""
196 for _, line := range strings.Split(string(data), "\n") {
197 fields := strings.Fields(line)
198 if len(fields) < 3 || fields[0] != "publickey" {
199 continue
200 }
201 if found != "" && found != fields[2] {
202 return ""
203 }
204 found = fields[2]
205 }
206 return found
207}
208
209// keyBlob is the base64 key in an authorized_keys line: the field after
210// the first one naming a key type.
211func keyBlob(line string) string {
212 fields := strings.Fields(line)
213 for i := 0; i+1 < len(fields); i++ {
214 f := fields[i]
215 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
216 return fields[i+1]
217 }
218 }
219 return ""
220}
221
222// gitShellPath is the git-shell beside the git this program was built
223// with.
224func gitShellPath() (string, error) {
225 if filepath.IsAbs(gitProgram) {
226 return filepath.Join(filepath.Dir(gitProgram), "git-shell"), nil
227 }
228 return exec.LookPath("git-shell")
229}