-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathknown_hosts.go
79 lines (70 loc) · 1.83 KB
/
known_hosts.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 ssh3
import (
"bufio"
"crypto/x509"
"encoding/base64"
"fmt"
"os"
"strings"
"syscall"
)
type KnownHosts map[string][]*x509.Certificate
func (kh KnownHosts) Knows(hostname string) bool {
if len(kh) == 0 {
return false
}
_, ok := kh[hostname]
return ok
}
type InvalidKnownHost struct {
line string
}
func (e InvalidKnownHost) Error() string {
return fmt.Sprintf("invalid known host line: %s", e.line)
}
func ParseKnownHosts(filename string) (knownHosts KnownHosts, invalidLines []int, err error) {
knownHosts = make(map[string][]*x509.Certificate)
file, err := os.Open(filename)
if os.IsNotExist(err) {
// the known hosts file simply does not exist yet, so there is no known host
return knownHosts, nil, nil
}
if err != nil {
return nil, nil, err
}
scanner := bufio.NewScanner(file)
for i := 0; scanner.Scan(); i {
knownHost := strings.TrimSpace(scanner.Text())
fields := strings.Fields(knownHost)
if len(fields) != 3 || fields[1] != "x509-certificate" {
invalidLines = append(invalidLines, i)
continue
}
certBytes, err := base64.StdEncoding.DecodeString(fields[2])
if err != nil {
invalidLines = append(invalidLines, i)
continue
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
invalidLines = append(invalidLines, i)
continue
}
certs := knownHosts[fields[0]]
certs = append(certs, cert)
knownHosts[fields[0]] = certs
}
return knownHosts, invalidLines, nil
}
func AppendKnownHost(filename string, host string, cert *x509.Certificate) error {
encodedCert := base64.StdEncoding.EncodeToString(cert.Raw)
knownHosts, err := os.OpenFile(filename, os.O_CREATE|syscall.O_APPEND|syscall.O_WRONLY, 0600)
if err != nil {
return err
}
_, err = knownHosts.WriteString(fmt.Sprintf("%s x509-certificate %s\n", host, encodedCert))
if err != nil {
return err
}
return nil
}