-
Notifications
You must be signed in to change notification settings - Fork 0
/
knownhosts.go
96 lines (83 loc) · 2.28 KB
/
knownhosts.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
92
93
94
95
96
package gosh
import (
"errors"
"net"
"os"
"path/filepath"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
func AutoFixedHostKeyCallback(host string, remote net.Addr, key ssh.PublicKey) error {
found, err := VerifyKnownHost("", host, remote, key)
if err != nil {
return err
}
if found {
return nil
}
// Add the new host to known hosts file.
return AppendKnownHost("", host, remote, key)
}
// DefaultHostKeyCallback returns host key callback from default known_hosts file.
func DefaultHostKeyCallback() (ssh.HostKeyCallback, error) {
fpath, err := DefaultKnownHostsPath()
if err != nil {
return nil, err
}
return knownhosts.New(fpath)
}
// DefaultKnownHostsPath returns the path of default knows_hosts file.
func DefaultKnownHostsPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".ssh/known_hosts"), err
}
// VerifyKnownHost reports whether the given host in known hosts file and valid.
func VerifyKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) (bool, error) {
var (
keyErr *knownhosts.KeyError
callback ssh.HostKeyCallback
err error
)
if fpath != "" {
callback, err = knownhosts.New(fpath)
} else {
callback, err = DefaultHostKeyCallback()
}
if err != nil {
return false, err
}
// check if host already exists
if err = callback(host, remote, key); err == nil {
return true, nil
} else if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
// The known_hosts file contains the given host, but with different key.
return true, keyErr
}
return false, nil
}
// AppendKnownHost appends a host to known hosts file.
func AppendKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) error {
if fpath == "" {
f, err := DefaultKnownHostsPath()
if err != nil {
return err
}
fpath = f
}
f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
remoteNormalized := knownhosts.Normalize(remote.String())
hostNormalized := knownhosts.Normalize(host)
addresses := []string{remoteNormalized}
if hostNormalized != remoteNormalized {
addresses = append(addresses, hostNormalized)
}
_, err = f.WriteString(knownhosts.Line(addresses, key) + "\n")
return err
}