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.

forge/sshsession/sshsession.go +214

@@ -0,0 +1,214 @@
1 // Package sshsession holds the one-use tokens that carry an authenticated SSH
2 // key from sshd to `vole serve`.
3 //
4 // The front door authenticates with the system sshd, which runs
5 // `vole ssh-authorized-keys` while it is still deciding whether to let the key
6 // in. That command is the only place that can read the roster and the run
7 // credentials on this path, and it is not the process that may serve a request.
8 // So it mints a capability: a random token, a row describing whose session it
9 // is, and sixty seconds in which it must be spent. The forced command
10 // `vole ssh-exec` presents the token, and `vole serve` consumes it — once.
11 //
12 // Only the token's hash is stored. The row records the account, the credential
13 // fingerprint when the key was a job's, the client endpoint the token was minted
14 // for, and the expiry; the token itself exists on one command line and in one
15 // request.
16 package sshsession
17
18 import (
19 "crypto/rand"
20 "crypto/sha256"
21 "database/sql"
22 "encoding/base64"
23 "encoding/hex"
24 "errors"
25 "fmt"
26 "strings"
27 "time"
28
29 _ "github.com/mattn/go-sqlite3"
30 )
31
32 const (
33 // Lifetime bounds a token: minted while sshd authenticates, spent by the
34 // forced command that follows within the same handshake. A minute absorbs a
35 // slow connection without leaving a usable capability behind.
36 Lifetime = 60 * time.Second
37 // tokenBytes is the capability's size. It is a bearer value that only has to
38 // survive one handshake, and 256 bits is past guessing.
39 tokenBytes = 32
40 )
41
42 // Token is what a session token says about the session it opens. It is the row
43 // without the secret.
44 type Token struct {
45 // Account is the Vole account the key resolved to.
46 Account string
47 // Credential is the fingerprint of the run credential the key was, when the
48 // key was one. Empty means the key is the account's own.
49 Credential string
50 // Repo and RunID scope a credential session to the job it was minted for.
51 Repo string
52 RunID string
53 // Client is the client endpoint the token was minted for, normalized to
54 // "address port". A token presented from anywhere else is refused: the value
55 // is visible in the forced command's argv, and another local user reading
56 // /proc must not be able to spend it.
57 Client string
58 // Expires is when the token stops working.
59 Expires time.Time
60 }
61
62 // Store is the token table. It lives in the instance database, beside the roster
63 // it answers for, so a backup does not grow a file to forget.
64 type Store struct {
65 db *sql.DB
66 }
67
68 // Open prepares the token table. It is idempotent, so the service and the
69 // authentication command can both open the same file.
70 func Open(path string) (*Store, error) {
71 dsn := path + "?_busy_timeout=5000&_journal_mode=WAL&_txlock=immediate"
72 db, err := sql.Open("sqlite3", dsn)
73 if err != nil {
74 return nil, fmt.Errorf("sshsession: %w", err)
75 }
76 db.SetMaxOpenConns(2)
77 if _, err := db.Exec(`
78 CREATE TABLE IF NOT EXISTS ssh_sessions (
79 token_hash TEXT PRIMARY KEY,
80 account TEXT NOT NULL,
81 credential TEXT NOT NULL DEFAULT '',
82 repo TEXT NOT NULL DEFAULT '',
83 run_id TEXT NOT NULL DEFAULT '',
84 client TEXT NOT NULL,
85 expires INTEGER NOT NULL
86 );
87 CREATE INDEX IF NOT EXISTS ssh_sessions_expires ON ssh_sessions(expires);`); err != nil {
88 db.Close()
89 return nil, fmt.Errorf("sshsession: create token table: %w", err)
90 }
91 return &Store{db: db}, nil
92 }
93
94 func (s *Store) Close() error { return s.db.Close() }
95
96 // Mint records a token for t and returns it. The expiry is this package's
97 // decision, not the caller's, and the client endpoint is required: a token that
98 // is not bound to the connection that asked for it is a token any local process
99 // could spend.
100 //
101 // Expired rows are dropped in the same transaction, so the table stays bounded
102 // by the tokens minted in the last minute rather than by every key ever offered.
103 func (s *Store) Mint(t Token, now time.Time) (string, error) {
104 if t.Account == "" {
105 return "", errors.New("sshsession: a token needs an account")
106 }
107 client, err := NormalizeClient(t.Client)
108 if err != nil {
109 return "", err
110 }
111 raw := make([]byte, tokenBytes)
112 if _, err := rand.Read(raw); err != nil {
113 return "", fmt.Errorf("sshsession: generate a token: %w", err)
114 }
115 token := base64.RawURLEncoding.EncodeToString(raw)
116 expires := now.Add(Lifetime)
117
118 tx, err := s.db.Begin()
119 if err != nil {
120 return "", err
121 }
122 defer tx.Rollback()
123 if _, err := tx.Exec(`DELETE FROM ssh_sessions WHERE expires <= ?`, now.Unix()); err != nil {
124 return "", fmt.Errorf("sshsession: drop expired tokens: %w", err)
125 }
126 if _, err := tx.Exec(`INSERT INTO ssh_sessions
127 (token_hash, account, credential, repo, run_id, client, expires)
128 VALUES (?,?,?,?,?,?,?)`,
129 hash(token), t.Account, t.Credential, t.Repo, t.RunID, client, expires.Unix()); err != nil {
130 return "", fmt.Errorf("sshsession: store token: %w", err)
131 }
132 if err := tx.Commit(); err != nil {
133 return "", err
134 }
135 return token, nil
136 }
137
138 // Consume resolves a token once. It reports nil when the token is unknown, has
139 // expired, or was minted for a different client endpoint — one answer for every
140 // way a token can fail to be a session.
141 //
142 // The row is deleted whichever way it goes. A token that was presented at all is
143 // spent: the only party that can know the value is the connection it was minted
144 // for, so a wrong endpoint means the capability has leaked, and leaving it alive
145 // for the rest of its minute would let whoever has it keep trying.
146 func (s *Store) Consume(token, client string, now time.Time) (*Token, error) {
147 if token == "" {
148 return nil, nil
149 }
150 want, err := NormalizeClient(client)
151 if err != nil {
152 // A request whose connection cannot be read is not the connection the
153 // token was minted for.
154 want = ""
155 }
156
157 tx, err := s.db.Begin()
158 if err != nil {
159 return nil, err
160 }
161 defer tx.Rollback()
162 var t Token
163 var gotClient string
164 var expires int64
165 err = tx.QueryRow(`SELECT account, credential, repo, run_id, client, expires
166 FROM ssh_sessions WHERE token_hash = ?`, hash(token)).
167 Scan(&t.Account, &t.Credential, &t.Repo, &t.RunID, &gotClient, &expires)
168 if errors.Is(err, sql.ErrNoRows) {
169 return nil, nil
170 }
171 if err != nil {
172 return nil, fmt.Errorf("sshsession: read token: %w", err)
173 }
174 if _, err := tx.Exec(`DELETE FROM ssh_sessions WHERE token_hash = ?`, hash(token)); err != nil {
175 return nil, fmt.Errorf("sshsession: spend token: %w", err)
176 }
177 if err := tx.Commit(); err != nil {
178 return nil, err
179 }
180
181 t.Client, t.Expires = gotClient, time.Unix(expires, 0).UTC()
182 if !t.Expires.After(now) || want == "" || gotClient != want {
183 return nil, nil
184 }
185 return &t, nil
186 }
187
188 // Prune drops expired tokens. Mint already does this on every write, so this is
189 // for the service's ticker: an instance nobody authenticates against should not
190 // keep rows forever either.
191 func (s *Store) Prune(now time.Time) (int64, error) {
192 res, err := s.db.Exec(`DELETE FROM ssh_sessions WHERE expires <= ?`, now.Unix())
193 if err != nil {
194 return 0, fmt.Errorf("sshsession: prune tokens: %w", err)
195 }
196 return res.RowsAffected()
197 }
198
199 // NormalizeClient reduces sshd's %C token or SSH_CONNECTION to the client half:
200 // the address and the port it connected from. The server half is left out
201 // deliberately — it is the same accept either way, and a difference there (NAT, a
202 // second listener) must not turn a good token into a refused one.
203 func NormalizeClient(s string) (string, error) {
204 fields := strings.Fields(s)
205 if len(fields) < 2 {
206 return "", fmt.Errorf("sshsession: %q is not a client endpoint", s)
207 }
208 return fields[0] + " " + fields[1], nil
209 }
210
211 func hash(token string) string {
212 sum := sha256.Sum256([]byte(token))
213 return hex.EncodeToString(sum[:])
214 }