forked from gokrazy/rsync
/
anonssh.go
357 lines (306 loc) · 8.17 KB
/
anonssh.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package anonssh
import (
"bufio"
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/binary"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"github.com/google/shlex"
"github.com/superrxan/rsync/internal/log"
"github.com/superrxan/rsync/internal/rsyncdconfig"
"golang.org/x/crypto/ssh"
)
type mainFunc func(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error
type anonssh struct {
cfg *rsyncdconfig.Config
main mainFunc
}
// env is a Environment Variable request as per RFC4254 6.4.
type env struct {
VariableName string
VariableValue string
}
// execR is a Command request as per RFC4254 6.5.
type execR struct {
Command string
}
type session struct {
env []string
ptyf *os.File
ttyf *os.File
channel ssh.Channel
anonssh *anonssh
}
func (s *session) request(ctx context.Context, req *ssh.Request) error {
_ = ctx // FIXME: not yet used
switch req.Type {
case "env":
var r env
if err := ssh.Unmarshal(req.Payload, &r); err != nil {
return err
}
log.Printf("env request: %s=%s", r.VariableName, r.VariableValue)
//s.env = append(s.env, fmt.Sprintf("%s=%s", r.VariableName, r.VariableValue))
case "exec":
var r execR
if err := ssh.Unmarshal(req.Payload, &r); err != nil {
return err
}
cmdline, err := shlex.Split(r.Command)
if err != nil {
return err
}
log.Printf("cmdline: %q", cmdline)
// 2021/09/12 21:25:34 cmdline: ["rsync" "--server" "--daemon" "."]
go func() {
stderr := s.channel.Stderr()
err := s.anonssh.main(cmdline, s.channel, s.channel, stderr)
if err != nil {
fmt.Fprintf(stderr, "%s\n", err)
}
status := make([]byte, 4)
if err != nil {
binary.BigEndian.PutUint32(status, 1)
}
// See https://tools.ietf.org/html/rfc4254#section-6.10
if _, err := s.channel.SendRequest("exit-status", false /* wantReply */, status); err != nil {
log.Printf("err2: %v", err)
}
s.channel.Close()
}()
// stdout, err := cmd.StdoutPipe()
// if err != nil {
// return err
// }
// stdin, err := cmd.StdinPipe()
// if err != nil {
// return err
// }
// stderr, err := cmd.StderrPipe()
// if err != nil {
// return err
// }
// cmd.SysProcAttr.Setsid = true
// if err := cmd.Start(); err != nil {
// return err
// }
// req.Reply(true, nil)
// go io.Copy(s.channel, stdout)
// go io.Copy(s.channel.Stderr(), stderr)
// go func() {
// io.Copy(stdin, s.channel)
// stdin.Close()
// }()
// go func() {
// if err := cmd.Wait(); err != nil {
// log.Printf("err: %v", err)
// }
// status := make([]byte, 4)
// if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {
// binary.BigEndian.PutUint32(status, uint32(ws.ExitStatus()))
// }
// // See https://tools.ietf.org/html/rfc4254#section-6.10
// if _, err := s.channel.SendRequest("exit-status", false /* wantReply */, status); err != nil {
// log.Printf("err2: %v", err)
// }
// s.channel.Close()
// }()
return nil
default:
return fmt.Errorf("unknown request type: %q", req.Type)
}
return nil
}
func (as *anonssh) handleSession(newChannel ssh.NewChannel) {
channel, requests, err := newChannel.Accept()
if err != nil {
log.Printf("Could not accept channel (%s)", err)
return
}
// Sessions have out-of-band requests such as "shell", "pty-req" and "env"
go func(channel ssh.Channel, requests <-chan *ssh.Request) {
ctx, canc := context.WithCancel(context.Background())
defer canc()
s := session{channel: channel, anonssh: as}
for req := range requests {
if err := s.request(ctx, req); err != nil {
log.Printf("request(%q): %v", req.Type, err)
errmsg := []byte(err.Error())
// Append a trailing newline; the error message is
// displayed as-is by ssh(1).
if errmsg[len(errmsg)-1] != '\n' {
errmsg = append(errmsg, '\n')
}
req.Reply(false, errmsg)
channel.Write(errmsg)
channel.Close()
}
}
log.Printf("SSH requests exhausted")
}(channel, requests)
}
func (as *anonssh) handleChannel(newChan ssh.NewChannel) {
switch t := newChan.ChannelType(); t {
case "session":
as.handleSession(newChan)
default:
newChan.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %q", t))
return
}
}
func genHostKey(keyPath string) ([]byte, error) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
x509b, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, err
}
privateKeyPEM := &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509b,
}
f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return nil, err
}
defer f.Close()
b := pem.EncodeToMemory(privateKeyPEM)
if _, err := f.Write(b); err != nil {
return nil, err
}
if err := f.Close(); err != nil {
return nil, err
}
return b, nil
}
type Listener struct {
hostKey ssh.Signer
authorizedKeys map[string]bool
authorizedKeysPath string
}
func ListenerFromConfig(cfg rsyncdconfig.Listener) (*Listener, error) {
hostKey, err := loadHostKey()
if err != nil {
return nil, err
}
var authorizedKeys map[string]bool
if cfg.AuthorizedSSH.Address != "" {
if cfg.AuthorizedSSH.AuthorizedKeys == "" {
return nil, fmt.Errorf("authorized_keys not specified")
}
var err error
authorizedKeys, err = loadAuthorizedKeys(cfg.AuthorizedSSH.AuthorizedKeys)
if err != nil {
return nil, err
}
}
return &Listener{
hostKey: hostKey,
authorizedKeys: authorizedKeys,
authorizedKeysPath: cfg.AuthorizedSSH.AuthorizedKeys,
}, nil
}
func loadHostKey() (ssh.Signer, error) {
dir, err := os.UserConfigDir()
if err != nil {
return nil, err
}
path := filepath.Join(dir, "gokr-rsyncd", "ssh_host_ed25519_key")
b, err := ioutil.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, err
}
b, err = genHostKey(path)
if err != nil {
return nil, err
}
// fall-through
} else {
return nil, err
}
}
return ssh.ParsePrivateKey(b)
}
func loadAuthorizedKeys(path string) (map[string]bool, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
result := make(map[string]bool)
s := bufio.NewScanner(bytes.NewReader(b))
for lineNum := 1; s.Scan(); lineNum++ {
if tr := strings.TrimSpace(s.Text()); tr == "" || strings.HasPrefix(tr, "#") {
continue
}
pubKey, _, _, _, err := ssh.ParseAuthorizedKey(s.Bytes())
// This warning can be removed once the mentioned issue is resolved
if keyType := pubKey.Type(); keyType == "ssh-rsa" {
log.Printf("Warning: ignoring unsupported ssh-rsa key in %s:%d (see https://github.com/gokrazy/breakglass/issues/11)", path, lineNum)
}
if err != nil {
return nil, err
}
result[string(pubKey.Marshal())] = true
}
if err := s.Err(); err != nil {
return nil, err
}
return result, nil
}
func Serve(ln net.Listener, listener *Listener, cfg *rsyncdconfig.Config, main mainFunc) error {
as := &anonssh{
main: main,
}
config := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if listener.authorizedKeys == nil {
log.Printf("user %q successfully authorized from remote addr %s", conn.User(), conn.RemoteAddr())
return nil, nil
}
if listener.authorizedKeys[string(pubKey.Marshal())] {
log.Printf("user %q successfully authorized from remote addr %s", conn.User(), conn.RemoteAddr())
return nil, nil
}
return nil, fmt.Errorf("public key not found in %s", listener.authorizedKeysPath)
},
}
config.AddHostKey(listener.hostKey)
log.Printf("SSH host key fingerprint: %s", ssh.FingerprintSHA256(listener.hostKey.PublicKey()))
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return err
}
log.Printf("accept: %v", err)
continue
}
go func(conn net.Conn) {
_, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
log.Printf("handshake: %v", err)
return
}
// discard all out of band requests
go ssh.DiscardRequests(reqs)
for newChannel := range chans {
as.handleChannel(newChannel)
}
}(conn)
}
}