Debian Codegraph @

internal/anonssh/anonssh.go

raw symbols SCIP
1 package anonssh
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/ed25519"
8 "crypto/rand"
9 "crypto/x509"
10 "encoding/binary"
11 "encoding/pem"
12 "errors"
13 "fmt"
14 "io"
15 "net"
16 "os"
17 "path/filepath"
18 "strings"
19
20 "github.com/gokrazy/rsync/internal/rsyncdconfig"
21 "github.com/gokrazy/rsync/internal/rsyncos"
22 "github.com/google/shlex"
23 "golang.org/x/crypto/ssh"
24 )
25
26 type mainFunc func(args []string, stdin io.ReadCloser, stdout io.WriteCloser, stderr io.WriteCloser) error
27
28 type anonssh struct {
29 cfg *rsyncdconfig.Config
30 main mainFunc
31 osenv *rsyncos.Env
32 }
33
34 // env is a Environment Variable request as per RFC4254 6.4.
35 type env struct {
36 VariableName string
37 VariableValue string
38 }
39
40 // execR is a Command request as per RFC4254 6.5.
41 type execR struct {
42 Command string
43 }
44
45 type session struct {
46 channel ssh.Channel
47 anonssh *anonssh
48 }
49
50 func (s *session) request(ctx context.Context, req *ssh.Request) error {
51 _ = ctx // FIXME: not yet used
52
53 switch req.Type {
54
55 case "env":
56 var r env
57 if err := ssh.Unmarshal(req.Payload, &r); err != nil {
58 return err
59 }
60
61 s.anonssh.osenv.Logf("env request: %s=%s", r.VariableName, r.VariableValue)
62 //s.env = append(s.env, fmt.Sprintf("%s=%s", r.VariableName, r.VariableValue))
63
64 case "exec":
65 var r execR
66 if err := ssh.Unmarshal(req.Payload, &r); err != nil {
67 return err
68 }
69
70 cmdline, err := shlex.Split(r.Command)
71 if err != nil {
72 return err
73 }
74
75 s.anonssh.osenv.Logf("cmdline: %q", cmdline)
76 // 2021/09/12 21:25:34 cmdline: ["rsync" "--server" "--daemon" "."]
77 go func() {
78 stderr := s.channel.Stderr()
79 err := s.anonssh.main(cmdline, s.channel, s.channel, struct {
80 io.Writer
81 io.Closer
82 }{
83 Writer: stderr,
84 Closer: s.channel,
85 })
86 if err != nil {
87 fmt.Fprintf(stderr, "%s\n", err)
88 }
89
90 status := make([]byte, 4)
91 if err != nil {
92 binary.BigEndian.PutUint32(status, 1)
93 }
94
95 // See https://tools.ietf.org/html/rfc4254#section-6.10
96 if _, err := s.channel.SendRequest("exit-status", false /* wantReply */, status); err != nil {
97 s.anonssh.osenv.Logf("err2: %v", err)
98 }
99 s.channel.Close()
100 }()
101
102 if req.WantReply {
103 req.Reply(true, nil)
104 }
105
106 return nil
107
108 default:
109 return fmt.Errorf("unknown request type: %q", req.Type)
110 }
111
112 return nil
113 }
114
115 func (as *anonssh) handleSession(newChannel ssh.NewChannel) {
116 channel, requests, err := newChannel.Accept()
117 if err != nil {
118 as.osenv.Logf("Could not accept channel (%s)", err)
119 return
120 }
121
122 // Sessions have out-of-band requests such as "shell", "pty-req" and "env"
123 go func(channel ssh.Channel, requests <-chan *ssh.Request) {
124 ctx, canc := context.WithCancel(context.Background())
125 defer canc()
126 s := session{
127 channel: channel,
128 anonssh: as,
129 }
130 for req := range requests {
131 if err := s.request(ctx, req); err != nil {
132 s.anonssh.osenv.Logf("request(%q): %v", req.Type, err)
133 errmsg := []byte(err.Error())
134 // Append a trailing newline; the error message is
135 // displayed as-is by ssh(1).
136 if errmsg[len(errmsg)-1] != '\n' {
137 errmsg = append(errmsg, '\n')
138 }
139 req.Reply(false, errmsg)
140 channel.Write(errmsg)
141 channel.Close()
142 }
143 }
144 s.anonssh.osenv.Logf("SSH requests exhausted")
145 }(channel, requests)
146 }
147
148 func (as *anonssh) handleChannel(newChan ssh.NewChannel) {
149 switch t := newChan.ChannelType(); t {
150 case "session":
151 as.handleSession(newChan)
152 default:
153 newChan.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %q", t))
154 return
155 }
156 }
157
158 func genHostKey(keyPath string) ([]byte, error) {
159 _, privateKey, err := ed25519.GenerateKey(rand.Reader)
160 if err != nil {
161 return nil, err
162 }
163
164 x509b, err := x509.MarshalPKCS8PrivateKey(privateKey)
165 if err != nil {
166 return nil, err
167 }
168 privateKeyPEM := &pem.Block{
169 Type: "PRIVATE KEY",
170 Bytes: x509b,
171 }
172 f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
173 if err != nil {
174 return nil, err
175 }
176 defer f.Close()
177
178 b := pem.EncodeToMemory(privateKeyPEM)
179 if _, err := f.Write(b); err != nil {
180 return nil, err
181 }
182 if err := f.Close(); err != nil {
183 return nil, err
184 }
185
186 return b, nil
187 }
188
189 type Listener struct {
190 hostKey ssh.Signer
191 authorizedKeys map[string]bool
192 authorizedKeysPath string
193 }
194
195 func ListenerFromConfig(osenv *rsyncos.Env, cfg rsyncdconfig.Listener) (*Listener, error) {
196 hostKeyPath := cfg.HostKeyPath
197 if hostKeyPath == "" {
198 dir, err := os.UserConfigDir()
199 if err != nil {
200 return nil, err
201 }
202 hostKeyPath = filepath.Join(dir, "gokr-rsyncd", "ssh_host_ed25519_key")
203 }
204 hostKey, err := loadHostKey(hostKeyPath)
205 if err != nil {
206 return nil, err
207 }
208
209 var authorizedKeys map[string]bool
210 if cfg.AuthorizedSSH.Address != "" {
211 if cfg.AuthorizedSSH.AuthorizedKeys == "" {
212 return nil, fmt.Errorf("authorized_keys not specified")
213 }
214
215 var err error
216 authorizedKeys, err = loadAuthorizedKeys(osenv, cfg.AuthorizedSSH.AuthorizedKeys)
217 if err != nil {
218 return nil, err
219 }
220 }
221
222 return &Listener{
223 hostKey: hostKey,
224 authorizedKeys: authorizedKeys,
225 authorizedKeysPath: cfg.AuthorizedSSH.AuthorizedKeys,
226 }, nil
227 }
228
229 func loadHostKey(path string) (ssh.Signer, error) {
230 b, err := os.ReadFile(path)
231 if err != nil {
232 if os.IsNotExist(err) {
233 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
234 return nil, err
235 }
236 b, err = genHostKey(path)
237 if err != nil {
238 return nil, err
239 }
240 // fall-through
241 } else {
242 return nil, err
243 }
244 }
245 return ssh.ParsePrivateKey(b)
246 }
247
248 func loadAuthorizedKeys(osenv *rsyncos.Env, path string) (map[string]bool, error) {
249 b, err := os.ReadFile(path)
250 if err != nil {
251 return nil, err
252 }
253
254 result := make(map[string]bool)
255
256 s := bufio.NewScanner(bytes.NewReader(b))
257 for lineNum := 1; s.Scan(); lineNum++ {
258 if tr := strings.TrimSpace(s.Text()); tr == "" || strings.HasPrefix(tr, "#") {
259 continue
260 }
261 pubKey, _, _, _, err := ssh.ParseAuthorizedKey(s.Bytes())
262
263 // This warning can be removed once the mentioned issue is resolved
264 if keyType := pubKey.Type(); keyType == "ssh-rsa" {
265 osenv.Logf("Warning: ignoring unsupported ssh-rsa key in %s:%d (see https://github.com/gokrazy/breakglass/issues/11)", path, lineNum)
266 }
267
268 if err != nil {
269 return nil, err
270 }
271 result[string(pubKey.Marshal())] = true
272 }
273 if err := s.Err(); err != nil {
274 return nil, err
275 }
276
277 return result, nil
278 }
279
280 func Serve(ctx context.Context, osenv *rsyncos.Env, ln net.Listener, listener *Listener, cfg *rsyncdconfig.Config, main mainFunc) error {
281 go func() {
282 <-ctx.Done()
283 ln.Close() // unblocks Accept()
284 }()
285
286 as := &anonssh{
287 cfg: cfg,
288 main: main,
289 osenv: osenv,
290 }
291
292 config := &ssh.ServerConfig{
293 PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
294 if listener.authorizedKeys == nil {
295 osenv.Logf("user %q successfully authorized from remote addr %s", conn.User(), conn.RemoteAddr())
296 return nil, nil
297 }
298 if listener.authorizedKeys[string(pubKey.Marshal())] {
299 osenv.Logf("user %q successfully authorized from remote addr %s", conn.User(), conn.RemoteAddr())
300 return nil, nil
301 }
302 return nil, fmt.Errorf("public key not found in %s", listener.authorizedKeysPath)
303 },
304 }
305
306 config.AddHostKey(listener.hostKey)
307
308 osenv.Logf("SSH host key fingerprint: %s", ssh.FingerprintSHA256(listener.hostKey.PublicKey()))
309
310 for {
311 conn, err := ln.Accept()
312 if err != nil {
313 select {
314 case <-ctx.Done():
315 return nil // ignore expected 'use of closed network connection' error on context cancel
316 default:
317 }
318
319 if errors.Is(err, net.ErrClosed) {
320 return err
321 }
322 osenv.Logf("accept: %v", err)
323 continue
324 }
325
326 go func(conn net.Conn) {
327 _, chans, reqs, err := ssh.NewServerConn(conn, config)
328 if err != nil {
329 osenv.Logf("handshake: %v", err)
330 return
331 }
332
333 // discard all out of band requests
334 go ssh.DiscardRequests(reqs)
335
336 for newChannel := range chans {
337 as.handleChannel(newChannel)
338 }
339 }(conn)
340 }
341 }