gunk-dev/the-valley

shell.go

sourcef69adc17996fmain's published tip history
11.1 KiB
1package main
2
3import (
4 "bufio"
5 "encoding/json"
6 "errors"
7 "flag"
8 "fmt"
9 "io"
10 "net"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "strings"
16 "syscall"
17 "time"
18
19 "the-valley/telemetry"
20)
21
22// The git user's login shell. sshd runs it for every session as
23// `shell -c "<the client's command>"`, and it runs git-shell after three
24// things that make the push boundary hold whatever sshd was configured to
25// pass through.
26//
27// The principal is derived here, from the key sshd authenticated, and from
28// nowhere else. With ExposeAuthInfo on, sshd names that key in the file
29// SSH_USER_AUTH points at. The key is looked up in the same files sshd
30// authorized it from, in the same order, and the principal is the tag on
31// the first entry naming it. A VALLEY_PRINCIPAL the session arrived with is
32// dropped, so no client environment, sshd setting or ~/.ssh/environment can
33// name a principal.
34//
35// Every GIT_ variable the session arrived with is dropped too. git reads
36// configuration, hook locations and object directories from them, and none
37// of that is the client's to choose.
38//
39// A push is refused until the host has converged. valley-init records the
40// configuration it converged on in a file only it writes, and a push is let
41// through only while that record names the configuration this shell was
42// rendered for. A valley-init that failed, or has not yet run since a
43// switch, therefore leaves no write path open, whatever hooks the
44// repositories hold. The operator can hold pushes too, for as long as a
45// file the shell is told about exists, whatever valley-init has recorded.
46// Fetches stay open either way.
47//
48// One other command is the shell's own: the telemetry command
49// (../telemetry), which a session with the observe or report grant uses to
50// read the host's diagnostics or send its own. The shell parses it whole
51// against the command's closed grammar, checks the grant in the telemetry
52// grants file, and passes the collector one request line naming the
53// principal it derived. Nothing of the command reaches git-shell or any
54// other program, refused or not, and neither a hold nor a missing
55// convergence stops it: diagnosing a paused host is when it is needed.
56
57const shellUsage = `usage: valleyhook shell [flags] -- [-c COMMAND]
58
59The valley git user's login shell: derives the pushing principal from the
60key sshd authenticated, drops the GIT_ environment a session arrived with,
61refuses a push until valley-init has converged on this configuration, and
62then runs git-shell.
63
64flags:
65 --converged FILE the record valley-init writes when it converges
66 --expect ID the configuration that record has to name
67 --hold FILE a file whose existence holds every push
68 --authorized-keys FILE a file sshd authorizes the git user's keys from, in
69 the order sshd reads them. Repeatable.
70 --telemetry-socket PATH
71 the telemetry collector's socket; without it, the
72 telemetry command is refused
73 --telemetry-grants FILE
74 who holds the observe and report grants
75`
76
77// tagged is the principal option on a key's entry.
78var tagged = regexp.MustCompile(`environment="VALLEY_PRINCIPAL=([^"]*)"`)
79
80func shell(args []string, stderr io.Writer) int {
81 fs := flag.NewFlagSet("shell", flag.ContinueOnError)
82 fs.SetOutput(stderr)
83 fs.Usage = func() { fmt.Fprint(stderr, shellUsage) }
84 converged := fs.String("converged", "", "the record valley-init writes when it converges")
85 expect := fs.String("expect", "", "the configuration that record has to name")
86 hold := fs.String("hold", "", "a file whose existence holds every push")
87 telemetrySocket := fs.String("telemetry-socket", "", "the telemetry collector's socket")
88 telemetryGrants := fs.String("telemetry-grants", "", "the telemetry grants")
89 var keyFiles []string
90 fs.Func("authorized-keys", "a file the git user's keys are authorized from; repeatable", func(path string) error {
91 keyFiles = append(keyFiles, path)
92 return nil
93 })
94 if err := fs.Parse(args); err != nil {
95 return 2
96 }
97 if *converged == "" || *expect == "" {
98 fmt.Fprint(stderr, shellUsage)
99 return 2
100 }
101 rest := fs.Args()
102
103 if len(rest) == 2 && rest[0] == "-c" && telemetry.IsCommand(rest[1]) {
104 principal := authenticatedPrincipal(os.Getenv("SSH_USER_AUTH"), keyFiles)
105 return telemetryCommand(rest[1], principal, *telemetrySocket, *telemetryGrants, os.Stdin, os.Stdout, stderr)
106 }
107
108 if len(rest) == 2 && rest[0] == "-c" && isPush(rest[1]) {
109 if *hold != "" {
110 if _, err := os.Lstat(*hold); !errors.Is(err, os.ErrNotExist) {
111 fmt.Fprintln(stderr, "valley: pushes to this host are held by its operator; fetching is open")
112 return 1
113 }
114 }
115 if !hasConverged(*converged, *expect) {
116 fmt.Fprintln(stderr, "valley: pushes to this host are paused until valley-init converges on its configuration; fetching is open")
117 return 1
118 }
119 }
120
121 env := sessionEnvironment(os.Environ())
122 if principal := authenticatedPrincipal(os.Getenv("SSH_USER_AUTH"), keyFiles); principal != "" {
123 env = append(env, "VALLEY_PRINCIPAL="+principal)
124 }
125
126 gitShell, err := gitShellPath()
127 if err != nil {
128 fmt.Fprintf(stderr, "valley: %v\n", err)
129 return 1
130 }
131 err = syscall.Exec(gitShell, append([]string{"git-shell"}, rest...), env)
132 fmt.Fprintf(stderr, "valley: could not run git-shell: %v\n", err)
133 return 1
134}
135
136// isPush reports whether a command git-shell would run is receive-pack.
137// git-shell reads "git" followed by whitespace as "git-", and runs a
138// command whose name is followed by a space or nothing; anything that
139// could read as receive-pack is treated as one.
140func isPush(command string) bool {
141 if len(command) > 3 && strings.HasPrefix(command, "git") && strings.ContainsRune(" \t\n\r\v\f", rune(command[3])) {
142 command = "git-" + command[4:]
143 }
144 return strings.HasPrefix(command, "git-receive-pack")
145}
146
147// hasConverged reads valley-init's record. Anything but a record naming
148// the expected configuration — no file, an unreadable one, another
149// configuration's — is not converged.
150func hasConverged(path, expect string) bool {
151 f, err := os.Open(path)
152 if err != nil {
153 return false
154 }
155 defer f.Close()
156 line, err := bufio.NewReaderSize(io.LimitReader(f, 256), 256).ReadString('\n')
157 if err != nil && !errors.Is(err, io.EOF) {
158 return false
159 }
160 return strings.TrimSpace(line) == expect
161}
162
163// sessionEnvironment is the session's environment less every GIT_
164// variable and any principal it arrived with.
165func sessionEnvironment(inherited []string) []string {
166 var env []string
167 for _, kv := range inherited {
168 name, _, _ := strings.Cut(kv, "=")
169 if strings.HasPrefix(name, "GIT_") || name == "VALLEY_PRINCIPAL" {
170 continue
171 }
172 env = append(env, kv)
173 }
174 return env
175}
176
177// authenticatedPrincipal is the principal the authenticated key acts as:
178// the tag on the first entry naming that key, in the files sshd read, in
179// order. A session sshd names no key for — no SSH_USER_AUTH, or no public
180// key in it — and a key no file names, act as nobody.
181func authenticatedPrincipal(authFile string, keyFiles []string) string {
182 key := authenticatedKey(authFile)
183 if key == "" {
184 return ""
185 }
186 for _, path := range keyFiles {
187 data, err := os.ReadFile(path)
188 if err != nil {
189 continue
190 }
191 for _, line := range strings.Split(string(data), "\n") {
192 if keyBlob(line) != key {
193 continue
194 }
195 if m := tagged.FindStringSubmatch(line); m != nil {
196 return m[1]
197 }
198 return ""
199 }
200 }
201 return ""
202}
203
204// authenticatedKey is the public key sshd says authenticated the session.
205// ExposeAuthInfo writes one line per method that succeeded; a public key
206// line is "publickey <type> <base64>". Two public keys naming different
207// keys are refused as no key at all.
208func authenticatedKey(path string) string {
209 if path == "" {
210 return ""
211 }
212 f, err := os.Open(path)
213 if err != nil {
214 return ""
215 }
216 defer f.Close()
217 data, err := io.ReadAll(io.LimitReader(f, 64<<10))
218 if err != nil {
219 return ""
220 }
221 found := ""
222 for _, line := range strings.Split(string(data), "\n") {
223 fields := strings.Fields(line)
224 if len(fields) < 3 || fields[0] != "publickey" {
225 continue
226 }
227 if found != "" && found != fields[2] {
228 return ""
229 }
230 found = fields[2]
231 }
232 return found
233}
234
235// keyBlob is the base64 key in an authorized_keys line: the field after
236// the first one naming a key type.
237func keyBlob(line string) string {
238 fields := strings.Fields(line)
239 for i := 0; i+1 < len(fields); i++ {
240 f := fields[i]
241 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
242 return fields[i+1]
243 }
244 }
245 return ""
246}
247
248// gitShellPath is the git-shell beside the git this program was built
249// with.
250func gitShellPath() (string, error) {
251 if filepath.IsAbs(gitProgram) {
252 return filepath.Join(filepath.Dir(gitProgram), "git-shell"), nil
253 }
254 return exec.LookPath("git-shell")
255}
256
257// telemetryCommand answers a telemetry command: refused unless the host
258// serves telemetry, the session's key names a principal, the command
259// parses, and the principal holds the grant its operation needs; then
260// relayed to the collector as one request line, followed for a report by
261// the records on standard input, with the collector's answer copied back.
262// It exits 0 only when that answer ended.
263func telemetryCommand(cmd, principal, socket, grantsFile string, stdin io.Reader, stdout, stderr io.Writer) int {
264 if socket == "" || grantsFile == "" {
265 fmt.Fprintln(stderr, "valley: this host serves no telemetry")
266 return 1
267 }
268 if principal == "" {
269 fmt.Fprintln(stderr, "valley: telemetry is for a key that names a principal")
270 return 1
271 }
272 req, err := telemetry.ParseCommand(cmd)
273 if err != nil {
274 fmt.Fprintf(stderr, "valley: %v\n", err)
275 return 2
276 }
277 req.Principal = principal
278 g := grants{}
279 if err := g.read(grantsFile); err != nil {
280 fmt.Fprintf(stderr, "valley: the telemetry grants do not read: %v\n", err)
281 return 1
282 }
283 if !g[principal][req.Grant()] {
284 fmt.Fprintf(stderr, "valley: %s does not hold the telemetry %s grant\n", principal, req.Grant())
285 return 1
286 }
287 conn, err := net.DialTimeout("unix", socket, 5*time.Second)
288 if err != nil {
289 fmt.Fprintf(stderr, "valley: the telemetry collector is not answering: %v\n", err)
290 return 1
291 }
292 defer conn.Close()
293 line, err := json.Marshal(req)
294 if err != nil {
295 return 1
296 }
297 conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
298 if _, err := conn.Write(append(line, '\n')); err != nil {
299 fmt.Fprintf(stderr, "valley: the telemetry collector is not answering: %v\n", err)
300 return 1
301 }
302 conn.SetWriteDeadline(time.Time{})
303 uc := conn.(*net.UnixConn)
304 if req.Op == telemetry.OpReport {
305 go func() {
306 io.Copy(conn, io.LimitReader(stdin, telemetry.MaxReportBytes+1))
307 uc.CloseWrite()
308 }()
309 } else {
310 uc.CloseWrite()
311 }
312 tail := &lastBytes{}
313 if _, err := io.Copy(io.MultiWriter(stdout, tail), conn); err != nil {
314 return 1
315 }
316 // The collector's answer ends with an end line, and only an answer
317 // that did exits 0: a refusal, an error, or a collector that stopped
318 // half way does not read as success to the client.
319 if !strings.Contains(string(tail.b), `"kind":"end"`) {
320 return 1
321 }
322 return 0
323}
324
325// lastBytes keeps the last bytes written through it.
326type lastBytes struct{ b []byte }
327
328func (l *lastBytes) Write(p []byte) (int, error) {
329 l.b = append(l.b, p...)
330 if len(l.b) > 512 {
331 l.b = l.b[len(l.b)-512:]
332 }
333 return len(p), nil
334}