Debian Codegraph @

sshd/server.go

raw
1 package sshd
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net"
10 "sync"
11
12 "github.com/armon/go-radix"
13 "golang.org/x/crypto/ssh"
14 )
15
16 type SSHServer struct {
17 config *ssh.ServerConfig
18 l *slog.Logger
19
20 certChecker *ssh.CertChecker
21
22 // authLock guards trustedKeys and trustedCAs
23 authLock sync.RWMutex
24 // Map of user -> authorized keys
25 trustedKeys map[string]map[string]bool
26 trustedCAs []ssh.PublicKey
27
28 // List of available commands
29 helpCommand *Command
30 commands *radix.Tree
31 listener net.Listener
32
33 // ctx parents per-Run contexts. Cancelling it (e.g. via Control.Stop) tears the server down even
34 // across reloads, since each Run derives a fresh child rather than reusing this one directly.
35 ctx context.Context
36 }
37
38 // NewSSHServer creates a new ssh server rigged with default commands and prepares to listen.
39 // The ssh server's context is parented off the supplied ctx so cancelling it
40 // (e.g. on Control.Stop) tears down active sessions and closes the listener.
41 func NewSSHServer(ctx context.Context, l *slog.Logger) (*SSHServer, error) {
42 s := &SSHServer{
43 trustedKeys: make(map[string]map[string]bool),
44 l: l,
45 commands: radix.New(),
46 ctx: ctx,
47 }
48
49 cc := ssh.CertChecker{
50 IsUserAuthority: func(auth ssh.PublicKey) bool {
51 s.authLock.RLock()
52 defer s.authLock.RUnlock()
53 for _, ca := range s.trustedCAs {
54 if bytes.Equal(ca.Marshal(), auth.Marshal()) {
55 return true
56 }
57 }
58
59 return false
60 },
61 UserKeyFallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
62 pk := string(pubKey.Marshal())
63 fp := ssh.FingerprintSHA256(pubKey)
64
65 s.authLock.RLock()
66 defer s.authLock.RUnlock()
67 tk, ok := s.trustedKeys[c.User()]
68 if !ok {
69 return nil, fmt.Errorf("unknown user %s", c.User())
70 }
71
72 _, ok = tk[pk]
73 if !ok {
74 return nil, fmt.Errorf("unknown public key for %s (%s)", c.User(), fp)
75 }
76
77 return &ssh.Permissions{
78 // Record the public key used for authentication.
79 Extensions: map[string]string{
80 "fp": fp,
81 "user": c.User(),
82 },
83 }, nil
84
85 },
86 }
87
88 s.config = &ssh.ServerConfig{
89 PublicKeyCallback: cc.Authenticate,
90 ServerVersion: fmt.Sprintf("SSH-2.0-Nebula???"),
91 }
92
93 s.RegisterCommand(&Command{
94 Name: "help",
95 ShortDescription: "prints available commands or help <command> for specific usage info",
96 Callback: func(a any, args []string, w StringWriter) error {
97 return helpCallback(s.commands, args, w)
98 },
99 })
100
101 return s, nil
102 }
103
104 func (s *SSHServer) SetHostKey(hostPrivateKey []byte) error {
105 private, err := ssh.ParsePrivateKey(hostPrivateKey)
106 if err != nil {
107 return fmt.Errorf("failed to parse private key: %s", err)
108 }
109
110 s.config.AddHostKey(private)
111 return nil
112 }
113
114 func (s *SSHServer) ClearTrustedCAs() {
115 s.authLock.Lock()
116 s.trustedCAs = []ssh.PublicKey{}
117 s.authLock.Unlock()
118 }
119
120 func (s *SSHServer) ClearAuthorizedKeys() {
121 s.authLock.Lock()
122 s.trustedKeys = make(map[string]map[string]bool)
123 s.authLock.Unlock()
124 }
125
126 // AddTrustedCA adds a trusted CA for user certificates
127 func (s *SSHServer) AddTrustedCA(pubKey string) error {
128 pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
129 if err != nil {
130 return err
131 }
132
133 s.authLock.Lock()
134 s.trustedCAs = append(s.trustedCAs, pk)
135 s.authLock.Unlock()
136 s.l.Info("Trusted CA key", "sshKey", pubKey)
137 return nil
138 }
139
140 // AddAuthorizedKey adds an ssh public key for a user
141 func (s *SSHServer) AddAuthorizedKey(user, pubKey string) error {
142 pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKey))
143 if err != nil {
144 return err
145 }
146
147 s.authLock.Lock()
148 tk, ok := s.trustedKeys[user]
149 if !ok {
150 tk = make(map[string]bool)
151 s.trustedKeys[user] = tk
152 }
153
154 tk[string(pk.Marshal())] = true
155 s.authLock.Unlock()
156 s.l.Info("Authorized ssh key",
157 "sshKey", pubKey,
158 "sshUser", user,
159 )
160 return nil
161 }
162
163 // RegisterCommand adds a command that can be run by a user, by default only `help` is available
164 func (s *SSHServer) RegisterCommand(c *Command) {
165 s.commands.Insert(c.Name, c)
166 }
167
168 // Run begins listening and accepting connections. Each invocation derives a fresh per-Run context
169 // from the constructor-supplied ctx so a Stop+Run sequence (used by config reload) starts clean
170 // rather than carrying a permanently-cancelled context across runs.
171 func (s *SSHServer) Run(addr string) error {
172 if s.ctx.Err() != nil {
173 return s.ctx.Err()
174 }
175
176 listener, err := net.Listen("tcp", addr)
177 if err != nil {
178 return err
179 }
180 // s.listener is the public handle Stop uses to interrupt the active run; listener (the local) is what
181 // this run owns. They start equal but a fast reload may overwrite s.listener with the next run's
182 // listener before this run's watcher fires, so each run must close its own listener via the local
183 // reference.
184 s.listener = listener
185
186 runCtx, cancel := context.WithCancel(s.ctx)
187 defer cancel()
188
189 // Close the listener when this run's context is cancelled. That can come from the parent
190 // (Control.Stop), from Run returning normally (defer cancel above), or transitively when a sibling
191 // run cancels through Stop closing the listener. net.Listener.Close is idempotent so a duplicate
192 // close from Stop is benign.
193 go func() {
194 <-runCtx.Done()
195 if err := listener.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
196 s.l.Warn("Failed to close the sshd listener", "error", err)
197 }
198 }()
199
200 s.l.Info("SSH server is listening", "sshListener", addr)
201
202 // Run loops until there is an error
203 s.run(runCtx, listener)
204
205 s.l.Info("SSH server stopped listening")
206 // We don't return an error because run logs for us
207 return nil
208 }
209
210 func (s *SSHServer) run(ctx context.Context, listener net.Listener) {
211 for {
212 c, err := listener.Accept()
213 if err != nil {
214 if !errors.Is(err, net.ErrClosed) {
215 s.l.Warn("Error in listener, shutting down", "error", err)
216 }
217 return
218 }
219 go func(c net.Conn) {
220 // NewServerConn may block while waiting for the client to complete the handshake.
221 // Ensure that a bad client doesn't hurt us by checking for the parent context
222 // cancellation before calling NewServerConn, and forcing the socket to close when
223 // the context is cancelled.
224 sessionContext, sessionCancel := context.WithCancel(ctx)
225 go func() {
226 <-sessionContext.Done()
227 c.Close()
228 }()
229 conn, chans, reqs, err := ssh.NewServerConn(c, s.config)
230 fp := ""
231 if conn != nil {
232 fp = conn.Permissions.Extensions["fp"]
233 }
234
235 if err != nil {
236 l := s.l.With(
237 "error", err,
238 "remoteAddress", c.RemoteAddr(),
239 )
240 if conn != nil {
241 l = l.With("sshUser", conn.User())
242 conn.Close()
243 }
244 if fp != "" {
245 l = l.With("sshFingerprint", fp)
246 }
247 l.Warn("failed to handshake")
248 sessionCancel()
249 return
250 }
251
252 l := s.l.With("sshUser", conn.User())
253 l.Info("ssh user logged in",
254 "remoteAddress", c.RemoteAddr(),
255 "sshFingerprint", fp,
256 )
257
258 NewSession(s.commands, conn, chans, sessionCancel, l.With("subsystem", "sshd.session"))
259
260 go ssh.DiscardRequests(reqs)
261
262 }(c)
263 }
264 }
265
266 func (s *SSHServer) Stop() {
267 if s.listener != nil {
268 if err := s.listener.Close(); err != nil {
269 s.l.Warn("Failed to close the sshd listener", "error", err)
270 }
271 }
272 }