ssh.go

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