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