Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Mint a one-use session for each front door connection

e075258f0e4456f654680eeb7ba246e80d6c9a97 · Keenan Nemetz · 16d ago · parent 5ff8dfc9

Mint a one-use session for each front door connection

sshd can authenticate a Vole key and then hand the request to something else.
This adds the two ends of that handoff, plus the capability that crosses it.

`vole ssh-authorized-keys` is sshd's AuthorizedKeysCommand. It opens the roster
and the run credentials without running a schema or a migration — a write on the
path sshd takes before it knows who is connecting is a write nobody watches — and
for an active key prints the client's key back with `restrict,command=` and a
token. An unknown key, a retired account, and an expired credential all produce
no line and no row, so sshd refuses before any Vole process runs.

The token is 256 random bits, stored only as a SHA-256 hash, good for one use and
sixty seconds, and bound to the client endpoint sshd reports for the connection.
That binding is what closes the one weakness of a capability in argv: `/proc`
lets another local user read the forced command, but not spend it from their own
connection. A token that turns up at the wrong endpoint is deleted, not left for
the rest of its minute.

`vole ssh-exec` is the forced command, and `vole ssh-shell` is the account's
login shell. sshd runs a forced command *through* the login shell with `-c`, so a
shell that refuses everything would break every command it fronts: this one
recognises the single line ssh-authorized-keys printed, execs it directly, and
refuses anything else, including an interactive session. Generating that line
therefore refuses a config path containing whitespace rather than quoting it into
shell syntax.

The wire between them is `internal/sshwire`: one hello, one accept or refusal,
then length-prefixed stdin, stdout, stderr and exit frames over the Unix socket,
so the streams stay separate and backpressure is a blocked writer rather than a
buffer. `ssh_socket` is where that socket lives; it is absolute-only because
sshd's working directory is not the instance's.

The socket listener, the token sweeper, and the configuration that enables the
mode are #305. Until then nothing here runs unless sshd is wired to it.

cmd/vole/ssh_test.go +529

