-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathssh_keys.go
91 lines (73 loc) · 2 KB
/
ssh_keys.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
package main
/*
* SSH key generation / import
* ---------------------------
*/
import (
"errors"
"fmt"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/ssh"
"io/ioutil"
"os"
"path"
)
// Generate an SSH key pair, and save it into the machine store folder.
func (driver *Driver) generateSSHKey() error {
if driver.SSHKeyPath != "" {
return errors.New("SSH key path already configured")
}
driver.SSHKeyPath = driver.ResolveStorePath("id_rsa")
err := ssh.GenerateSSHKey(driver.SSHKeyPath)
if err != nil {
log.Errorf("Failed to generate SSH key pair: %s", err.Error())
return err
}
return nil
}
// Import the configured SSH key files into the machine store folder.
func (driver *Driver) importSSHKey() error {
if driver.SSHKey == "" {
return errors.New("SSH key path not configured")
}
driver.SSHKeyPath = driver.ResolveStorePath(
path.Base(driver.SSHKey),
)
err := copySSHKey(driver.SSHKey, driver.SSHKeyPath)
if err != nil {
log.Infof("Couldn't copy SSH private key: %s", err.Error())
return err
}
err = copySSHKey(driver.SSHKey+".pub", driver.SSHKeyPath+".pub")
if err != nil {
log.Infof("Couldn't copy SSH public key: %s", err.Error())
return err
}
return nil
}
// Get the public portion of the configured SSH key.
func (driver *Driver) getSSHPublicKey() (string, error) {
publicKeyFile, err := os.Open(driver.SSHKeyPath + ".pub")
if err != nil {
return "", err
}
defer publicKeyFile.Close()
publicKeyData, err := ioutil.ReadAll(publicKeyFile)
if err != nil {
return "", err
}
return string(publicKeyData), nil
}
// Copy an SSH key file.
func copySSHKey(sourceFile string, destinationFile string) error {
err := mcnutils.CopyFile(sourceFile, destinationFile)
if err != nil {
return fmt.Errorf("unable to copy ssh key: %s", err.Error())
}
err = os.Chmod(destinationFile, 0600)
if err != nil {
return fmt.Errorf("unable to set permissions on the ssh key: %s", err.Error())
}
return nil
}