-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhostkey.go
301 lines (260 loc) · 8.83 KB
/
hostkey.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"golang.org/x/crypto/ssh"
"io"
"net"
"os"
"strings"
)
func prepareHostKeyHandler(knownHostsFilePath string) func(string, net.Addr, ssh.PublicKey) error {
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
rawHostname, friendlyHostname, err := extractHostname(hostname)
if err != nil {
return fmt.Errorf("failed to extract hostname %s: %w", hostname, err)
}
var rawAddr string
if remote.(*net.TCPAddr).Port == DefaultSSHPort {
rawAddr = remote.(*net.TCPAddr).IP.String()
} else {
rawAddr = fmt.Sprintf("[%s]:%d", remote.(*net.TCPAddr).IP.String(), remote.(*net.TCPAddr).Port)
}
// Query known_hosts file
knownHostsFile, err := os.OpenFile(knownHostsFilePath, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return fmt.Errorf("failed to open known_hosts file: %w", err)
}
defer knownHostsFile.Close()
isPerfectMatch, hostsWithSameKey, oldKey, relevantLineStart, relevantLineEnd := findServer(knownHostsFile, rawHostname, rawAddr, key)
if isPerfectMatch {
return nil
}
// No matching result found, prepare event
evPayload := EventPayloadHostKey{
Host: friendlyHostname,
Fingerprint: ssh.FingerprintSHA256(key),
}
if oldKey == nil {
// New host
evPayload.HostWithSameKey = hostsWithSameKey // Could be nil, but that's expected
} else {
// Server change its key
evPayload.OldFingerprint = p(ssh.FingerprintSHA256(oldKey))
}
// Send event
keyEvBytes, err := buildEvent(EventNameHostKey, &evPayload)
if err != nil {
return fmt.Errorf("failed to build key event: %w", err)
}
if _, err = os.Stdout.Write(keyEvBytes); err != nil {
return fmt.Errorf("failed to write key event: %w", err)
}
// Waiting for reply
resBuf := make([]byte, DefaultBufferSize)
n, err := os.Stdin.Read(resBuf)
if err != nil {
return fmt.Errorf("failed to read from stdin: %w", err)
}
if n == 0 {
return fmt.Errorf("nothing read from stdin")
}
if !arrayContains([]byte("yY1\r\n"), resBuf[0]) {
// User rejected
return fmt.Errorf("user rejected")
}
// else: user approved, update file before proceed
if err = updateKnownHosts(knownHostsFile, rawHostname, key, oldKey, hostsWithSameKey, relevantLineStart, relevantLineEnd); err != nil {
// Update failed, but continue processing
LogError(fmt.Errorf("failed to update known_hosts file: %w", err))
}
return nil
}
}
func extractHostname(hostname string) (rawHostname, friendlyHostname string, err error) {
// hostname will always include port
host, port, err := net.SplitHostPort(hostname)
if err != nil {
return "", "", fmt.Errorf("failed to split host: %v", err)
}
if port == fmt.Sprintf("%d", DefaultSSHPort) {
rawHostname = host
friendlyHostname = host // discard port
} else {
rawHostname = fmt.Sprintf("[%s]:%s", host, port) // Always include square bracket when using non-standard port
friendlyHostname = hostname
}
return
}
func findServer(knownHostsFile io.Reader, hostname string, rawAddr string, key ssh.PublicKey) (bool, []string, ssh.PublicKey, int64, int64) {
var (
relevantLineStart int64 = 0
relevantLineEnd int64 = 0
)
knownHostsScanner := bufio.NewScanner(knownHostsFile)
for ; knownHostsScanner.Scan(); relevantLineStart = relevantLineEnd {
line := knownHostsScanner.Text()
if len(strings.TrimSpace(line)) == 0 {
// Empty line
continue
}
relevantLineEnd += int64(len(line) + 1) // + line separator
// Each line: host1:port1,host2,host3... algo pubkey
// for example:
// github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl
splits := strings.SplitN(line, " ", 2)
if len(splits) != 2 {
// Malformed line, skip
continue
}
// Parse
hostsInLine := strings.Split(splits[0], ",")
keyInLine, _, _, _, err := ssh.ParseAuthorizedKey([]byte(splits[1]))
if err != nil {
// Parse failed, skip
continue
}
// Compare
isHostMatch := (arrayContains(hostsInLine, hostname) || arrayContains(hostsInLine, rawAddr)) && (key.Type() == keyInLine.Type())
isKeyMatch := bytes.Equal(key.Marshal(), keyInLine.Marshal())
if !isHostMatch && !isKeyMatch {
// Not this one, proceed next line
continue
} else if isHostMatch && isKeyMatch {
// Perfect Match
return true, nil, nil, 0, 0
} else if isHostMatch { // !isKeyMatch
// Server change its key
return false, nil, keyInLine, relevantLineStart, relevantLineEnd
} else { // isKeyMatch && !isHostMatch
// Access the same server using different host
return false, hostsInLine, nil, relevantLineStart, relevantLineEnd
}
}
// Nothing matches, this is a new server
return false, nil, nil, relevantLineStart, relevantLineEnd // Use relevant line end to mark file end position
}
func updateKnownHosts(knownHostsFile *os.File, hostname string, key ssh.PublicKey, oldKey ssh.PublicKey, hostsWithSameKey []string, relevantLineStart, relevantLineEnd int64) error {
bytesToWrite := []byte(fmt.Sprintf(
"%s %s",
strings.Join(append(hostsWithSameKey, hostname), ","),
ssh.MarshalAuthorizedKey(key),
)) // ssh.MarshalAuthorizedKey will include \n, so no need to add manually
if oldKey == nil && hostsWithSameKey == nil {
// Brand-new host, just append to end of file
if stat, err := knownHostsFile.Stat(); err != nil {
return fmt.Errorf("failed to stat known_hosts file: %w", err)
} else if stat.Size() > 0 {
// Check if last byte is newline - we don't want to corrupt this file
if _, err := knownHostsFile.Seek(-1, io.SeekEnd); err != nil {
return fmt.Errorf("failed to seek known_hosts file: %w", err)
}
finalByte := make([]byte, 1)
if _, err := knownHostsFile.Read(finalByte); err != nil {
return fmt.Errorf("failed to read final byte of known_hosts file: %w", err)
}
if finalByte[0] != '\n' {
// No line separator at the end of file, should add line separator before our content or file would be corrupted
bytesToWrite = append([]byte{'\n'}, bytesToWrite...)
}
}
if _, err := knownHostsFile.Write(bytesToWrite); err != nil {
return fmt.Errorf("failed to append to known_hosts file: %w", err)
}
} else {
// Partial modification
// Step 1: Spare space
if _, err := knownHostsFile.Seek(relevantLineStart, io.SeekStart); err != nil {
return fmt.Errorf("failed to seek known_hosts file: %w", err)
}
// Spare space
if err := spareSpace(knownHostsFile, relevantLineStart, relevantLineEnd, int64(len(bytesToWrite))); err != nil {
return fmt.Errorf("failed to space space from known_hosts file: %w", err)
}
// Step 2: write
if _, err := knownHostsFile.WriteAt(bytesToWrite, relevantLineStart); err != nil {
return fmt.Errorf("failed to append to known_hosts file: %w", err)
}
}
return nil
}
func spareSpace(targetFile *os.File, keepBefore int64, keepAfter int64, requiredSpace int64) error {
lengthDiff := requiredSpace - (keepAfter - keepBefore)
if lengthDiff == 0 {
// No need to process
return nil
}
// Get file current size
var fileSize int64
if stat, err := targetFile.Stat(); err != nil {
return fmt.Errorf("failed to stat known_hosts file: %w", err)
} else {
fileSize = stat.Size()
if fileSize == 0 {
// Nothing to read
return nil
}
}
// else: we have a job now
buf := make([]byte, DefaultBufferSize)
if lengthDiff > 0 {
// Longer, move from back to front
lastStart := fileSize
start := fileSize - int64(len(buf))
reachTop := false
for !reachTop {
if start < keepAfter {
start = keepAfter
reachTop = true
}
// Read
readCount, err := targetFile.ReadAt(buf, start)
if err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("failed to read from file: %w", err)
}
if reachTop {
readCount = int(lastStart - start) // fix read count
if readCount <= 0 {
break
}
}
// Write
writeCount, err := targetFile.WriteAt(buf[:readCount], start+lengthDiff)
if err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}
if writeCount != readCount {
return fmt.Errorf("read write mismatch, data corrupted")
}
// Update pointer
lastStart = start
start -= int64(readCount)
}
} else {
// Shorter, move from front to back
for start := keepAfter; start < fileSize; {
// Read
readCount, err := targetFile.ReadAt(buf, start)
if err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("failed to read from file: %w", err)
}
// Write
writeCount, err := targetFile.WriteAt(buf[:readCount], start+lengthDiff)
if err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}
if writeCount != readCount {
return fmt.Errorf("read write mismatch, data corrupted")
}
// Update start
start += int64(readCount)
}
// Truncate file after move to remove unexpected bytes
if err := targetFile.Truncate(fileSize + lengthDiff); err != nil {
return fmt.Errorf("failed to truncate file: %w", err)
}
}
return nil
}