1package ssh
2
3import (
4 "context"
5 "fmt"
6 "net"
7 "os"
8 "strconv"
9 "time"
10
11 "charm.land/log/v2"
12 "charm.land/wish/v2"
13 bm "charm.land/wish/v2/bubbletea"
14 rm "charm.land/wish/v2/recover"
15 "github.com/charmbracelet/keygen"
16 "github.com/charmbracelet/soft-serve/pkg/backend"
17 "github.com/charmbracelet/soft-serve/pkg/config"
18 "github.com/charmbracelet/soft-serve/pkg/db"
19 "github.com/charmbracelet/soft-serve/pkg/store"
20 "github.com/charmbracelet/ssh"
21 "github.com/prometheus/client_golang/prometheus"
22 "github.com/prometheus/client_golang/prometheus/promauto"
23 gossh "golang.org/x/crypto/ssh"
24)
25
26var (
27 publicKeyCounter = promauto.NewCounterVec(prometheus.CounterOpts{
28 Namespace: "soft_serve",
29 Subsystem: "ssh",
30 Name: "public_key_auth_total",
31 Help: "The total number of public key auth requests",
32 }, []string{"allowed"})
33
34 keyboardInteractiveCounter = promauto.NewCounterVec(prometheus.CounterOpts{
35 Namespace: "soft_serve",
36 Subsystem: "ssh",
37 Name: "keyboard_interactive_auth_total",
38 Help: "The total number of keyboard interactive auth requests",
39 }, []string{"allowed"})
40)
41
42// SSHServer is a SSH server that implements the git protocol.
43type SSHServer struct { //nolint: revive
44 srv *ssh.Server
45 cfg *config.Config
46 be *backend.Backend
47 ctx context.Context
48 logger *log.Logger
49}
50
51// NewSSHServer returns a new SSHServer.
52func NewSSHServer(ctx context.Context) (*SSHServer, error) {
53 cfg := config.FromContext(ctx)
54 logger := log.FromContext(ctx).WithPrefix("ssh")
55 dbx := db.FromContext(ctx)
56 datastore := store.FromContext(ctx)
57 be := backend.FromContext(ctx)
58
59 var err error
60 s := &SSHServer{
61 cfg: cfg,
62 ctx: ctx,
63 be: be,
64 logger: logger,
65 }
66
67 mw := []wish.Middleware{
68 rm.MiddlewareWithLogger(
69 logger,
70 // BubbleTea middleware.
71 bm.MiddlewareWithProgramHandler(SessionHandler),
72 // CLI middleware.
73 CommandMiddleware,
74 // Logging middleware.
75 LoggingMiddleware,
76 // Authentication middleware.
77 // gossh.PublicKeyHandler doesn't guarantee that the public key
78 // is in fact the one used for authentication, so we need to
79 // check it again here.
80 AuthenticationMiddleware,
81 // Context middleware.
82 // This must come first to set up the context.
83 ContextMiddleware(cfg, dbx, datastore, be, logger),
84 ),
85 }
86
87 opts := []ssh.Option{
88 ssh.PublicKeyAuth(s.PublicKeyHandler),
89 ssh.KeyboardInteractiveAuth(s.KeyboardInteractiveHandler),
90 wish.WithAddress(cfg.SSH.ListenAddr),
91 wish.WithHostKeyPath(cfg.SSH.KeyPath),
92 wish.WithMiddleware(mw...),
93 }
94
95 // TODO: Support a real PTY in future version.
96 opts = append(opts, ssh.EmulatePty())
97
98 s.srv, err = wish.NewServer(opts...)
99 if err != nil {
100 return nil, err
101 }
102
103 if config.IsDebug() {
104 s.srv.ServerConfigCallback = func(_ ssh.Context) *gossh.ServerConfig {
105 return &gossh.ServerConfig{
106 AuthLogCallback: func(conn gossh.ConnMetadata, method string, err error) {
107 logger.Debug("authentication", "user", conn.User(), "method", method, "err", err)
108 },
109 }
110 }
111 }
112
113 if cfg.SSH.MaxTimeout > 0 {
114 s.srv.MaxTimeout = time.Duration(cfg.SSH.MaxTimeout) * time.Second
115 }
116
117 if cfg.SSH.IdleTimeout > 0 {
118 s.srv.IdleTimeout = time.Duration(cfg.SSH.IdleTimeout) * time.Second
119 }
120
121 // Create client ssh key
122 if _, err := os.Stat(cfg.SSH.ClientKeyPath); err != nil && os.IsNotExist(err) {
123 _, err := keygen.New(cfg.SSH.ClientKeyPath, keygen.WithKeyType(keygen.Ed25519), keygen.WithWrite())
124 if err != nil {
125 return nil, fmt.Errorf("client ssh key: %w", err)
126 }
127 }
128
129 return s, nil
130}
131
132// ListenAndServe starts the SSH server.
133func (s *SSHServer) ListenAndServe() error {
134 return s.srv.ListenAndServe()
135}
136
137// Serve starts the SSH server on the given net.Listener.
138func (s *SSHServer) Serve(l net.Listener) error {
139 return s.srv.Serve(l)
140}
141
142// Close closes the SSH server.
143func (s *SSHServer) Close() error {
144 return s.srv.Close()
145}
146
147// Shutdown gracefully shuts down the SSH server.
148func (s *SSHServer) Shutdown(ctx context.Context) error {
149 return s.srv.Shutdown(ctx)
150}
151
152func initializePermissions(ctx ssh.Context) {
153 perms := ctx.Permissions()
154 if perms == nil || perms.Permissions == nil {
155 perms = &ssh.Permissions{Permissions: &gossh.Permissions{}}
156 }
157 if perms.Extensions == nil {
158 perms.Extensions = make(map[string]string)
159 }
160}
161
162// PublicKeyHandler handles public key authentication.
163func (s *SSHServer) PublicKeyHandler(ctx ssh.Context, pk ssh.PublicKey) (allowed bool) {
164 if pk == nil {
165 return false
166 }
167
168 allowed = true
169
170 // XXX: store the first "approved" public-key fingerprint in the
171 // permissions block to use for authentication later.
172 initializePermissions(ctx)
173 perms := ctx.Permissions()
174
175 // Set the public key fingerprint to be used for authentication.
176 perms.Extensions["pubkey-fp"] = gossh.FingerprintSHA256(pk)
177 ctx.SetValue(ssh.ContextKeyPermissions, perms)
178
179 return
180}
181
182// KeyboardInteractiveHandler handles keyboard interactive authentication.
183// This is used after all public key authentication has failed.
184func (s *SSHServer) KeyboardInteractiveHandler(ctx ssh.Context, _ gossh.KeyboardInteractiveChallenge) bool {
185 ac := s.be.AllowKeyless(ctx)
186 keyboardInteractiveCounter.WithLabelValues(strconv.FormatBool(ac)).Inc()
187
188 // If we're allowing keyless access, reset the public key fingerprint
189 initializePermissions(ctx)
190 perms := ctx.Permissions()
191
192 if ac {
193 // XXX: reset the public-key fingerprint. This is used to validate the
194 // public key being used to authenticate.
195 perms.Extensions["pubkey-fp"] = ""
196 ctx.SetValue(ssh.ContextKeyPermissions, perms)
197 }
198 return ac
199}