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.
|
e075258f
Keenan Nemetz
16d ago
|
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" | |
|
16a92c6f
Keenan Nemetz
16d ago
|
26 | "sort" |
|
e075258f
Keenan Nemetz
16d ago
|
27 | "strings" |
| 28 | "time" | |
| 29 | ||
|
8f6548a6
Keenan Nemetz
3d ago
|
30 | "rodent.software/vole/internal/sqlstore" |
|
e075258f
Keenan Nemetz
16d ago
|
31 | ) |
| 32 | ||
| 33 | const ( | |
| 34 | // Lifetime bounds a token: minted while sshd authenticates, spent by the | |
| 35 | // forced command that follows within the same handshake. A minute absorbs a | |
| 36 | // slow connection without leaving a usable capability behind. | |
| 37 | Lifetime = 60 * time.Second | |
| 38 | // tokenBytes is the capability's size. It is a bearer value that only has to | |
| 39 | // survive one handshake, and 256 bits is past guessing. | |
| 40 | tokenBytes = 32 | |
| 41 | ) | |
| 42 | ||
| 43 | // Token is what a session token says about the session it opens. It is the row | |
| 44 | // without the secret. | |
| 45 | type Token struct { | |
| 46 | // Account is the Vole account the key resolved to. | |
| 47 | Account string | |
| 48 | // Credential is the fingerprint of the run credential the key was, when the | |
| 49 | // key was one. Empty means the key is the account's own. | |
| 50 | Credential string | |
|
c5f2c5d4
Keenan Nemetz
16d ago
|
51 | // Key is the fingerprint sshd authenticated. It travels with the session so |
| 52 | // the service reports the same identity detail the built-in listener reports: | |
| 53 | // the hook environment, the audit detail, and the run-credential lookup all | |
| 54 | // key off it. | |
| 55 | Key string | |
|
e075258f
Keenan Nemetz
16d ago
|
56 | // Repo and RunID scope a credential session to the job it was minted for. |
| 57 | Repo string | |
| 58 | RunID string | |
|
16a92c6f
Keenan Nemetz
16d ago
|
59 | // Client is the connection the token was minted for, canonicalized by |
| 60 | // NormalizeClient. A token presented from anywhere else is refused: the value | |
|
e075258f
Keenan Nemetz
16d ago
|
61 | // is visible in the forced command's argv, and another local user reading |
| 62 | // /proc must not be able to spend it. | |
| 63 | Client string | |
| 64 | // Expires is when the token stops working. | |
| 65 | Expires time.Time | |
| 66 | } | |
| 67 | ||
| 68 | // Store is the token table. It lives in the instance database, beside the roster | |
| 69 | // it answers for, so a backup does not grow a file to forget. | |
| 70 | type Store struct { | |
| 71 | db *sql.DB | |
| 72 | } | |
| 73 | ||
| 74 | // Open prepares the token table. It is idempotent, so the service and the | |
| 75 | // authentication command can both open the same file. | |
| 76 | func Open(path string) (*Store, error) { | |
|
8f6548a6
Keenan Nemetz
3d ago
|
77 | db, err := sqlstore.Open(path, sqlstore.Options{MaxConns: 2}) |
|
e075258f
Keenan Nemetz
16d ago
|
78 | if err != nil { |
| 79 | return nil, fmt.Errorf("sshsession: %w", err) | |
| 80 | } | |
| 81 | if _, err := db.Exec(` | |
| 82 | CREATE TABLE IF NOT EXISTS ssh_sessions ( | |
| 83 | token_hash TEXT PRIMARY KEY, | |
| 84 | account TEXT NOT NULL, | |
| 85 | credential TEXT NOT NULL DEFAULT '', | |
|
c5f2c5d4
Keenan Nemetz
16d ago
|
86 | key_fp TEXT NOT NULL DEFAULT '', |
|
e075258f
Keenan Nemetz
16d ago
|
87 | repo TEXT NOT NULL DEFAULT '', |
| 88 | run_id TEXT NOT NULL DEFAULT '', | |
| 89 | client TEXT NOT NULL, | |
| 90 | expires INTEGER NOT NULL | |
| 91 | ); | |
| 92 | CREATE INDEX IF NOT EXISTS ssh_sessions_expires ON ssh_sessions(expires);`); err != nil { | |
| 93 | db.Close() | |
| 94 | return nil, fmt.Errorf("sshsession: create token table: %w", err) | |
| 95 | } | |
| 96 | return &Store{db: db}, nil | |
| 97 | } | |
| 98 | ||
| 99 | func (s *Store) Close() error { return s.db.Close() } | |
| 100 | ||
| 101 | // Mint records a token for t and returns it. The expiry is this package's | |
| 102 | // decision, not the caller's, and the client endpoint is required: a token that | |
| 103 | // is not bound to the connection that asked for it is a token any local process | |
| 104 | // could spend. | |
| 105 | // | |
| 106 | // Expired rows are dropped in the same transaction, so the table stays bounded | |
| 107 | // by the tokens minted in the last minute rather than by every key ever offered. | |
| 108 | func (s *Store) Mint(t Token, now time.Time) (string, error) { | |
| 109 | if t.Account == "" { | |
| 110 | return "", errors.New("sshsession: a token needs an account") | |
| 111 | } | |
| 112 | client, err := NormalizeClient(t.Client) | |
| 113 | if err != nil { | |
| 114 | return "", err | |
| 115 | } | |
| 116 | raw := make([]byte, tokenBytes) | |
| 117 | if _, err := rand.Read(raw); err != nil { | |
| 118 | return "", fmt.Errorf("sshsession: generate a token: %w", err) | |
| 119 | } | |
| 120 | token := base64.RawURLEncoding.EncodeToString(raw) | |
| 121 | expires := now.Add(Lifetime) | |
| 122 | ||
| 123 | tx, err := s.db.Begin() | |
| 124 | if err != nil { | |
| 125 | return "", err | |
| 126 | } | |
| 127 | defer tx.Rollback() | |
| 128 | if _, err := tx.Exec(`DELETE FROM ssh_sessions WHERE expires <= ?`, now.Unix()); err != nil { | |
| 129 | return "", fmt.Errorf("sshsession: drop expired tokens: %w", err) | |
| 130 | } | |
| 131 | if _, err := tx.Exec(`INSERT INTO ssh_sessions | |
|
c5f2c5d4
Keenan Nemetz
16d ago
|
132 | (token_hash, account, credential, key_fp, repo, run_id, client, expires) |
| 133 | VALUES (?,?,?,?,?,?,?,?)`, | |
| 134 | hash(token), t.Account, t.Credential, t.Key, t.Repo, t.RunID, client, expires.Unix()); err != nil { | |
|
e075258f
Keenan Nemetz
16d ago
|
135 | return "", fmt.Errorf("sshsession: store token: %w", err) |
| 136 | } | |
| 137 | if err := tx.Commit(); err != nil { | |
| 138 | return "", err | |
| 139 | } | |
| 140 | return token, nil | |
| 141 | } | |
| 142 | ||
| 143 | // Consume resolves a token once. It reports nil when the token is unknown, has | |
| 144 | // expired, or was minted for a different client endpoint — one answer for every | |
| 145 | // way a token can fail to be a session. | |
| 146 | // | |
| 147 | // The row is deleted whichever way it goes. A token that was presented at all is | |
| 148 | // spent: the only party that can know the value is the connection it was minted | |
| 149 | // for, so a wrong endpoint means the capability has leaked, and leaving it alive | |
| 150 | // for the rest of its minute would let whoever has it keep trying. | |
| 151 | func (s *Store) Consume(token, client string, now time.Time) (*Token, error) { | |
| 152 | if token == "" { | |
| 153 | return nil, nil | |
| 154 | } | |
| 155 | want, err := NormalizeClient(client) | |
| 156 | if err != nil { | |
| 157 | // A request whose connection cannot be read is not the connection the | |
| 158 | // token was minted for. | |
| 159 | want = "" | |
| 160 | } | |
| 161 | ||
| 162 | tx, err := s.db.Begin() | |
| 163 | if err != nil { | |
| 164 | return nil, err | |
| 165 | } | |
| 166 | defer tx.Rollback() | |
| 167 | var t Token | |
| 168 | var gotClient string | |
| 169 | var expires int64 | |
|
c5f2c5d4
Keenan Nemetz
16d ago
|
170 | err = tx.QueryRow(`SELECT account, credential, key_fp, repo, run_id, client, expires |
|
e075258f
Keenan Nemetz
16d ago
|
171 | FROM ssh_sessions WHERE token_hash = ?`, hash(token)). |
|
c5f2c5d4
Keenan Nemetz
16d ago
|
172 | Scan(&t.Account, &t.Credential, &t.Key, &t.Repo, &t.RunID, &gotClient, &expires) |
|
e075258f
Keenan Nemetz
16d ago
|
173 | if errors.Is(err, sql.ErrNoRows) { |
| 174 | return nil, nil | |
| 175 | } | |
| 176 | if err != nil { | |
| 177 | return nil, fmt.Errorf("sshsession: read token: %w", err) | |
| 178 | } | |
| 179 | if _, err := tx.Exec(`DELETE FROM ssh_sessions WHERE token_hash = ?`, hash(token)); err != nil { | |
| 180 | return nil, fmt.Errorf("sshsession: spend token: %w", err) | |
| 181 | } | |
| 182 | if err := tx.Commit(); err != nil { | |
| 183 | return nil, err | |
| 184 | } | |
| 185 | ||
| 186 | t.Client, t.Expires = gotClient, time.Unix(expires, 0).UTC() | |
| 187 | if !t.Expires.After(now) || want == "" || gotClient != want { | |
| 188 | return nil, nil | |
| 189 | } | |
| 190 | return &t, nil | |
| 191 | } | |
| 192 | ||
| 193 | // Prune drops expired tokens. Mint already does this on every write, so this is | |
| 194 | // for the service's ticker: an instance nobody authenticates against should not | |
| 195 | // keep rows forever either. | |
| 196 | func (s *Store) Prune(now time.Time) (int64, error) { | |
| 197 | res, err := s.db.Exec(`DELETE FROM ssh_sessions WHERE expires <= ?`, now.Unix()) | |
| 198 | if err != nil { | |
| 199 | return 0, fmt.Errorf("sshsession: prune tokens: %w", err) | |
| 200 | } | |
| 201 | return res.RowsAffected() | |
| 202 | } | |
| 203 | ||
|
16a92c6f
Keenan Nemetz
16d ago
|
204 | // NormalizeClient canonicalizes the connection a token is bound to. sshd's %C |
| 205 | // token and the SSH_CONNECTION environment variable describe the same TCP | |
| 206 | // connection with the same four values, but not in the same order: on OpenSSH | |
| 207 | // 9.6p1, %C expands to "server address, server port, client address, client | |
| 208 | // port" while SSH_CONNECTION is "client address, client port, server address, | |
| 209 | // server port" — and sshd_config(5) describes %C the second way, which the | |
| 210 | // binary does not do. Sorting makes the binding depend on the values, which | |
| 211 | // identify the connection, rather than on an order that is neither documented | |
| 212 | // consistently nor stable. | |
| 213 | // | |
| 214 | // Four values are required, and a caller that cannot produce them gets a refusal | |
| 215 | // rather than a weaker check. | |
|
e075258f
Keenan Nemetz
16d ago
|
216 | func NormalizeClient(s string) (string, error) { |
| 217 | fields := strings.Fields(s) | |
|
16a92c6f
Keenan Nemetz
16d ago
|
218 | if len(fields) != 4 { |
| 219 | return "", fmt.Errorf("sshsession: %q is not a connection's four endpoints", s) | |
|
e075258f
Keenan Nemetz
16d ago
|
220 | } |
|
16a92c6f
Keenan Nemetz
16d ago
|
221 | sorted := append([]string(nil), fields...) |
| 222 | sort.Strings(sorted) | |
| 223 | return strings.Join(sorted, " "), nil | |
|
e075258f
Keenan Nemetz
16d ago
|
224 | } |
| 225 | ||
| 226 | func hash(token string) string { | |
| 227 | sum := sha256.Sum256([]byte(token)) | |
| 228 | return hex.EncodeToString(sum[:]) | |
| 229 | } |