internal/sshd/sshd.go
440 lines · 13495 bytes
1// Package sshd implements the embedded SSH listener: public-key auth against
2// registered keys, then dispatch to git transport or control commands.
3package sshd
4
5import (
6 "context"
7 "crypto/ed25519"
8 "crypto/rand"
9 "encoding/base64"
10 "encoding/pem"
11 "errors"
12 "fmt"
13 "io"
14 "log/slog"
15 "net"
16 "os"
17 "path/filepath"
18 "strconv"
19 "sync"
20 "sync/atomic"
21 "time"
22
23 "golang.org/x/crypto/ssh"
24
25 "gitbay.org/gitbay/internal/config"
26 "gitbay.org/gitbay/internal/control"
27 "gitbay.org/gitbay/internal/gitutil"
28 "gitbay.org/gitbay/internal/hookd"
29 "gitbay.org/gitbay/internal/policy"
30 "gitbay.org/gitbay/internal/protocol"
31 "gitbay.org/gitbay/internal/store"
32)
33
34type Server struct {
35 cfg config.Config
36 st *store.Store
37 sshCfg *ssh.ServerConfig
38 authLimiter *rateLimiter
39 sessions sync.WaitGroup // accepted connections still being served
40 mu sync.Mutex
41 conns map[*conn]struct{}
42}
43
44// conn is one accepted connection and how many sessions it is running.
45// A CLI's shared connection sits idle between commands; on shutdown an
46// idle connection is closed at once and only a session mid-command is
47// waited for (#141).
48type conn struct {
49 net net.Conn
50 active atomic.Int32
51}
52
53func New(cfg config.Config, st *store.Store) (*Server, error) {
54 s := &Server{cfg: cfg, st: st, authLimiter: newRateLimiter(cfg.Limits.SSHAuthRate, time.Minute), conns: map[*conn]struct{}{}}
55
56 sc := &ssh.ServerConfig{
57 PublicKeyCallback: s.authenticate,
58 ServerVersion: "SSH-2.0-gitbayd",
59 }
60 signers, err := loadHostKeys(cfg)
61 if err != nil {
62 return nil, err
63 }
64 for _, sg := range signers {
65 sc.AddHostKey(sg)
66 }
67 s.sshCfg = sc
68 return s, nil
69}
70
71// loadHostKeys loads the configured host keys, or generates an ed25519 key
72// under server.root/ssh/ when none are configured.
73func loadHostKeys(cfg config.Config) ([]ssh.Signer, error) {
74 paths := cfg.SSH.HostKeys
75 if len(paths) == 0 {
76 p := filepath.Join(cfg.Server.Root, "ssh", "host_ed25519")
77 if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
78 if err := generateHostKey(p); err != nil {
79 return nil, fmt.Errorf("generating host key: %w", err)
80 }
81 slog.Info("generated ssh host key", "path", p)
82 }
83 paths = []string{p}
84 }
85 var signers []ssh.Signer
86 for _, p := range paths {
87 raw, err := os.ReadFile(p)
88 if err != nil {
89 return nil, fmt.Errorf("host key %s: %w", p, err)
90 }
91 sg, err := ssh.ParsePrivateKey(raw)
92 if err != nil {
93 return nil, fmt.Errorf("host key %s: %w", p, err)
94 }
95 signers = append(signers, sg)
96 }
97 return signers, nil
98}
99
100func generateHostKey(path string) error {
101 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
102 return err
103 }
104 _, priv, err := ed25519.GenerateKey(rand.Reader)
105 if err != nil {
106 return err
107 }
108 block, err := ssh.MarshalPrivateKey(priv, "")
109 if err != nil {
110 return err
111 }
112 return os.WriteFile(path, pem.EncodeToMemory(block), 0o600)
113}
114
115// authenticate resolves the presented key to a registered account. The SSH
116// username is ignored; identity comes from the key alone. When registration
117// is open or invite-based, unknown keys are admitted to run exactly one
118// command: register.
119func (s *Server) authenticate(meta ssh.ConnMetadata, pub ssh.PublicKey) (*ssh.Permissions, error) {
120 ip := remoteIP(meta.RemoteAddr())
121 if !s.authLimiter.allow(ip) {
122 // One audit entry per throttled window, not per rejected attempt.
123 if s.authLimiter.firstThrottle(ip) {
124 s.st.Audit(0, "auth.throttled", map[string]any{"ip": ip, "rate": s.cfg.Limits.SSHAuthRate})
125 }
126 return nil, fmt.Errorf("too many authentication attempts; try again shortly")
127 }
128 fp := ssh.FingerprintSHA256(pub)
129 key, err := s.st.SSHKeyByFingerprint(fp)
130 if err != nil && !errors.Is(err, store.ErrNotFound) {
131 // The store, not the key, failed. Neither a failure against the
132 // limiter nor "unknown key": a busy database during a restart
133 // would otherwise lock every client out for a minute.
134 slog.Error("ssh auth: key lookup", "err", err)
135 return nil, fmt.Errorf("authentication temporarily unavailable")
136 }
137 if err != nil {
138 if s.cfg.Registration.Mode != "closed" {
139 return &ssh.Permissions{Extensions: map[string]string{
140 "anon-key": base64.StdEncoding.EncodeToString(pub.Marshal()),
141 }}, nil
142 }
143 s.authLimiter.fail(ip)
144 s.st.Audit(0, "auth.failed", map[string]any{"ip": ip, "fingerprint": fp})
145 return nil, fmt.Errorf("unknown key %s", fp)
146 }
147 s.authLimiter.success(ip)
148 return &ssh.Permissions{Extensions: map[string]string{
149 "user-id": strconv.FormatInt(key.UserID, 10),
150 "key-id": strconv.FormatInt(key.ID, 10),
151 "key-fp": fp,
152 "scope": key.Scope,
153 }}, nil
154}
155
156// Serve accepts connections on ln until it is closed.
157func (s *Server) Serve(ln net.Listener) error {
158 for {
159 nc, err := ln.Accept()
160 if err != nil {
161 return err
162 }
163 c := &conn{net: nc}
164 s.mu.Lock()
165 s.conns[c] = struct{}{}
166 s.mu.Unlock()
167 s.sessions.Add(1)
168 go func() {
169 defer s.sessions.Done()
170 defer func() {
171 s.mu.Lock()
172 delete(s.conns, c)
173 s.mu.Unlock()
174 }()
175 s.handleConn(c)
176 }()
177 }
178}
179
180// Shutdown closes every idle connection, then waits for the ones with a
181// session running, or for ctx. The caller closes the listener first; a
182// push in flight completes rather than being cut mid-pack.
183func (s *Server) Shutdown(ctx context.Context) error {
184 s.mu.Lock()
185 for c := range s.conns {
186 if c.active.Load() == 0 {
187 c.net.Close()
188 }
189 }
190 s.mu.Unlock()
191 done := make(chan struct{})
192 go func() {
193 s.sessions.Wait()
194 close(done)
195 }()
196 select {
197 case <-done:
198 return nil
199 case <-ctx.Done():
200 return ctx.Err()
201 }
202}
203
204func (s *Server) handleConn(c *conn) {
205 defer c.net.Close()
206 sconn, chans, reqs, err := ssh.NewServerConn(c.net, s.sshCfg)
207 if err != nil {
208 return
209 }
210 defer sconn.Close()
211 go ssh.DiscardRequests(reqs)
212
213 for newCh := range chans {
214 if newCh.ChannelType() != "session" {
215 newCh.Reject(ssh.UnknownChannelType, "only session channels are supported")
216 continue
217 }
218 ch, chReqs, err := newCh.Accept()
219 if err != nil {
220 continue
221 }
222 c.active.Add(1)
223 go func() {
224 defer c.active.Add(-1)
225 s.handleSession(sconn, ch, chReqs)
226 }()
227 }
228}
229
230func (s *Server) handleSession(sconn *ssh.ServerConn, ch ssh.Channel, reqs <-chan *ssh.Request) {
231 defer ch.Close()
232 for req := range reqs {
233 switch req.Type {
234 case "exec":
235 var payload struct{ Command string }
236 if err := ssh.Unmarshal(req.Payload, &payload); err != nil {
237 req.Reply(false, nil)
238 continue
239 }
240 req.Reply(true, nil)
241 // x/crypto closes reqs when the client closes the channel. That
242 // is how a follow learns nobody is reading: the CLI's shared
243 // connection outlives a Ctrl-C, the channel does not.
244 done := make(chan struct{})
245 go func() {
246 for r := range reqs {
247 r.Reply(false, nil)
248 }
249 close(done)
250 }()
251 code := s.runExec(sconn, ch, payload.Command, done)
252 sendExit(ch, code)
253 return
254 case "shell":
255 req.Reply(true, nil)
256 fmt.Fprintf(ch, "gitbay control plane: interactive shells are not available.\nTry: ssh %s help\n", s.cfg.Server.SiteURL)
257 sendExit(ch, protocol.ExitUsage)
258 return
259 case "pty-req", "env":
260 // Harmless; accept and ignore.
261 req.Reply(true, nil)
262 default:
263 req.Reply(false, nil)
264 }
265 }
266}
267
268func sendExit(ch ssh.Channel, code int) {
269 var msg = struct{ Status uint32 }{uint32(code)}
270 ch.SendRequest("exit-status", false, ssh.Marshal(&msg))
271}
272
273func (s *Server) runExec(sconn *ssh.ServerConn, ch ssh.Channel, cmdline string, done <-chan struct{}) int {
274 ext := sconn.Permissions.Extensions
275 if blob := ext["anon-key"]; blob != "" {
276 return s.runAnonymous(ch, blob, cmdline)
277 }
278 userID, _ := strconv.ParseInt(ext["user-id"], 10, 64)
279 keyID, _ := strconv.ParseInt(ext["key-id"], 10, 64)
280 user, err := s.st.UserByID(userID)
281 if err != nil {
282 fmt.Fprintln(ch.Stderr(), "account no longer exists")
283 return protocol.ExitDenied
284 }
285 _ = s.st.TouchSSHKey(keyID)
286 return Exec(s.cfg, s.st, user, ext["scope"], ext["key-fp"], cmdline, ch, ch, ch.Stderr(), done)
287}
288
289// runAnonymous handles a session from an unregistered key: the register
290// command and nothing else.
291func (s *Server) runAnonymous(ch ssh.Channel, keyB64, cmdline string) int {
292 raw, err := base64.StdEncoding.DecodeString(keyB64)
293 if err != nil {
294 return protocol.ExitFailure
295 }
296 pub, err := ssh.ParsePublicKey(raw)
297 if err != nil {
298 return protocol.ExitFailure
299 }
300 argv, err := protocol.Tokenize(cmdline)
301 if err != nil {
302 fmt.Fprintf(ch.Stderr(), "cannot parse command: %v\n", err)
303 return protocol.ExitUsage
304 }
305 if len(argv) == 0 || argv[0] != "register" {
306 fmt.Fprintf(ch.Stderr(), "this key is not registered here. Create an account with:\n ssh <host> register --username <name> %s\n",
307 map[string]string{"open": "--email <address>", "invite": "--invite <code>"}[s.cfg.Registration.Mode])
308 return protocol.ExitDenied
309 }
310 return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr())
311}
312
313// Exec runs one SSH exec command line for an authenticated key. It is the
314// single dispatch path shared by the embedded listener and the system-sshd
315// forced command (gitbayd shell).
316func Exec(cfg config.Config, st *store.Store, user store.User, scope, source, cmdline string,
317 stdin io.Reader, stdout, stderr io.Writer, done <-chan struct{}) int {
318 if user.Disabled {
319 fmt.Fprintln(stderr, "this account is disabled; contact the instance admin")
320 return protocol.ExitDenied
321 }
322 argv, err := protocol.Tokenize(cmdline)
323 if err != nil {
324 fmt.Fprintf(stderr, "cannot parse command: %v\n", err)
325 return protocol.ExitUsage
326 }
327 if len(argv) > 0 {
328 switch argv[0] {
329 case "git-upload-pack", "git-receive-pack", "git-upload-archive":
330 if user.Pending {
331 fmt.Fprintln(stderr, "your account is not active yet: verify your email first")
332 return protocol.ExitDenied
333 }
334 return runGit(cfg, st, user, scope, argv, stdin, stdout, stderr)
335 case "git-lfs-authenticate":
336 // Part of the git transport, not the control plane: usable by
337 // git-scoped and deploy keys, with the transports' access rules.
338 if user.Pending {
339 fmt.Fprintln(stderr, "your account is not active yet: verify your email first")
340 return protocol.ExitDenied
341 }
342 return runLFSAuthenticate(cfg, st, user, scope, argv, stdout, stderr)
343 }
344 }
345 ctx := &control.Ctx{
346 User: user,
347 Scope: scope,
348 Source: source,
349 Store: st,
350 Cfg: cfg,
351 Stdin: stdin,
352 Stdout: stdout,
353 Stderr: stderr,
354 Done: done,
355 }
356 return control.Dispatch(ctx, argv)
357}
358
359// runGit streams a git transport service after access checks.
360func runGit(cfg config.Config, st *store.Store, user store.User, scope string, argv []string,
361 stdin io.Reader, stdout, stderr io.Writer) int {
362 service := argv[0]
363 if len(argv) != 2 {
364 fmt.Fprintf(stderr, "usage: %s <path>\n", service)
365 return protocol.ExitUsage
366 }
367 write := service == "git-receive-pack"
368
369 repo, err := st.RepoByPath(argv[1])
370 if err != nil {
371 fmt.Fprintln(stderr, "repository not found")
372 return protocol.ExitNotFound
373 }
374 if policy.IsDeployScope(scope) {
375 // A deploy key authorizes by its binding alone: one repository,
376 // its mode, nothing inherited from whoever registered it. Any
377 // mismatch reads as nonexistence, same as the access rules.
378 if !policy.DeployScopeAllows(scope, repo.ID, write) {
379 fmt.Fprintln(stderr, "repository not found")
380 return protocol.ExitNotFound
381 }
382 } else {
383 grant, err := st.AccessRole(repo.ID, user.ID)
384 if err != nil {
385 fmt.Fprintln(stderr, "internal error")
386 return protocol.ExitFailure
387 }
388 if !policy.CanRead(user, repo, grant) {
389 // Same answer as nonexistence: private repos must not be enumerable.
390 fmt.Fprintln(stderr, "repository not found")
391 return protocol.ExitNotFound
392 }
393 if !policy.ScopeAllowsGit(scope, repo.Path(), write) {
394 fmt.Fprintf(stderr, "this key's scope (%s) does not allow %s on %s\n", scope, service, repo.Path())
395 return protocol.ExitDenied
396 }
397 if write && !policy.CanWrite(user, repo, grant) {
398 fmt.Fprintf(stderr, "write access to %s denied\n", repo.Path())
399 return protocol.ExitDenied
400 }
401 }
402 if write && repo.Settings.Archived {
403 fmt.Fprintf(stderr, "%s is archived and read-only\n", repo.Path())
404 return protocol.ExitDenied
405 }
406 if write {
407 if mirrored, err := st.PullMirrored(repo.ID); err == nil && mirrored {
408 fmt.Fprintf(stderr, "%s is a pull mirror: its refs come from the upstream; push there instead\n", repo.Path())
409 return protocol.ExitDenied
410 }
411 }
412
413 dir := control.RepoDir(cfg.Server.Root, repo.OwnerName, repo.Name)
414 env := []string{
415 hookd.EnvSocket + "=" + hookd.SocketPath(cfg.Server.Root),
416 hookd.EnvRepoID + "=" + strconv.FormatInt(repo.ID, 10),
417 hookd.EnvUserID + "=" + strconv.FormatInt(user.ID, 10),
418 hookd.EnvScope + "=" + scope,
419 }
420 // A storage quota on the owner rides the same mechanism as the pack
421 // cap: the pack may be no larger than what the owner has left.
422 maxPack := cfg.Limits.MaxPackBytes
423 if write && repo.OwnerKind == "user" {
424 if limit := control.ByteLimit(st, control.QuotaConfig(cfg), repo.OwnerID); limit > 0 {
425 used := control.OwnedBytes(st, cfg.Server.Root, repo.OwnerID)
426 left := limit - used
427 if left <= 0 {
428 fmt.Fprintf(stderr, "%s's storage quota is used up (%d of %d bytes); delete something, or ask an admin to raise the limit\n", repo.OwnerName, used, limit)
429 return protocol.ExitDenied
430 }
431 if maxPack == 0 || left < maxPack {
432 maxPack = left
433 }
434 }
435 }
436 if err := gitutil.Transport(service, dir, stdin, stdout, stderr, env, maxPack); err != nil {
437 return protocol.ExitFailure
438 }
439 return protocol.ExitOK
440}