blob: 35433dd564615d3c19e594f4c967974bf3705692 [file] [log] [blame]
Sean McCullough4854c652025-04-24 18:37:02 -07001package dockerimg
2
3import (
4 "bufio"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/x509"
Sean McCullough4854c652025-04-24 18:37:02 -07008 "encoding/pem"
9 "fmt"
10 "os"
11 "path/filepath"
12 "strings"
13
14 "github.com/kevinburke/ssh_config"
15 "golang.org/x/crypto/ssh"
Sean McCullough7d5a6302025-04-24 21:27:51 -070016 "golang.org/x/crypto/ssh/knownhosts"
Sean McCullough4854c652025-04-24 18:37:02 -070017)
18
19const keyBitSize = 2048
20
21// SSHTheater does the necessary key pair generation, known_hosts updates, ssh_config file updates etc steps
22// so that ssh can connect to a locally running sketch container to other local processes like vscode without
23// the user having to run the usual ssh obstacle course.
24//
25// SSHTheater does not modify your default .ssh/config, or known_hosts files. However, in order for you
26// to be able to use it properly you will have to make a one-time edit to your ~/.ssh/config file.
27//
28// In your ~/.ssh/config file, add the following line:
29//
30// Include $HOME/.sketch/ssh_config
31//
32// where $HOME is your home directory.
33type SSHTheater struct {
34 cntrName string
35 sshHost string
36 sshPort string
37
38 knownHostsPath string
39 userIdentityPath string
40 sshConfigPath string
41 serverIdentityPath string
42
43 serverPublicKey ssh.PublicKey
44 serverIdentity []byte
45 userIdentity []byte
46}
47
48// NewSSHTheather will set up everything so that you can use ssh on localhost to connect to
49// the sketch container. Call #Clean when you are done with the container to remove the
50// various entries it created in its known_hosts and ssh_config files. Also note that
51// this will generate key pairs for both the ssh server identity and the user identity, if
52// these files do not already exist. These key pair files are not deleted by #Cleanup,
53// so they can be re-used across invocations of sketch. This means every sketch container
54// that runs on this host will use the same ssh server identity.
55//
56// If this doesn't return an error, you should be able to run "ssh <cntrName>"
57// in a terminal on your host machine to open a shell into the container without having
58// to manually accept changes to your known_hosts file etc.
59func NewSSHTheather(cntrName, sshHost, sshPort string) (*SSHTheater, error) {
60 base := filepath.Join(os.Getenv("HOME"), ".sketch")
Sean McCullough7d5a6302025-04-24 21:27:51 -070061 if _, err := os.Stat(base); err != nil {
62 if err := os.Mkdir(base, 0o777); err != nil {
63 return nil, fmt.Errorf("couldn't create %s: %w", base, err)
64 }
65 }
66
Sean McCullough4854c652025-04-24 18:37:02 -070067 cst := &SSHTheater{
68 cntrName: cntrName,
69 sshHost: sshHost,
70 sshPort: sshPort,
71 knownHostsPath: filepath.Join(base, "known_hosts"),
72 userIdentityPath: filepath.Join(base, "container_user_identity"),
73 serverIdentityPath: filepath.Join(base, "container_server_identity"),
74 sshConfigPath: filepath.Join(base, "ssh_config"),
75 }
Sean McCullough7d5a6302025-04-24 21:27:51 -070076 if _, err := createKeyPairIfMissing(cst.serverIdentityPath); err != nil {
77 return nil, fmt.Errorf("couldn't create server identity: %w", err)
78 }
79 if _, err := createKeyPairIfMissing(cst.userIdentityPath); err != nil {
80 return nil, fmt.Errorf("couldn't create user identity: %w", err)
Sean McCullough4854c652025-04-24 18:37:02 -070081 }
82
83 serverIdentity, err := os.ReadFile(cst.serverIdentityPath)
84 if err != nil {
85 return nil, fmt.Errorf("couldn't read container's ssh server identity: %w", err)
86 }
87 cst.serverIdentity = serverIdentity
88
89 serverPubKeyBytes, err := os.ReadFile(cst.serverIdentityPath + ".pub")
90 serverPubKey, _, _, _, err := ssh.ParseAuthorizedKey(serverPubKeyBytes)
91 if err != nil {
92 return nil, fmt.Errorf("couldn't read ssh server public key: %w", err)
93 }
94 cst.serverPublicKey = serverPubKey
95
96 userIdentity, err := os.ReadFile(cst.userIdentityPath + ".pub")
97 if err != nil {
98 return nil, fmt.Errorf("couldn't read ssh user identity: %w", err)
99 }
100 cst.userIdentity = userIdentity
101
Sean McCullough7d5a6302025-04-24 21:27:51 -0700102 if err := cst.addContainerToSSHConfig(); err != nil {
103 return nil, fmt.Errorf("couldn't add container to ssh_config: %w", err)
104 }
105
106 if err := cst.addContainerToKnownHosts(); err != nil {
107 return nil, fmt.Errorf("couldn't update known hosts: %w", err)
108 }
109
Sean McCullough4854c652025-04-24 18:37:02 -0700110 return cst, nil
111}
112
113func removeFromHosts(cntrName string, cfgHosts []*ssh_config.Host) []*ssh_config.Host {
114 hosts := []*ssh_config.Host{}
115 for _, host := range cfgHosts {
116 if host.Matches(cntrName) || strings.Contains(host.String(), cntrName) {
117 continue
118 }
119 patMatch := false
120 for _, pat := range host.Patterns {
121 if strings.Contains(pat.String(), cntrName) {
122 patMatch = true
123 }
124 }
125 if patMatch {
126 continue
127 }
128
129 hosts = append(hosts, host)
130 }
131 return hosts
132}
133
134func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
135 privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
136 if err != nil {
137 return nil, err
138 }
139 return privateKey, nil
140}
141
142// generatePublicKey take a rsa.PublicKey and return bytes suitable for writing to .pub file
143// returns in the format "ssh-rsa ..."
144func generatePublicKey(privatekey *rsa.PublicKey) (ssh.PublicKey, error) {
145 publicRsaKey, err := ssh.NewPublicKey(privatekey)
146 if err != nil {
147 return nil, err
148 }
149
150 return publicRsaKey, nil
151}
152
153func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
154 pemBlock := &pem.Block{
155 Type: "RSA PRIVATE KEY",
156 Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
157 }
158 pemBytes := pem.EncodeToMemory(pemBlock)
159 return pemBytes
160}
161
162func writeKeyToFile(keyBytes []byte, filename string) error {
163 err := os.WriteFile(filename, keyBytes, 0o600)
164 return err
165}
166
167func createKeyPairIfMissing(idPath string) (ssh.PublicKey, error) {
168 if _, err := os.Stat(idPath); err == nil {
169 return nil, nil
170 }
171
172 privateKey, err := generatePrivateKey(keyBitSize)
173 if err != nil {
174 return nil, fmt.Errorf("Error generating private key: %w", err)
175 }
176
177 publicRsaKey, err := generatePublicKey(&privateKey.PublicKey)
178 if err != nil {
179 return nil, fmt.Errorf("Error generating public key: %w", err)
180 }
181
182 privateKeyPEM := encodePrivateKeyToPEM(privateKey)
183
184 err = writeKeyToFile(privateKeyPEM, idPath)
185 if err != nil {
186 return nil, fmt.Errorf("Error writing private key to file %w", err)
187 }
188 pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
189
190 err = writeKeyToFile([]byte(pubKeyBytes), idPath+".pub")
191 if err != nil {
192 return nil, fmt.Errorf("Error writing public key to file %w", err)
193 }
194 return publicRsaKey, nil
195}
196
197func (c *SSHTheater) addSketchHostMatchIfMissing(cfg *ssh_config.Config) error {
198 found := false
199 for _, host := range cfg.Hosts {
200 if strings.Contains(host.String(), "host=\"sketch-*\"") {
201 found = true
202 break
203 }
204 }
205 if !found {
206 hostPattern, err := ssh_config.NewPattern("host=\"sketch-*\"")
207 if err != nil {
208 return fmt.Errorf("couldn't add pattern to ssh_config: %w", err)
209 }
210
211 hostCfg := &ssh_config.Host{Patterns: []*ssh_config.Pattern{hostPattern}}
212 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "UserKnownHostsFile", Value: c.knownHostsPath})
213
Sean McCullough4854c652025-04-24 18:37:02 -0700214 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "IdentityFile", Value: c.userIdentityPath})
Sean McCullough4854c652025-04-24 18:37:02 -0700215 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.Empty{})
216
217 cfg.Hosts = append([]*ssh_config.Host{hostCfg}, cfg.Hosts...)
218 }
219 return nil
220}
221
222func (c *SSHTheater) addContainerToSSHConfig() error {
Sean McCullough4854c652025-04-24 18:37:02 -0700223 f, err := os.OpenFile(c.sshConfigPath, os.O_RDWR|os.O_CREATE, 0o644)
224 if err != nil {
225 return fmt.Errorf("couldn't open ssh_config: %w", err)
226 }
227 defer f.Close()
228
229 cfg, err := ssh_config.Decode(f)
230 if err != nil {
231 return fmt.Errorf("couldn't decode ssh_config: %w", err)
232 }
233 cntrPattern, err := ssh_config.NewPattern(c.cntrName)
234 if err != nil {
235 return fmt.Errorf("couldn't add pattern to ssh_config: %w", err)
236 }
237
238 // Remove any matches for this container if they already exist.
239 cfg.Hosts = removeFromHosts(c.cntrName, cfg.Hosts)
240
241 hostCfg := &ssh_config.Host{Patterns: []*ssh_config.Pattern{cntrPattern}}
242 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "HostName", Value: c.sshHost})
243 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "User", Value: "root"})
244 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "Port", Value: c.sshPort})
245 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "IdentityFile", Value: c.userIdentityPath})
246 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.KV{Key: "UserKnownHostsFile", Value: c.knownHostsPath})
247
248 hostCfg.Nodes = append(hostCfg.Nodes, &ssh_config.Empty{})
249 cfg.Hosts = append(cfg.Hosts, hostCfg)
250
251 if err := c.addSketchHostMatchIfMissing(cfg); err != nil {
252 return fmt.Errorf("couldn't add missing host match: %w", err)
253 }
254
255 cfgBytes, err := cfg.MarshalText()
256 if err != nil {
257 return fmt.Errorf("couldn't marshal ssh_config: %w", err)
258 }
259 if err := f.Truncate(0); err != nil {
260 return fmt.Errorf("couldn't truncate ssh_config: %w", err)
261 }
262 if _, err := f.Seek(0, 0); err != nil {
263 return fmt.Errorf("couldn't seek to beginning of ssh_config: %w", err)
264 }
265 if _, err := f.Write(cfgBytes); err != nil {
266 return fmt.Errorf("couldn't write ssh_config: %w", err)
267 }
268
269 return nil
270}
271
272func (c *SSHTheater) addContainerToKnownHosts() error {
273 f, err := os.OpenFile(c.knownHostsPath, os.O_RDWR|os.O_CREATE, 0o644)
274 if err != nil {
275 return fmt.Errorf("couldn't open %s: %w", c.knownHostsPath, err)
276 }
277 defer f.Close()
Sean McCullough7d5a6302025-04-24 21:27:51 -0700278 pkBytes := c.serverPublicKey.Marshal()
279 if len(pkBytes) == 0 {
280 return fmt.Errorf("empty serverPublicKey. This is a bug")
281 }
282 newHostLine := knownhosts.Line([]string{c.sshHost + ":" + c.sshPort}, c.serverPublicKey)
Sean McCullough4854c652025-04-24 18:37:02 -0700283
Sean McCullough7d5a6302025-04-24 21:27:51 -0700284 outputLines := []string{}
285 scanner := bufio.NewScanner(f)
286 for scanner.Scan() {
287 outputLines = append(outputLines, scanner.Text())
288 }
289 outputLines = append(outputLines, newHostLine)
290 if err := f.Truncate(0); err != nil {
291 return fmt.Errorf("couldn't truncate known_hosts: %w", err)
292 }
293 if _, err := f.Seek(0, 0); err != nil {
294 return fmt.Errorf("couldn't seek to beginning of known_hosts: %w", err)
295 }
296 if _, err := f.Write([]byte(strings.Join(outputLines, "\n"))); err != nil {
297 return fmt.Errorf("couldn't write updated known_hosts to to %s: %w", c.knownHostsPath, err)
Sean McCullough4854c652025-04-24 18:37:02 -0700298 }
299
300 return nil
301}
302
303func (c *SSHTheater) removeContainerFromKnownHosts() error {
304 f, err := os.OpenFile(c.knownHostsPath, os.O_RDWR|os.O_CREATE, 0o644)
305 if err != nil {
306 return fmt.Errorf("couldn't open ssh_config: %w", err)
307 }
308 defer f.Close()
309 scanner := bufio.NewScanner(f)
Sean McCullough7d5a6302025-04-24 21:27:51 -0700310 lineToRemove := knownhosts.Line([]string{c.sshHost + ":" + c.sshPort}, c.serverPublicKey)
Sean McCullough4854c652025-04-24 18:37:02 -0700311 outputLines := []string{}
312 for scanner.Scan() {
313 if scanner.Text() == lineToRemove {
314 continue
315 }
316 outputLines = append(outputLines, scanner.Text())
317 }
318 if err := f.Truncate(0); err != nil {
319 return fmt.Errorf("couldn't truncate known_hosts: %w", err)
320 }
321 if _, err := f.Seek(0, 0); err != nil {
322 return fmt.Errorf("couldn't seek to beginning of known_hosts: %w", err)
323 }
324 if _, err := f.Write([]byte(strings.Join(outputLines, "\n"))); err != nil {
325 return fmt.Errorf("couldn't write updated known_hosts to to %s: %w", c.knownHostsPath, err)
326 }
327
328 return nil
329}
330
331func (c *SSHTheater) Cleanup() error {
332 if err := c.removeContainerFromSSHConfig(); err != nil {
333 return fmt.Errorf("couldn't remove container from ssh_config: %v\n", err)
334 }
335 if err := c.removeContainerFromKnownHosts(); err != nil {
336 return fmt.Errorf("couldn't remove container from ssh_config: %v\n", err)
337 }
338
339 return nil
340}
341
342func (c *SSHTheater) removeContainerFromSSHConfig() error {
343 f, err := os.OpenFile(c.sshConfigPath, os.O_RDWR|os.O_CREATE, 0o644)
344 if err != nil {
345 return fmt.Errorf("couldn't open ssh_config: %w", err)
346 }
347 defer f.Close()
348
349 cfg, err := ssh_config.Decode(f)
350 if err != nil {
351 return fmt.Errorf("couldn't decode ssh_config: %w", err)
352 }
353 cfg.Hosts = removeFromHosts(c.cntrName, cfg.Hosts)
354
355 if err := c.addSketchHostMatchIfMissing(cfg); err != nil {
356 return fmt.Errorf("couldn't add missing host match: %w", err)
357 }
358
359 cfgBytes, err := cfg.MarshalText()
360 if err != nil {
361 return fmt.Errorf("couldn't marshal ssh_config: %w", err)
362 }
363 if err := f.Truncate(0); err != nil {
364 return fmt.Errorf("couldn't truncate ssh_config: %w", err)
365 }
366 if _, err := f.Seek(0, 0); err != nil {
367 return fmt.Errorf("couldn't seek to beginning of ssh_config: %w", err)
368 }
369 if _, err := f.Write(cfgBytes); err != nil {
370 return fmt.Errorf("couldn't write ssh_config: %w", err)
371 }
372 return nil
373}