/
fns.go
324 lines (299 loc) · 8.78 KB
/
fns.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
// Copyright 2018-2019 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package client
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
// We use this ssh because it implements port redirection.
// It can not, however, unpack password-protected keys yet.
config "github.com/kevinburke/ssh_config"
// We use this ssh because it can unpack password-protected private keys.
ssh "golang.org/x/crypto/ssh"
)
const (
// DefaultPort is the default cpu port.
DefaultPort = "17010"
)
var (
// DefaultKeyFile is the default key for cpu users.
DefaultKeyFile = filepath.Join(os.Getenv("HOME"), ".ssh/cpu_rsa")
// Debug9p enables 9p debugging.
Debug9p bool
// Dump9p enables dumping 9p packets.
Dump9p bool
// DumpWriter is an io.Writer to which dump packets are written.
DumpWriter io.Writer = os.Stderr
)
// a nonce is a [32]byte containing only printable characters, suitable for use as a string
type nonce [32]byte
func verbose(f string, a ...interface{}) {
v("client:"+f, a...)
}
// generateNonce returns a nonce, or an error if random reader fails.
func generateNonce() (nonce, error) {
var b [len(nonce{}) / 2]byte
if _, err := rand.Read(b[:]); err != nil {
return nonce{}, err
}
var n nonce
copy(n[:], fmt.Sprintf("%02x", b))
return n, nil
}
// String is a Stringer for nonce.
func (n nonce) String() string {
return string(n[:])
}
// UserKeyConfig sets up authentication for a User Key.
// It is required in almost all cases.
func (c *Cmd) UserKeyConfig() error {
if c.DisablePrivateKey {
verbose("Not using a key file to encrypt the ssh connection")
return nil
}
kf := c.PrivateKeyFile
if len(kf) == 0 {
kf = config.Get(c.Host, "IdentityFile")
verbose("key file from config is %q", kf)
if len(kf) == 0 {
kf = DefaultKeyFile
}
}
// The kf will always be non-zero at this point.
if strings.HasPrefix(kf, "~/") {
kf = filepath.Join(os.Getenv("HOME"), kf[1:])
}
key, err := os.ReadFile(kf)
if err != nil {
return fmt.Errorf("unable to read private key %q: %v", kf, err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return fmt.Errorf("ParsePrivateKey %q: %v", kf, err)
}
c.config.Auth = append(c.config.Auth, ssh.PublicKeys(signer))
return nil
}
// HostKeyConfig sets the host key. It is optional.
func (c *Cmd) HostKeyConfig(hostKeyFile string) error {
hk, err := os.ReadFile(hostKeyFile)
if err != nil {
return fmt.Errorf("unable to read host key %v: %v", hostKeyFile, err)
}
pk, err := ssh.ParsePublicKey(hk)
if err != nil {
return fmt.Errorf("host key %v: %v", string(hk), err)
}
c.config.HostKeyCallback = ssh.FixedHostKey(pk)
return nil
}
// SetEnv sets zero or more environment variables for a Session.
// If envs is nil or a zero length slice, no variables are set.
func (c *Cmd) SetEnv(envs ...string) error {
for _, v := range envs {
env := strings.SplitN(v, "=", 2)
if len(env) == 1 {
env = append(env, "")
}
if err := c.session.Setenv(env[0], env[1]); err != nil {
return fmt.Errorf("Warning: c.session.Setenv(%q, %q): %v", v, os.Getenv(v), err)
}
}
return nil
}
// SSHStdin implements an ssh-like reader, honoring ~ commands.
func (c *Cmd) SSHStdin(w io.WriteCloser, r io.Reader) {
var newLine, tilde bool
var t = []byte{'~'}
var b [1]byte
for {
if _, err := r.Read(b[:]); err != nil {
break
}
switch b[0] {
default:
newLine = false
if tilde {
if _, err := w.Write(t[:]); err != nil {
return
}
tilde = false
}
if _, err := w.Write(b[:]); err != nil {
return
}
case '\n', '\r':
newLine = true
if _, err := w.Write(b[:]); err != nil {
return
}
case '~':
if newLine {
newLine = false
tilde = true
break
}
if _, err := w.Write(t[:]); err != nil {
return
}
case '.':
if tilde {
c.session.Close()
return
}
if _, err := w.Write(b[:]); err != nil {
return
}
}
}
}
// GetKeyFile picks a keyfile if none has been set.
// It will use ssh config, else use a default.
func GetKeyFile(host, kf string) string {
verbose("getKeyFile for %q", kf)
if len(kf) == 0 {
kf = config.Get(host, "IdentityFile")
verbose("key file from config is %q", kf)
if len(kf) == 0 {
kf = DefaultKeyFile
}
}
// The kf will always be non-zero at this point.
if strings.HasPrefix(kf, "~") {
kf = filepath.Join(os.Getenv("HOME"), kf[1:])
}
verbose("getKeyFile returns %q", kf)
// this is a tad annoying, but the config package doesn't handle ~.
return kf
}
// GetHostName reads the host name from the ssh config file,
// if needed. If it is not found, the host name is returned.
func GetHostName(host string) string {
h := config.Get(host, "HostName")
if len(h) != 0 {
host = h
}
return host
}
// GetPort gets a port. It verifies that the port fits in 16-bit space.
// The rules here are messy, since config.Get will return "22" if
// there is no entry in .ssh/config. 22 is not allowed. So in the case
// of "22", convert to defaultPort.
func GetPort(host, port string) (string, error) {
p := port
verbose("getPort(%q, %q)", host, port)
if len(port) == 0 {
if cp := config.Get(host, "Port"); len(cp) != 0 {
verbose("config.Get(%q,%q): %q", host, port, cp)
p = cp
}
}
if len(p) == 0 || p == "22" {
p = DefaultPort
verbose("getPort: return default %q", p)
}
verbose("returns %q", p)
return p, nil
}
// vsockIDPort gets a client id and a port from host and port
// The id and port are uint32.
func vsockIDPort(host, port string) (uint32, uint32, error) {
h, err := strconv.ParseUint(host, 0, 32)
if err != nil {
return 0, 0, err
}
p, err := strconv.ParseUint(port, 0, 32)
if err != nil {
return 0, 0, err
}
return uint32(h), uint32(p), nil
}
// Signal implements ssh.Signal
func (c *Cmd) Signal(s ssh.Signal) error {
return c.session.Signal(s)
}
// Outputs returns a slice of bytes.Buffer for stdout and stderr,
// and an error if either had trouble being read.
func (c *Cmd) Outputs() ([]bytes.Buffer, error) {
var r [2]bytes.Buffer
var errs []error
if _, err := io.Copy(&r[0], c.SessionOut); err != nil && err != io.EOF {
errs = append(errs, fmt.Errorf("Stdout: %w", err))
}
if _, err := io.Copy(&r[1], c.SessionErr); err != nil && err != io.EOF {
errs = append(errs, fmt.Errorf("Stderr: %w", err))
}
if errs != nil {
return r[:], fmt.Errorf(fmt.Sprintf("%v", errs))
}
return r[:], nil
}
// parseBinds parses a CPU_NAMESPACE-style string to a
// an fstab format string.
func parseBinds(s string) (string, error) {
var fstab string
if len(s) == 0 {
return fstab, nil
}
// This is bit tricky. For now we have to assume
// cpud is on Linux, since only Linux has the features we
// need for private name spaces. Therefore, to run this test on
// (e.g.) Darwin, we just use /tmp, not os.TempDir()
tmpMnt := "/tmp"
binds := strings.Split(s, ":")
for i, bind := range binds {
if len(bind) == 0 {
return "", fmt.Errorf("bind: element %d is zero length:%w", i, strconv.ErrSyntax)
}
// If the value is local=remote, len(c) will be 2.
// The value might be some weird degenerate form such as
// =name or name=. Both are considered to be an error.
// The convention is to split on the first =. It is not up
// to this code to determine that more than one = is an error
// There is no rule that filenames can not contain an '='!
c := strings.SplitN(bind, "=", 2)
var local, remote string
switch len(c) {
case 0:
return fstab, fmt.Errorf("bind: element %d(%q): empty elements are not supported:%w", i, bind, strconv.ErrSyntax)
case 1:
local, remote = c[0], c[0]
case 2:
local, remote = c[0], c[1]
default:
return fstab, fmt.Errorf("bind: element %d(%q): too many elements around = sign:%w", i, bind, strconv.ErrSyntax)
}
if len(local) == 0 {
return fstab, fmt.Errorf("bind: element %d(%q): local is 0 length:%w", i, bind, strconv.ErrSyntax)
}
if len(remote) == 0 {
return fstab, fmt.Errorf("bind: element %d(%q): remote is 0 length:%w", i, bind, strconv.ErrSyntax)
}
// The convention is that the remote side is relative to filepath.Join(tmpMnt, "cpu")
// and the left side is taken exactly as written. Further, recall that in bind mounts, the
// remote side is the "device", and the local side is the "target."
fstab = fstab + fmt.Sprintf("%s %s none defaults,bind 0 0\n", filepath.Join(tmpMnt, "cpu", remote), local)
}
return fstab, nil
}
// joinFSTab joins an arbitrary number of fstab-style strings.
// The intent is to deal with strings that may not be well formatted
// as provided by users, e.g. too many newlines, not enough, and so on.
func joinFSTab(tables ...string) string {
if len(tables) == 0 {
return ""
}
for i := range tables {
if len(tables[i]) == 0 {
continue
}
tables[i] = strings.TrimRight(tables[i], "\n")
}
return strings.Join(tables, "\n") + "\n"
}