|
1 | 1 | package ssh |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "crypto/rand" |
5 | | - "crypto/rsa" |
6 | | - "crypto/x509" |
7 | | - "encoding/pem" |
8 | 4 | "fmt" |
9 | 5 | "os" |
| 6 | + "path/filepath" |
10 | 7 |
|
11 | 8 | "golang.org/x/crypto/ssh" |
12 | 9 | ) |
13 | 10 |
|
14 | | -const HostKeyPath = "/etc/ssh-ify/host_key" |
15 | | - |
16 | 11 | func LoadHostKey() (ssh.Signer, error) { |
17 | | - privateBytes, err := os.ReadFile(HostKeyPath) |
| 12 | + home, err := os.UserHomeDir() |
18 | 13 | if err != nil { |
19 | | - if err := os.MkdirAll("/etc/ssh-ify", 0700); err != nil { |
20 | | - return nil, fmt.Errorf("failed to create config directory: %v", err) |
21 | | - } |
22 | | - if err := GenerateHostKey(HostKeyPath); err != nil { |
23 | | - return nil, fmt.Errorf("failed to generate host key: %v", err) |
24 | | - } |
25 | | - privateBytes, err = os.ReadFile(HostKeyPath) |
26 | | - if err != nil { |
27 | | - return nil, fmt.Errorf("failed to read generated host key: %v", err) |
28 | | - } |
| 14 | + return nil, fmt.Errorf("failed to get home directory: %w", err) |
29 | 15 | } |
30 | 16 |
|
31 | | - return ssh.ParsePrivateKey(privateBytes) |
32 | | -} |
33 | | - |
34 | | -func GenerateHostKey(keyPath string) error { |
35 | | - privateKey, err := rsa.GenerateKey(rand.Reader, 4096) |
| 17 | + keyPath := filepath.Join(home, ".ssh", "id_rsa") |
| 18 | + privateBytes, err := os.ReadFile(keyPath) |
36 | 19 | if err != nil { |
37 | | - return err |
| 20 | + if os.IsNotExist(err) { |
| 21 | + return nil, fmt.Errorf("host key not found, please generate one: ssh-keygen -t rsa -b 4096 -f %s", keyPath) |
| 22 | + } |
| 23 | + return nil, fmt.Errorf("failed to read host key: %w", err) |
38 | 24 | } |
39 | 25 |
|
40 | | - privDER := x509.MarshalPKCS1PrivateKey(privateKey) |
41 | | - privBlock := &pem.Block{ |
42 | | - Type: "RSA PRIVATE KEY", |
43 | | - Bytes: privDER, |
| 26 | + signer, err := ssh.ParsePrivateKey(privateBytes) |
| 27 | + if err != nil { |
| 28 | + return nil, fmt.Errorf("failed to parse host key: %w", err) |
44 | 29 | } |
45 | | - privateBytes := pem.EncodeToMemory(privBlock) |
46 | 30 |
|
47 | | - return os.WriteFile(keyPath, privateBytes, 0600) |
| 31 | + return signer, nil |
48 | 32 | } |
0 commit comments