-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
288 lines (253 loc) · 7.07 KB
/
middleware.go
File metadata and controls
288 lines (253 loc) · 7.07 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package ssh
import (
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"time"
"charm.land/log/v2"
"charm.land/wish/v2"
"github.com/charmbracelet/ssh"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/spf13/cobra"
"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/ssh/cmd"
"github.com/urutau-ltd/git-cone/pkg/sshutils"
"github.com/urutau-ltd/git-cone/pkg/store"
gossh "golang.org/x/crypto/ssh"
"golang.org/x/time/rate"
)
// ErrPermissionDenied is returned when a user is not allowed connect.
var ErrPermissionDenied = fmt.Errorf("permission denied")
// AuthenticationMiddleware handles authentication.
func AuthenticationMiddleware(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
// XXX: The authentication key is set in the context but gossh doesn't
// validate the authentication. We need to verify that the _last_ key
// that was approved is the one that's being used.
ctx := s.Context()
be := backend.FromContext(ctx)
var pkFp string
perms := s.Permissions().Permissions
pk := s.PublicKey()
if pk != nil {
// There is no public key stored in the context, public-key auth
// was never requested, skip
if perms == nil {
wish.Fatalln(s, ErrPermissionDenied)
return
}
pkFp = gossh.FingerprintSHA256(pk)
}
// Check if the key is the same as the one we have in context
fp := perms.Extensions["pubkey-fp"]
if fp != "" && fp != pkFp {
be.TrackAuthFailure(remoteIP(s))
wish.Fatalln(s, ErrPermissionDenied)
return
}
ac := be.AllowKeyless(ctx)
publicKeyCounter.WithLabelValues(strconv.FormatBool(ac || pk != nil)).Inc()
if !ac && pk == nil {
be.TrackAuthFailure(remoteIP(s))
wish.Fatalln(s, ErrPermissionDenied)
return
}
// Set the auth'd user, or anon, in the context
var user proto.User
if pk != nil {
var err error
user, err = authenticatedUserForPublicKey(ctx, be, config.FromContext(ctx), pk)
if err != nil {
if errors.Is(err, proto.ErrUserNotFound) {
be.TrackAuthFailure(remoteIP(s))
wish.Fatalln(s, ErrPermissionDenied)
return
}
wish.Fatalln(s, err)
return
}
}
ctx.SetValue(proto.ContextKeyUser, user)
sh(s)
}
}
func authenticatedUserForPublicKey(ctx context.Context, be *backend.Backend, cfg *config.Config, pk gossh.PublicKey) (proto.User, error) {
if pk == nil {
return nil, proto.ErrUserNotFound
}
user, err := be.UserByPublicKey(ctx, pk)
if err == nil {
return user, nil
}
if !errors.Is(err, proto.ErrUserNotFound) {
return nil, err
}
if cmd.IsPublicKeyAdmin(cfg, pk) {
return nil, nil
}
return nil, proto.ErrUserNotFound
}
func remoteIP(s ssh.Session) string {
host, _, err := net.SplitHostPort(s.RemoteAddr().String())
if err == nil {
return host
}
return s.RemoteAddr().String()
}
// ContextMiddleware adds the config, backend, and logger to the session context.
func ContextMiddleware(cfg *config.Config, dbx *db.DB, datastore store.Store, be *backend.Backend, logger *log.Logger) func(ssh.Handler) ssh.Handler {
return func(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
ctx := s.Context()
ctx.SetValue(sshutils.ContextKeySession, s)
ctx.SetValue(config.ContextKey, cfg)
ctx.SetValue(db.ContextKey, dbx)
ctx.SetValue(store.ContextKey, datastore)
ctx.SetValue(backend.ContextKey, be)
ctx.SetValue(log.ContextKey, logger.WithPrefix("ssh"))
sh(s)
}
}
}
var cliCommandCounter = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "soft_serve",
Subsystem: "cli",
Name: "commands_total",
Help: "Total times each command was called",
}, []string{"command"})
// CommandMiddleware handles git commands and CLI commands.
// This middleware must be run after the ContextMiddleware.
func CommandMiddleware(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
_, _, ptyReq := s.Pty()
if ptyReq {
sh(s)
return
}
ctx := s.Context()
cfg := config.FromContext(ctx)
args := s.Command()
cliCommandCounter.WithLabelValues(cmd.CommandName(args)).Inc()
rootCmd := &cobra.Command{
Short: "cone is a self-hosted Git server for the command line.",
SilenceUsage: true,
}
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.SetUsageTemplate(cmd.UsageTemplate)
rootCmd.SetUsageFunc(cmd.UsageFunc)
rootCmd.AddCommand(
cmd.GitUploadPackCommand(),
cmd.GitUploadArchiveCommand(),
cmd.GitReceivePackCommand(),
cmd.RepoCommand(),
cmd.SettingsCommand(),
cmd.UserCommand(),
cmd.InfoCommand(),
cmd.PubkeyCommand(),
cmd.SetUsernameCommand(),
cmd.JWTCommand(),
cmd.TokenCommand(),
cmd.AuditCommand(),
cmd.DoctorCommand(),
)
if cfg.LFS.Enabled {
rootCmd.AddCommand(
cmd.GitLFSAuthenticateCommand(),
)
if cfg.LFS.SSHEnabled {
rootCmd.AddCommand(
cmd.GitLFSTransfer(),
)
}
}
rootCmd.SetArgs(args)
if len(args) == 0 {
// otherwise it'll default to os.Args, which is not what we want.
rootCmd.SetArgs([]string{"--help"})
}
rootCmd.SetIn(s)
rootCmd.SetOut(s)
rootCmd.SetErr(s.Stderr())
rootCmd.SetContext(ctx)
if err := rootCmd.ExecuteContext(ctx); err != nil {
s.Exit(1) //nolint: errcheck
return
}
}
}
// LoggingMiddleware logs the ssh connection and command.
func LoggingMiddleware(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
ctx := s.Context()
logger := log.FromContext(ctx).WithPrefix("ssh")
ct := time.Now()
hpk := sshutils.MarshalAuthorizedKey(s.PublicKey())
ptyReq, _, isPty := s.Pty()
addr := s.RemoteAddr().String()
user := proto.UserFromContext(ctx)
logArgs := []interface{}{
"addr",
addr,
"cmd",
s.Command(),
}
if user != nil {
logArgs = append([]interface{}{
"username",
user.Username(),
}, logArgs...)
}
if isPty {
logArgs = []interface{}{
"term", ptyReq.Term,
"width", ptyReq.Window.Width,
"height", ptyReq.Window.Height,
}
}
if config.IsVerbose() {
logArgs = append(logArgs,
"key", hpk,
"envs", s.Environ(),
)
}
msg := fmt.Sprintf("user %q", s.User())
logger.Debug(msg+" connected", logArgs...)
sh(s)
logger.Debug(msg+" disconnected", append(logArgs, "duration", time.Since(ct))...)
}
}
// InputRateLimitMiddleware limits SSH stdin events to prevent DoS via rapid
// key input (e.g. spamming Tab in the BubbleTea TUI causing CPU spikes).
func InputRateLimitMiddleware(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
lim := rate.NewLimiter(rate.Every(50*time.Millisecond), 100)
sh(limitedSession{Session: s, r: &rateLimitedReader{
r: s,
lim: lim,
ctx: s.Context(),
}})
}
}
type limitedSession struct {
ssh.Session
r io.Reader
}
func (ls limitedSession) Read(p []byte) (int, error) { return ls.r.Read(p) }
type rateLimitedReader struct {
r io.Reader
lim *rate.Limiter
ctx context.Context
}
func (r *rateLimitedReader) Read(p []byte) (int, error) {
if err := r.lim.Wait(r.ctx); err != nil {
return 0, err
}
return r.r.Read(p)
}