-
Notifications
You must be signed in to change notification settings - Fork 8
/
ssh.go
163 lines (136 loc) Β· 3.86 KB
/
ssh.go
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
package server
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/bubbletea"
"github.com/gabe565/ascii-movie/internal/movie"
"github.com/gabe565/ascii-movie/internal/player"
"github.com/gabe565/ascii-movie/internal/util"
"github.com/muesli/termenv"
flag "github.com/spf13/pflag"
gossh "golang.org/x/crypto/ssh"
"golang.org/x/sync/errgroup"
)
//nolint:gochecknoglobals
var sshListeners uint8
type SSHServer struct {
MovieServer
HostKeyPath []string
HostKeyPEM []string
}
func NewSSH(flags *flag.FlagSet) SSHServer {
ssh := SSHServer{MovieServer: NewMovieServer(flags, SSHFlagPrefix)}
var err error
if ssh.HostKeyPath, err = flags.GetStringSlice(SSHHostKeyPathFlag); err != nil {
panic(err)
}
if ssh.HostKeyPEM, err = flags.GetStringSlice(SSHHostKeyDataFlag); err != nil {
panic(err)
}
if len(ssh.HostKeyPath) == 0 && len(ssh.HostKeyPEM) == 0 {
ssh.HostKeyPath = []string{"$HOME/.ssh/ascii_movie_ed25519", "$HOME/.ssh/ascii_movie_rsa"}
}
return ssh
}
func (s *SSHServer) Listen(ctx context.Context, m *movie.Movie) error {
s.Log.Info().Str("address", s.Address).Msg("Starting SSH server")
sshOptions := []ssh.Option{
wish.WithAddress(s.Address),
wish.WithIdleTimeout(idleTimeout),
wish.WithMaxTimeout(maxTimeout),
wish.WithMiddleware(
bubbletea.Middleware(s.Handler(m)),
s.TrackStream,
),
}
for _, pem := range s.HostKeyPEM {
sshOptions = append(sshOptions, wish.WithHostKeyPEM([]byte(pem)))
}
for _, path := range s.HostKeyPath {
if strings.Contains(path, "$HOME") {
home, err := os.UserHomeDir()
if err != nil {
return err
}
path = strings.ReplaceAll(path, "$HOME", home)
}
sshOptions = append(sshOptions, wish.WithHostKeyPath(path))
}
server, err := wish.NewServer(sshOptions...)
if err != nil {
return err
}
for _, signer := range server.HostSigners {
s.Log.Debug().
Str("type", signer.PublicKey().Type()).
Str("fingerprint", gossh.FingerprintSHA256(signer.PublicKey())).
Msg("Using host key")
}
group, ctx := errgroup.WithContext(ctx)
group.Go(func() error {
if ctx.Err() != nil {
return ctx.Err()
}
sshListeners++
defer func() {
sshListeners--
}()
if err = server.ListenAndServe(); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
return fmt.Errorf("failed to start server: %w", err)
}
return nil
})
group.Go(func() error {
<-ctx.Done()
s.Log.Info().Msg("Stopping SSH server")
defer s.Log.Info().Msg("Stopped SSH server")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
return server.Shutdown(shutdownCtx)
})
return group.Wait()
}
func (s *SSHServer) Handler(m *movie.Movie) bubbletea.Handler {
return func(session ssh.Session) (tea.Model, []tea.ProgramOption) {
remoteIP := RemoteIP(session.RemoteAddr().String())
logger := s.Log.With().
Str("remote_ip", remoteIP).
Str("user", session.User()).
Logger()
renderer := bubbletea.MakeRenderer(session)
if renderer.ColorProfile() == termenv.Ascii {
if pty, _, ok := session.Pty(); ok {
renderer.SetColorProfile(util.Profile(pty.Term))
}
}
player := player.NewPlayer(m, logger, renderer)
return player, []tea.ProgramOption{
tea.WithFPS(30),
tea.WithAltScreen(),
tea.WithMouseCellMotion(),
}
}
}
func (s *SSHServer) TrackStream(handler ssh.Handler) ssh.Handler {
return func(session ssh.Session) {
remoteIP := RemoteIP(session.RemoteAddr().String())
id, err := serverInfo.StreamConnect("ssh", remoteIP)
if err != nil {
s.Log.Err(err).
Str("remote_ip", remoteIP).
Str("user", session.User()).
Msg("Failed to begin stream")
_, _ = session.Write([]byte(ErrorText(err) + "\n"))
return
}
defer serverInfo.StreamDisconnect(id)
handler(session)
}
}