-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
80 lines (69 loc) · 1.45 KB
/
key.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
package shell
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/gliderlabs/ssh"
gossh "golang.org/x/crypto/ssh"
"log"
"os"
)
type HostKeyResolver struct {
hostKeyFile string
}
func NewHostKeyResolver(config *Config) *HostKeyResolver {
return &HostKeyResolver{
hostKeyFile: config.HostKeyFile,
}
}
func (r *HostKeyResolver) Resolve() string {
if r.hostKeyFile == "" {
return ""
}
_, err := os.Stat(r.hostKeyFile)
if err != nil {
if os.IsNotExist(err) {
err := r.createHostKeyFile()
if err != nil {
log.Fatal(err)
}
} else {
log.Fatal(err)
}
}
return r.hostKeyFile
}
func (r *HostKeyResolver) createHostKeyFile() error {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
publicKey, err := gossh.NewPublicKey(key.Public())
if err != nil {
return err
}
fingerprint := gossh.FingerprintSHA256(publicKey)
log.Printf("I: Generating host key with fingerprint %s to %s\n", fingerprint, r.hostKeyFile)
file, err := os.Create(r.hostKeyFile)
if err != nil {
return err
}
//noinspection GoUnhandledErrorResult
defer file.Close()
var keyBlock = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
err = pem.Encode(file, keyBlock)
return err
}
func (r *HostKeyResolver) ResolveOption() ssh.Option {
if r.hostKeyFile == "" {
return func(s *ssh.Server) error {
return nil
}
} else {
return ssh.HostKeyFile(r.Resolve())
}
}