| 1 | package main |
| 2 | |
| 3 | import ( |
| 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 | |
| 57 | const shellUsage = `usage: valleyhook shell [flags] -- [-c COMMAND] |
| 58 | |
| 59 | The valley git user's login shell: derives the pushing principal from the |
| 60 | key sshd authenticated, drops the GIT_ environment a session arrived with, |
| 61 | refuses a push until valley-init has converged on this configuration, and |
| 62 | then runs git-shell. |
| 63 | |
| 64 | flags: |
| 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. |
| 78 | var tagged = regexp.MustCompile(`environment="VALLEY_PRINCIPAL=([^"]*)"`) |
| 79 | |
| 80 | func 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 | // The check worker (status/worker.go) tries a push refused |
| 117 | // with these words again soon, so keep them as they are. |
| 118 | fmt.Fprintln(stderr, "valley: pushes to this host are paused until valley-init converges on its configuration; fetching is open") |
| 119 | return 1 |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | env := sessionEnvironment(os.Environ()) |
| 124 | if principal := authenticatedPrincipal(os.Getenv("SSH_USER_AUTH"), keyFiles); principal != "" { |
| 125 | env = append(env, "VALLEY_PRINCIPAL="+principal) |
| 126 | } |
| 127 | |
| 128 | gitShell, err := gitShellPath() |
| 129 | if err != nil { |
| 130 | fmt.Fprintf(stderr, "valley: %v\n", err) |
| 131 | return 1 |
| 132 | } |
| 133 | err = syscall.Exec(gitShell, append([]string{"git-shell"}, rest...), env) |
| 134 | fmt.Fprintf(stderr, "valley: could not run git-shell: %v\n", err) |
| 135 | return 1 |
| 136 | } |
| 137 | |
| 138 | // isPush reports whether a command git-shell would run is receive-pack. |
| 139 | // git-shell reads "git" followed by whitespace as "git-", and runs a |
| 140 | // command whose name is followed by a space or nothing; anything that |
| 141 | // could read as receive-pack is treated as one. |
| 142 | func isPush(command string) bool { |
| 143 | if len(command) > 3 && strings.HasPrefix(command, "git") && strings.ContainsRune(" \t\n\r\v\f", rune(command[3])) { |
| 144 | command = "git-" + command[4:] |
| 145 | } |
| 146 | return strings.HasPrefix(command, "git-receive-pack") |
| 147 | } |
| 148 | |
| 149 | // hasConverged reads valley-init's record. Anything but a record naming |
| 150 | // the expected configuration — no file, an unreadable one, another |
| 151 | // configuration's — is not converged. |
| 152 | func hasConverged(path, expect string) bool { |
| 153 | f, err := os.Open(path) |
| 154 | if err != nil { |
| 155 | return false |
| 156 | } |
| 157 | defer f.Close() |
| 158 | line, err := bufio.NewReaderSize(io.LimitReader(f, 256), 256).ReadString('\n') |
| 159 | if err != nil && !errors.Is(err, io.EOF) { |
| 160 | return false |
| 161 | } |
| 162 | return strings.TrimSpace(line) == expect |
| 163 | } |
| 164 | |
| 165 | // sessionEnvironment is the session's environment less every GIT_ |
| 166 | // variable and any principal it arrived with. |
| 167 | func sessionEnvironment(inherited []string) []string { |
| 168 | var env []string |
| 169 | for _, kv := range inherited { |
| 170 | name, _, _ := strings.Cut(kv, "=") |
| 171 | if strings.HasPrefix(name, "GIT_") || name == "VALLEY_PRINCIPAL" { |
| 172 | continue |
| 173 | } |
| 174 | env = append(env, kv) |
| 175 | } |
| 176 | return env |
| 177 | } |
| 178 | |
| 179 | // authenticatedPrincipal is the principal the authenticated key acts as: |
| 180 | // the tag on the first entry naming that key, in the files sshd read, in |
| 181 | // order. A session sshd names no key for — no SSH_USER_AUTH, or no public |
| 182 | // key in it — and a key no file names, act as nobody. |
| 183 | func authenticatedPrincipal(authFile string, keyFiles []string) string { |
| 184 | key := authenticatedKey(authFile) |
| 185 | if key == "" { |
| 186 | return "" |
| 187 | } |
| 188 | for _, path := range keyFiles { |
| 189 | data, err := os.ReadFile(path) |
| 190 | if err != nil { |
| 191 | continue |
| 192 | } |
| 193 | for _, line := range strings.Split(string(data), "\n") { |
| 194 | if keyBlob(line) != key { |
| 195 | continue |
| 196 | } |
| 197 | if m := tagged.FindStringSubmatch(line); m != nil { |
| 198 | return m[1] |
| 199 | } |
| 200 | return "" |
| 201 | } |
| 202 | } |
| 203 | return "" |
| 204 | } |
| 205 | |
| 206 | // authenticatedKey is the public key sshd says authenticated the session. |
| 207 | // ExposeAuthInfo writes one line per method that succeeded; a public key |
| 208 | // line is "publickey <type> <base64>". Two public keys naming different |
| 209 | // keys are refused as no key at all. |
| 210 | func authenticatedKey(path string) string { |
| 211 | if path == "" { |
| 212 | return "" |
| 213 | } |
| 214 | f, err := os.Open(path) |
| 215 | if err != nil { |
| 216 | return "" |
| 217 | } |
| 218 | defer f.Close() |
| 219 | data, err := io.ReadAll(io.LimitReader(f, 64<<10)) |
| 220 | if err != nil { |
| 221 | return "" |
| 222 | } |
| 223 | found := "" |
| 224 | for _, line := range strings.Split(string(data), "\n") { |
| 225 | fields := strings.Fields(line) |
| 226 | if len(fields) < 3 || fields[0] != "publickey" { |
| 227 | continue |
| 228 | } |
| 229 | if found != "" && found != fields[2] { |
| 230 | return "" |
| 231 | } |
| 232 | found = fields[2] |
| 233 | } |
| 234 | return found |
| 235 | } |
| 236 | |
| 237 | // keyBlob is the base64 key in an authorized_keys line: the field after |
| 238 | // the first one naming a key type. |
| 239 | func keyBlob(line string) string { |
| 240 | fields := strings.Fields(line) |
| 241 | for i := 0; i+1 < len(fields); i++ { |
| 242 | f := fields[i] |
| 243 | if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") { |
| 244 | return fields[i+1] |
| 245 | } |
| 246 | } |
| 247 | return "" |
| 248 | } |
| 249 | |
| 250 | // gitShellPath is the git-shell beside the git this program was built |
| 251 | // with. |
| 252 | func gitShellPath() (string, error) { |
| 253 | if filepath.IsAbs(gitProgram) { |
| 254 | return filepath.Join(filepath.Dir(gitProgram), "git-shell"), nil |
| 255 | } |
| 256 | return exec.LookPath("git-shell") |
| 257 | } |
| 258 | |
| 259 | // telemetryCommand answers a telemetry command: refused unless the host |
| 260 | // serves telemetry, the session's key names a principal, the command |
| 261 | // parses, and the principal holds the grant its operation needs; then |
| 262 | // relayed to the collector as one request line, followed for a report by |
| 263 | // the records on standard input, with the collector's answer copied back. |
| 264 | // It exits 0 only when that answer ended. |
| 265 | func telemetryCommand(cmd, principal, socket, grantsFile string, stdin io.Reader, stdout, stderr io.Writer) int { |
| 266 | if socket == "" || grantsFile == "" { |
| 267 | fmt.Fprintln(stderr, "valley: this host serves no telemetry") |
| 268 | return 1 |
| 269 | } |
| 270 | if principal == "" { |
| 271 | fmt.Fprintln(stderr, "valley: telemetry is for a key that names a principal") |
| 272 | return 1 |
| 273 | } |
| 274 | req, err := telemetry.ParseCommand(cmd) |
| 275 | if err != nil { |
| 276 | fmt.Fprintf(stderr, "valley: %v\n", err) |
| 277 | return 2 |
| 278 | } |
| 279 | req.Principal = principal |
| 280 | g := grants{} |
| 281 | if err := g.read(grantsFile); err != nil { |
| 282 | fmt.Fprintf(stderr, "valley: the telemetry grants do not read: %v\n", err) |
| 283 | return 1 |
| 284 | } |
| 285 | if !g[principal][req.Grant()] { |
| 286 | fmt.Fprintf(stderr, "valley: %s does not hold the telemetry %s grant\n", principal, req.Grant()) |
| 287 | return 1 |
| 288 | } |
| 289 | conn, err := net.DialTimeout("unix", socket, 5*time.Second) |
| 290 | if err != nil { |
| 291 | fmt.Fprintf(stderr, "valley: the telemetry collector is not answering: %v\n", err) |
| 292 | return 1 |
| 293 | } |
| 294 | defer conn.Close() |
| 295 | line, err := json.Marshal(req) |
| 296 | if err != nil { |
| 297 | return 1 |
| 298 | } |
| 299 | conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) |
| 300 | if _, err := conn.Write(append(line, '\n')); err != nil { |
| 301 | fmt.Fprintf(stderr, "valley: the telemetry collector is not answering: %v\n", err) |
| 302 | return 1 |
| 303 | } |
| 304 | conn.SetWriteDeadline(time.Time{}) |
| 305 | uc := conn.(*net.UnixConn) |
| 306 | if req.Op == telemetry.OpReport { |
| 307 | go func() { |
| 308 | io.Copy(conn, io.LimitReader(stdin, telemetry.MaxReportBytes+1)) |
| 309 | uc.CloseWrite() |
| 310 | }() |
| 311 | } else { |
| 312 | uc.CloseWrite() |
| 313 | } |
| 314 | tail := &lastBytes{} |
| 315 | if _, err := io.Copy(io.MultiWriter(stdout, tail), conn); err != nil { |
| 316 | return 1 |
| 317 | } |
| 318 | // The collector's answer ends with an end line, and only an answer |
| 319 | // that did exits 0: a refusal, an error, or a collector that stopped |
| 320 | // half way does not read as success to the client. |
| 321 | if !strings.Contains(string(tail.b), `"kind":"end"`) { |
| 322 | return 1 |
| 323 | } |
| 324 | return 0 |
| 325 | } |
| 326 | |
| 327 | // lastBytes keeps the last bytes written through it. |
| 328 | type lastBytes struct{ b []byte } |
| 329 | |
| 330 | func (l *lastBytes) Write(p []byte) (int, error) { |
| 331 | l.b = append(l.b, p...) |
| 332 | if len(l.b) > 512 { |
| 333 | l.b = l.b[len(l.b)-512:] |
| 334 | } |
| 335 | return len(p), nil |
| 336 | } |