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
package sshd
import (
"io/ioutil"
"os"
"path"
"golang.org/x/crypto/ssh"
"github.com/jumpserver/koko/pkg/common"
)
type HostKey struct {
Value string
Path string
}
func (hk *HostKey) loadHostKeyFromFile(keyPath string) (signer ssh.Signer, err error) {
_, err = os.Stat(keyPath)
if err != nil {
return
}
buf, err := ioutil.ReadFile(keyPath)
if err != nil {
return
}
return hk.loadHostKeyFromString(string(buf))
}
func (hk *HostKey) loadHostKeyFromString(value string) (signer ssh.Signer, err error) {
signer, err = ssh.ParsePrivateKey([]byte(value))
return
}
func (hk *HostKey) Gen() (signer ssh.Signer, err error) {
key, err := common.GeneratePrivateKey(2048)
if err != nil {
return
}
keyBytes := common.EncodePrivateKeyToPEM(key)
keyDir := path.Dir(hk.Path)
if !common.FileExists(keyDir) {
err := os.MkdirAll(keyDir, os.ModePerm)
if err != nil {
return signer, err
}
}
err = common.WriteKeyToFile(keyBytes, hk.Path)
if err != nil {
return
}
return ssh.NewSignerFromKey(key)
}
func (hk *HostKey) Load() (signer ssh.Signer, err error) {
if hk.Value != "" {
signer, err = hk.loadHostKeyFromString(hk.Value)
if err == nil {
return
}
}
if hk.Path != "" {
signer, err = hk.loadHostKeyFromFile(hk.Path)
if err == nil {
return
}
}
signer, err = hk.Gen()
return
}