/
keys.go
79 lines (62 loc) · 1.91 KB
/
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
package ssh
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"golang.org/x/crypto/ssh"
)
// ReadSSHAuthorizedKeys reads multiple authorized keys from given directory. Keys are stored in a map by username and
// public key.
func ReadSSHAuthorizedKeys(authorizedKeysDir string) (map[string]map[string]bool, error) {
_, err := os.Stat(authorizedKeysDir)
if os.IsNotExist(err) {
return nil, fmt.Errorf("authorized keys directory does not exist")
}
authorizedKeysMap := map[string]map[string]bool{}
files, err := filepath.Glob(path.Join(authorizedKeysDir, "*"))
for _, authorizedKeyFile := range files {
_, user := filepath.Split(authorizedKeyFile)
// TODO: check permissions of authorized keys file
authorizedKeysBytes, err := ioutil.ReadFile(authorizedKeyFile)
if err != nil {
return nil, fmt.Errorf("ssh: failed to load authorized_keys, err: %v", err)
}
for len(authorizedKeysBytes) > 0 {
pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
if err != nil {
log.Fatal(err)
}
if _, ok := authorizedKeysMap[user]; !ok {
authorizedKeysMap[user] = map[string]bool{}
}
authorizedKeysMap[user][string(pubKey.Marshal())] = true
authorizedKeysBytes = rest
}
}
if len(authorizedKeysMap) == 0 {
return nil, fmt.Errorf("ssh: no authorized keys defined")
}
return authorizedKeysMap, nil
}
// ReadSSHPrivateKey reads a private key and returns a ssh.Signer
func ReadSSHPrivateKey(path string) (ssh.Signer, error) {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, fmt.Errorf("ssh: private key file not found")
}
if err != nil {
return nil, err
}
hostKeyBytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to load private key: %s", err)
}
hostKey, err := ssh.ParsePrivateKey(hostKeyBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %s", err)
}
return hostKey, nil
}