@@ -0,0 +1,529 @@
1 package main
2
3 // The front door's two commands are plumbing, but they are the plumbing that
4 // decides who gets a session. These tests cover the three answers
5 // ssh-authorized-keys must give — one line, no line, and a refusal that does not
6 // become a session — and the binary itself, because the forced command's exit
7 // status and environment are the contract sshd sees.
8
9 import (
10 "bytes"
11 "crypto/ed25519"
12 "crypto/rand"
13 "database/sql"
14 "encoding/json"
15 "errors"
16 "fmt"
17 "net"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "strings"
22 "testing"
23 "time"
24
25 xssh "golang.org/x/crypto/ssh"
26
27 "rodent.software/vole/ci/runs"
28 "rodent.software/vole/forge/config"
29 "rodent.software/vole/forge/identity"
30 "rodent.software/vole/forge/sshsession"
31 "rodent.software/vole/internal/sshwire"
32 )
33
34 // testKey is one key as sshd presents it: a fingerprint, and the type and body
35 // halves it splits the key into.
36 type testKey struct {
37 fp, typ, body string
38 }
39
40 func newTestKey(t *testing.T) testKey {
41 t.Helper()
42 pub, _, err := ed25519.GenerateKey(rand.Reader)
43 if err != nil {
44 t.Fatal(err)
45 }
46 sshPub, err := xssh.NewPublicKey(pub)
47 if err != nil {
48 t.Fatal(err)
49 }
50 fields := strings.Fields(string(xssh.MarshalAuthorizedKey(sshPub)))
51 if len(fields) != 2 {
52 t.Fatalf("unexpected key line: %v", fields)
53 }
54 return testKey{fp: xssh.FingerprintSHA256(sshPub), typ: fields[0], body: fields[1]}
55 }
56
57 // line is the canonical authorized_keys line for the key, which is what
58 // ssh-authorized-keys has to print back.
59 func (k testKey) line() string { return k.typ + " " + k.body }
60
61 type sshFixture struct {
62 cfgPath string
63 dataDir string
64 instDB string
65 runsDB string
66 account string
67 key testKey
68 }
69
70 func newSSHFixture(t *testing.T) *sshFixture {
71 t.Helper()
72 root := filepath.Join(t.TempDir(), "vole")
73 captureStdout(t, func() error { return cmdInit([]string{"--dir", root}) })
74 cfgPath := filepath.Join(root, "vole.toml")
75 cfg, err := config.Load(cfgPath)
76 if err != nil {
77 t.Fatalf("load config: %v", err)
78 }
79 f := &sshFixture{
80 cfgPath: cfgPath,
81 dataDir: cfg.DataDir,
82 instDB: cfg.InstanceDB(),
83 runsDB: cfg.RunsDB(),
84 account: "alice",
85 key: newTestKey(t),
86 }
87 keyFile := filepath.Join(t.TempDir(), "id.pub")
88 if err := os.WriteFile(keyFile, []byte(f.key.line()+"\n"), 0o600); err != nil {
89 t.Fatal(err)
90 }
91 captureStdout(t, func() error {
92 return cmdAccount([]string{"create", f.account, "--key", keyFile, "--config", cfgPath})
93 })
94 return f
95 }
96
97 // connection is what sshd reports for this test's client, and what the token is
98 // bound to.
99 const connection = "203.0.113.5 4242 192.0.2.10 22"
100
101 func (f *sshFixture) authorizedKeys(t *testing.T, k testKey) string {
102 t.Helper()
103 return captureStdout(t, func() error {
104 return cmdSSHAuthorizedKeys([]string{
105 "--fingerprint", k.fp,
106 "--type", k.typ,
107 "--key", k.body,
108 "--connection", connection,
109 "--config", f.cfgPath,
110 })
111 })
112 }
113
114 // tokenCount reads the token table directly, which is how a test can assert that
115 // a refused key minted nothing at all.
116 func tokenCount(t *testing.T, path string) int {
117 t.Helper()
118 db, err := sql.Open("sqlite3", path)
119 if err != nil {
120 t.Fatal(err)
121 }
122 defer db.Close()
123 var n int
124 if err := db.QueryRow(`SELECT count(*) FROM ssh_sessions`).Scan(&n); err != nil {
125 if strings.Contains(err.Error(), "no such table") {
126 return 0
127 }
128 t.Fatal(err)
129 }
130 return n
131 }
132
133 func TestAuthorizedKeysPrintsTheKeyWithOneToken(t *testing.T) {
134 f := newSSHFixture(t)
135 if n := tokenCount(t, f.instDB); n != 0 {
136 t.Fatalf("%d tokens before any key was offered", n)
137 }
138
139 out := f.authorizedKeys(t, f.key)
140 if strings.Count(strings.TrimSpace(out), "\n") != 0 {
141 t.Fatalf("more than one line:\n%s", out)
142 }
143 line := strings.TrimSpace(out)
144 if !strings.HasPrefix(line, `restrict,command="`) {
145 t.Errorf("the options do not disable forwarding and PTY: %q", line)
146 }
147 if !strings.HasSuffix(line, f.key.line()) {
148 t.Errorf("the line does not end with the client's key: %q", line)
149 }
150
151 // The forced command has to name this binary, the config it will read, and
152 // the token. It is rebuilt from sshd's halves, so the key itself is canonical.
153 rest := strings.TrimPrefix(line, `restrict,command="`)
154 forced, _, ok := strings.Cut(rest, `" `)
155 if !ok {
156 t.Fatalf("the options are not closed: %q", line)
157 }
158 cfgAbs, err := filepath.Abs(f.cfgPath)
159 if err != nil {
160 t.Fatal(err)
161 }
162 if !strings.Contains(forced, " ssh-exec ") || !strings.Contains(forced, "--config "+cfgAbs+" ") {
163 t.Errorf("the forced command does not run ssh-exec with this config: %q", forced)
164 }
165 _, token, ok := strings.Cut(forced, "--session ")
166 if !ok || token == "" {
167 t.Fatalf("the forced command carries no session: %q", forced)
168 }
169
170 store, err := sshsession.Open(f.instDB)
171 if err != nil {
172 t.Fatal(err)
173 }
174 defer store.Close()
175 sess, err := store.Consume(token, connection, time.Now().UTC())
176 if err != nil {
177 t.Fatalf("consume: %v", err)
178 }
179 if sess == nil || sess.Account != f.account || sess.Credential != "" {
180 t.Fatalf("the token opened %+v, want an account session for %s", sess, f.account)
181 }
182 if again, err := store.Consume(token, connection, time.Now().UTC()); err != nil || again != nil {
183 t.Fatalf("the token worked twice: %+v, %v", again, err)
184 }
185 }
186
187 func TestAuthorizedKeysPrintsNothingForAKeyItCannotUse(t *testing.T) {
188 f := newSSHFixture(t)
189 before := tokenCount(t, f.instDB)
190
191 if out := f.authorizedKeys(t, newTestKey(t)); out != "" {
192 t.Errorf("an unknown key produced a line: %q", out)
193 }
194
195 // A retired account keeps its keys in the roster but must not authenticate.
196 // Retiring through the store rather than the CLI keeps this test to what it
197 // is about; the CLI's own retirement is covered by the admin tests.
198 ident, err := identity.OpenReader(f.instDB)
199 if err != nil {
200 t.Fatal(err)
201 }
202 ident.AuditPath = filepath.Join(f.dataDir, "audit.log")
203 if _, err := ident.Retire(f.account, "test"); err != nil {
204 t.Fatalf("retire: %v", err)
205 }
206 ident.Close()
207 if out := f.authorizedKeys(t, f.key); out != "" {
208 t.Errorf("a retired account produced a line: %q", out)
209 }
210
211 // A credential whose run ended, or whose runner never reported, is expired.
212 queue, err := runs.Open(f.runsDB)
213 if err != nil {
214 t.Fatal(err)
215 }
216 defer queue.Close()
217 expired := newTestKey(t)
218 past := time.Now().UTC().Add(-2 * time.Hour)
219 if err := queue.SetRunCredential(runs.RunCredential{
220 Fingerprint: expired.fp,
221 Account: f.account,
222 Repo: "demo",
223 RunID: "run-expired",
224 Expires: past.Add(time.Hour),
225 }, past); err != nil {
226 t.Fatal(err)
227 }
228 if out := f.authorizedKeys(t, expired); out != "" {
229 t.Errorf("an expired credential produced a line: %q", out)
230 }
231
232 if after := tokenCount(t, f.instDB); after != before {
233 t.Errorf("%d tokens were minted for keys that cannot be used (was %d)", after, before)
234 }
235 }
236
237 func TestAuthorizedKeysScopesARunCredential(t *testing.T) {
238 f := newSSHFixture(t)
239 queue, err := runs.Open(f.runsDB)
240 if err != nil {
241 t.Fatal(err)
242 }
243 defer queue.Close()
244 cred := newTestKey(t)
245 now := time.Now().UTC()
246 if err := queue.SetRunCredential(runs.RunCredential{
247 Fingerprint: cred.fp,
248 Account: f.account,
249 Repo: "demo",
250 RunID: "run-1",
251 Expires: now.Add(time.Hour),
252 }, now); err != nil {
253 t.Fatal(err)
254 }
255
256 line := strings.TrimSpace(f.authorizedKeys(t, cred))
257 _, forced, ok := strings.Cut(line, `restrict,command="`)
258 if !ok {
259 t.Fatalf("no forced command: %q", line)
260 }
261 _, token, ok := strings.Cut(forced, "--session ")
262 if !ok {
263 t.Fatalf("no session in %q", forced)
264 }
265 token, _, _ = strings.Cut(token, `"`)
266
267 store, err := sshsession.Open(f.instDB)
268 if err != nil {
269 t.Fatal(err)
270 }
271 defer store.Close()
272 sess, err := store.Consume(token, connection, time.Now().UTC())
273 if err != nil || sess == nil {
274 t.Fatalf("consume = %+v, %v", sess, err)
275 }
276 if sess.Account != f.account || sess.Credential != cred.fp || sess.Repo != "demo" || sess.RunID != "run-1" {
277 t.Errorf("the session lost its scope: %+v", sess)
278 }
279 }
280
281 // TestTheBinaryRunsTheFrontDoorCommands executes the built binary, because what
282 // sshd reads is a process: its environment in, its output and exit status out.
283 func TestTheBinaryRunsTheFrontDoorCommands(t *testing.T) {
284 bin := buildVole(t)
285 f := newSSHFixture(t)
286
287 t.Run("exec copies the streams and returns the status", func(t *testing.T) {
288 srv := serveWireOnce(t, func(t *testing.T, conn net.Conn, hello sshwire.Hello) {
289 if hello.Command != "git-upload-pack 'demo.git'" {
290 t.Errorf("hello command = %q", hello.Command)
291 }
292 if hello.Remote != connection {
293 t.Errorf("hello remote = %q", hello.Remote)
294 }
295 if hello.Session != "tok" {
296 t.Errorf("hello session = %q", hello.Session)
297 }
298 _ = sshwire.WriteJSON(conn, sshwire.KindAccept, sshwire.Accept{OK: true})
299 var in bytes.Buffer
300 for {
301 kind, payload, err := sshwire.ReadFrame(conn)
302 if err != nil {
303 t.Errorf("read input: %v", err)
304 return
305 }
306 if kind == sshwire.KindStdinEOF {
307 break
308 }
309 in.Write(payload)
310 }
311 _ = sshwire.WriteFrame(conn, sshwire.KindStdout, append([]byte("saw "), in.Bytes()...))
312 _ = sshwire.WriteFrame(conn, sshwire.KindStderr, []byte("warning\n"))
313 _ = sshwire.WriteJSON(conn, sshwire.KindExit, sshwire.Exit{Code: 129})
314 })
315 cfgPath := socketConfig(t, f, srv.path)
316 out, errOut, code := runBinary(t, bin, "input", cfgPath,
317 "SSH_ORIGINAL_COMMAND=git-upload-pack 'demo.git'", "SSH_CONNECTION="+connection)
318 if code != 129 {
319 t.Errorf("exit %d, want the session's 129", code)
320 }
321 if out != "saw input" {
322 t.Errorf("stdout %q", out)
323 }
324 if errOut != "warning\n" {
325 t.Errorf("stderr %q", errOut)
326 }
327 })
328
329 t.Run("exec reports a refused token and fails", func(t *testing.T) {
330 srv := serveWireOnce(t, func(t *testing.T, conn net.Conn, _ sshwire.Hello) {
331 _ = sshwire.WriteJSON(conn, sshwire.KindAccept, sshwire.Accept{Error: "that session token is not valid"})
332 })
333 cfgPath := socketConfig(t, f, srv.path)
334 out, errOut, code := runBinary(t, bin, "", cfgPath,
335 "SSH_ORIGINAL_COMMAND=git-upload-pack 'demo.git'", "SSH_CONNECTION="+connection)
336 if code != 1 {
337 t.Errorf("exit %d, want 1", code)
338 }
339 if out != "" {
340 t.Errorf("a refusal wrote to stdout: %q", out)
341 }
342 if !strings.Contains(errOut, "that session token is not valid") {
343 t.Errorf("the refusal was not reported: %q", errOut)
344 }
345 })
346
347 t.Run("exec without a command never reaches the socket", func(t *testing.T) {
348 // A path that does not exist proves the point: if the command dialled
349 // first, the message would be about the socket instead of the shell.
350 cfgPath := socketConfig(t, f, shortSocket(t))
351 out, errOut, code := runBinary(t, bin, "", cfgPath, "SSH_CONNECTION="+connection)
352 if code != 1 {
353 t.Errorf("exit %d, want 1", code)
354 }
355 if out != "" {
356 t.Errorf("stdout %q", out)
357 }
358 if !strings.Contains(errOut, "runs no shell") {
359 t.Errorf("the refusal does not say why: %q", errOut)
360 }
361 if strings.Contains(errOut, "cannot reach") {
362 t.Errorf("a connection with no command tried to open a session: %q", errOut)
363 }
364 })
365 }
366
367 // TestSSHShellRunsOnlyTheForcedCommand covers what sshd actually does with a
368 // command= option: it runs the login shell with -c and the forced command. The
369 // shell has to exec that one line and refuse everything else, including the -c
370 // form a person would expect to work.
371 func TestSSHShellRunsOnlyTheForcedCommand(t *testing.T) {
372 bin := buildVole(t)
373 f := newSSHFixture(t)
374
375 srv := serveWireOnce(t, func(t *testing.T, conn net.Conn, hello sshwire.Hello) {
376 if hello.Session != "tok" || hello.Command != "git-upload-pack 'demo.git'" {
377 t.Errorf("hello = %+v", hello)
378 }
379 _ = sshwire.WriteJSON(conn, sshwire.KindAccept, sshwire.Accept{OK: true})
380 _ = sshwire.WriteFrame(conn, sshwire.KindStdout, []byte("served"))
381 _ = sshwire.WriteJSON(conn, sshwire.KindExit, sshwire.Exit{Code: 0})
382 })
383 cfgPath := socketConfig(t, f, srv.path)
384 forced := bin + " ssh-exec --config " + cfgPath + " --session tok"
385
386 cmd := exec.Command(bin, "ssh-shell", "-c", forced)
387 cmd.Env = shellEnv()
388 var out, errOut bytes.Buffer
389 cmd.Stdout, cmd.Stderr = &out, &errOut
390 if err := cmd.Run(); err != nil {
391 t.Fatalf("the forced command did not run: %v (stderr %q)", err, errOut.String())
392 }
393 if out.String() != "served" {
394 t.Errorf("stdout %q, want the session's output", out.String())
395 }
396 if errOut.Len() != 0 {
397 t.Errorf("stderr %q", errOut.String())
398 }
399
400 for _, line := range []string{
401 "sh -c 'echo pwned'",
402 "/bin/sh ssh-exec --config " + cfgPath + " --session tok",
403 bin + " ssh-exec --config " + cfgPath + " --session tok; id",
404 bin + " ssh-exec --session tok --config " + cfgPath,
405 forced + " extra",
406 } {
407 cmd := exec.Command(bin, "ssh-shell", "-c", line)
408 cmd.Env = shellEnv()
409 var out, errOut bytes.Buffer
410 cmd.Stdout, cmd.Stderr = &out, &errOut
411 err := cmd.Run()
412 var exit *exec.ExitError
413 if !errors.As(err, &exit) || exit.ExitCode() != 1 {
414 t.Errorf("ssh-shell -c %q = %v, want exit 1", line, err)
415 }
416 if strings.Contains(out.String(), "pwned") || out.Len() != 0 {
417 t.Errorf("ssh-shell -c %q wrote to stdout: %q", line, out.String())
418 }
419 if !strings.Contains(errOut.String(), "no shell") {
420 t.Errorf("ssh-shell -c %q did not refuse: %q", line, errOut.String())
421 }
422 }
423
424 // No command at all: the interactive case, which must not become a shell.
425 cmd = exec.Command(bin, "ssh-shell")
426 cmd.Env = shellEnv()
427 var out2, errOut2 bytes.Buffer
428 cmd.Stdout, cmd.Stderr = &out2, &errOut2
429 err := cmd.Run()
430 var exit *exec.ExitError
431 if !errors.As(err, &exit) || exit.ExitCode() != 1 {
432 t.Fatalf("ssh-shell = %v, want exit 1", err)
433 }
434 if out2.Len() != 0 || !strings.Contains(errOut2.String(), "no shell") {
435 t.Errorf("an interactive session got a shell: stdout %q stderr %q", out2.String(), errOut2.String())
436 }
437 }
438
439 // shellEnv is what sshd sets for a front-door command.
440 func shellEnv() []string {
441 return []string{
442 "PATH=" + os.Getenv("PATH"),
443 "SSH_CONNECTION=" + connection,
444 "SSH_ORIGINAL_COMMAND=git-upload-pack 'demo.git'",
445 }
446 }
447
448 // socketConfig writes a minimal config that points ssh-exec at a test socket.
449 func socketConfig(t *testing.T, f *sshFixture, socket string) string {
450 t.Helper()
451 path := filepath.Join(t.TempDir(), "vole.toml")
452 body := fmt.Sprintf("data_dir = %q\nssh_socket = %q\n", f.dataDir, socket)
453 if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
454 t.Fatal(err)
455 }
456 return path
457 }
458
459 // runBinary runs `vole ssh-exec --config cfg --session tok` with the given stdin
460 // and extra environment, and reports what the client would see.
461 func runBinary(t *testing.T, bin, stdin, cfgPath string, env ...string) (string, string, int) {
462 t.Helper()
463 cmd := exec.Command(bin, "ssh-exec", "--config", cfgPath, "--session", "tok")
464 cmd.Env = append([]string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir()}, env...)
465 cmd.Stdin = strings.NewReader(stdin)
466 var out, errOut bytes.Buffer
467 cmd.Stdout, cmd.Stderr = &out, &errOut
468 err := cmd.Run()
469 code := 0
470 if err != nil {
471 var exit *exec.ExitError
472 if !errors.As(err, &exit) {
473 t.Fatalf("run: %v (stderr %q)", err, errOut.String())
474 }
475 code = exit.ExitCode()
476 }
477 return out.String(), errOut.String(), code
478 }
479
480 // buildVole builds the command once per test that needs it. The tests below run
481 // it as sshd would, so the argv, environment, and exit status are real.
482 func buildVole(t *testing.T) string {
483 t.Helper()
484 bin := filepath.Join(t.TempDir(), "vole")
485 cmd := exec.Command("go", "build", "-o", bin, "rodent.software/vole/cmd/vole")
486 if out, err := cmd.CombinedOutput(); err != nil {
487 t.Fatalf("build vole: %v\n%s", err, out)
488 }
489 return bin
490 }
491
492 // shortSocket returns a socket path that fits in sun_path: a temporary directory
493 // under /tmp is short, and t.TempDir is not.
494 func shortSocket(t *testing.T) string {
495 t.Helper()
496 dir, err := os.MkdirTemp("", "vole-wire-")
497 if err != nil {
498 t.Fatal(err)
499 }
500 t.Cleanup(func() { os.RemoveAll(dir) })
501 return filepath.Join(dir, "s.sock")
502 }
503
504 // serveWireOnce answers one session on a Unix socket, with fn writing every
505 // frame the service would write.
506 func serveWireOnce(t *testing.T, fn func(*testing.T, net.Conn, sshwire.Hello)) *wireServer {
507 t.Helper()
508 s := &wireServer{path: shortSocket(t)}
509 ln, err := net.Listen("unix", s.path)
510 if err != nil {
511 t.Fatalf("listen: %v", err)
512 }
513 t.Cleanup(func() { ln.Close() })
514 go func() {
515 conn, err := ln.Accept()
516 if err != nil {
517 return
518 }
519 defer conn.Close()
520 var hello sshwire.Hello
521 if kind, payload, err := sshwire.ReadFrame(conn); err == nil && kind == sshwire.KindHello {
522 _ = json.Unmarshal(payload, &hello)
523 }
524 fn(t, conn, hello)
525 }()
526 return s
527 }
528
529 type wireServer struct{ path string }