-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathntske.go
More file actions
353 lines (296 loc) · 8.93 KB
/
Copy pathntske.go
File metadata and controls
353 lines (296 loc) · 8.93 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright © Brett Vickers.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package nts
import (
"bufio"
"bytes"
"crypto/cipher"
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"strconv"
"github.com/secure-io/siv-go"
)
const (
ntskeProtocol = "ntske/1"
defaultNtsPort = 4460
defaultNtpPort = 123
ntpProtocolID = uint16(0)
algoAEAD_AES_SIV_CMAC_256 = uint16(15)
algoAEAD_AES_128_GCM_SIV = uint16(30)
)
var (
errInvalidRecordSize = errors.New("key exchange: invalid record size")
errInvalidCriticalBit = errors.New("key exchange: incorrect critical bit")
)
type recordType uint16
type newAEAD func(key []byte) (cipher.AEAD, error)
const (
recEOM recordType = 0
recProtocols recordType = 1
recError recordType = 2
recWarning recordType = 3
recAlgorithms recordType = 4
recCookie recordType = 5
recServer recordType = 6
recPort recordType = 7
recCompliant128GCM recordType = 1024
recCritical recordType = 0x8000
)
func (s *Session) performKeyExchange() error {
dialer := s.options.Dialer
// Use the default TLS dialer if none was provided.
if dialer == nil {
dialer = func(network, addr string, tlsConfig *tls.Config) (*tls.Conn, error) {
d := &net.Dialer{Timeout: s.options.Timeout}
return tls.DialWithDialer(d, network, addr, tlsConfig)
}
}
// Open a connection to the NTS-KE server.
conn, err := dialer("tcp", s.ntskeAddr, s.options.TLSConfig)
if err != nil {
return fmt.Errorf("key exchange: connection error: %w", err)
}
defer conn.Close()
// Verify that the negotiated protocol is NTS-KE.
state := conn.ConnectionState()
if state.NegotiatedProtocol != ntskeProtocol {
return errors.New("key exchange: NTS-KE protocol not negotiated")
}
// Build the NTS-KE request by writing records into a buffer.
var xmitBuf bytes.Buffer
{
writeRecProtocols(&xmitBuf, ntpProtocolID)
writeRecAlgorithms(&xmitBuf, algoAEAD_AES_128_GCM_SIV, algoAEAD_AES_SIV_CMAC_256)
writeRecCompliantAes128GcmSiv(&xmitBuf)
if s.options.RequestedNTPServerAddress != "" {
writeRecServer(&xmitBuf, s.options.RequestedNTPServerAddress)
}
if s.options.RequestedNTPServerPort != 0 {
writeRecPort(&xmitBuf, uint16(s.options.RequestedNTPServerPort))
}
writeRecEOM(&xmitBuf)
}
// Send the NTS-KE request to the server.
_, err = conn.Write(xmitBuf.Bytes())
if err != nil {
return fmt.Errorf("key exchange: connection error: %w", err)
}
// Read the NTS-KE response.
recvReader := bufio.NewReader(conn)
recvBuf := make([]byte, 1024)
useCompliant128GCM := s.options.AssumeCompliant128GCM
s.ntpAddr = ""
var port int
var algorithm uint16
// Parse the NTS-KE response records.
loop:
for {
// Retrieve the record header (type + length).
rhdr := recvBuf[:4]
_, err := io.ReadFull(recvReader, rhdr)
if err != nil {
return errors.New("key exchange: failed to read record header")
}
// Parse the record type, extracting the critical bit.
rtype := recordType(binary.BigEndian.Uint16(rhdr[0:2]))
critical := (rtype & recCritical) != 0
rtype &= ^recCritical
// Parse the record length.
rlen := int(binary.BigEndian.Uint16(rhdr[2:4]))
if rlen > len(recvBuf) {
return errors.New("key exchange: record length too large")
}
// Read the record body.
rbody := recvBuf[:rlen]
_, err = io.ReadFull(recvReader, rbody)
if err != nil {
return errors.New("key exchange: failed to read record")
}
// Process the record body based on its type.
switch rtype {
case recEOM:
if !critical {
return errInvalidCriticalBit
}
if len(rbody) != 0 {
return errInvalidRecordSize
}
break loop
case recProtocols:
if !critical {
return errInvalidCriticalBit
}
if len(rbody) == 0 {
return errors.New("key exchange: NTP protocol not supported")
}
if len(rbody) != 2 {
return errInvalidRecordSize
}
p := binary.BigEndian.Uint16(rbody)
if p != ntpProtocolID {
return errors.New("key exchange: NTP protocol not supported")
}
case recError:
if !critical {
return errInvalidCriticalBit
}
if len(rbody) != 2 {
return errInvalidRecordSize
}
code := binary.BigEndian.Uint16(rbody)
return processErrorCode(code)
case recWarning:
if !critical {
return errInvalidCriticalBit
}
if len(rbody) != 2 {
return errInvalidRecordSize
}
// Currently, no warning codes are defined in RFC 8915.
code := binary.BigEndian.Uint16(rbody)
return fmt.Errorf("key exchange: unrecognized warning code (0x%02x)", code)
case recAlgorithms:
if len(rbody) == 0 {
return errors.New("key exchange: server does not support requested algorithms")
}
if len(rbody) != 2 {
return errInvalidRecordSize
}
algorithm = binary.BigEndian.Uint16(rbody)
case recCookie:
if critical {
return errInvalidCriticalBit
}
if len(rbody) == 0 {
return errInvalidRecordSize
}
cookie := make([]byte, len(rbody))
copy(cookie, rbody)
s.cookies.Add(cookie)
case recServer:
if len(rbody) == 0 {
return errInvalidRecordSize
}
s.ntpAddr = string(rbody)
case recPort:
if len(rbody) != 2 {
return errInvalidRecordSize
}
port = int(binary.BigEndian.Uint16(rbody))
case recCompliant128GCM:
if critical {
return errInvalidCriticalBit
}
if len(rbody) != 0 {
return errInvalidRecordSize
}
useCompliant128GCM = true
default:
if critical {
return errInvalidCriticalBit
}
}
}
// Use the NTS host for NTP if no negotiated server record was reported.
if s.ntpAddr == "" {
s.ntpAddr, _, _ = net.SplitHostPort(conn.RemoteAddr().String())
}
// Use the default NTP port if no negotiated port was reported.
if port == 0 {
port = defaultNtpPort
}
// Form the host:port NTP server address string.
s.ntpAddr = net.JoinHostPort(s.ntpAddr, strconv.Itoa(port))
// If the NTP address override resolver is defined, call it.
if s.options.Resolver != nil {
s.ntpAddr = s.options.Resolver(s.ntpAddr)
}
// Extract TLS keys and use them to generate AEAD ciphers.
switch algorithm {
case algoAEAD_AES_128_GCM_SIV:
if useCompliant128GCM {
return s.extractKeys(conn, algoAEAD_AES_128_GCM_SIV, 16, siv.NewGCM)
}
return s.extractKeys(conn, algoAEAD_AES_SIV_CMAC_256, 16, siv.NewGCM)
case algoAEAD_AES_SIV_CMAC_256:
return s.extractKeys(conn, algoAEAD_AES_SIV_CMAC_256, 32, siv.NewCMAC)
default:
return errors.New("key exchange: no supported algorithm negotiated")
}
}
func writeRecProtocols(w io.Writer, id uint16) {
binary.Write(w, binary.BigEndian, recProtocols|recCritical)
binary.Write(w, binary.BigEndian, uint16(2))
binary.Write(w, binary.BigEndian, id)
}
func writeRecAlgorithms(w io.Writer, algo1, algo2 uint16) {
binary.Write(w, binary.BigEndian, recAlgorithms|recCritical)
binary.Write(w, binary.BigEndian, uint16(4))
binary.Write(w, binary.BigEndian, algo1)
binary.Write(w, binary.BigEndian, algo2)
}
func writeRecCompliantAes128GcmSiv(w io.Writer) {
binary.Write(w, binary.BigEndian, recCompliant128GCM)
binary.Write(w, binary.BigEndian, uint16(0))
}
func writeRecServer(w io.Writer, addr string) {
binary.Write(w, binary.BigEndian, recServer)
binary.Write(w, binary.BigEndian, uint16(len(addr)))
w.Write([]byte(addr))
}
func writeRecPort(w io.Writer, port uint16) {
binary.Write(w, binary.BigEndian, recPort)
binary.Write(w, binary.BigEndian, uint16(2))
binary.Write(w, binary.BigEndian, port)
}
func writeRecEOM(w io.Writer) {
binary.Write(w, binary.BigEndian, recEOM|recCritical)
binary.Write(w, binary.BigEndian, uint16(0))
}
func processErrorCode(code uint16) error {
switch code {
case 0:
return errors.New("key exchange: unrecognized critical record")
case 1:
return errors.New("key exchange: bad request")
case 2:
return errors.New("key exchange: internal server error")
default:
return fmt.Errorf("key exchange: unrecognized server error code (0x%02x)", code)
}
}
func (s *Session) extractKeys(conn *tls.Conn, algorithmID uint16, keyLength int, aead newAEAD) error {
const (
keyLabel = "EXPORTER-network-time-security"
c2sIndicator = 0
s2cIndicator = 1
)
context := make([]byte, 5)
binary.BigEndian.PutUint16(context[0:2], ntpProtocolID)
binary.BigEndian.PutUint16(context[2:4], algorithmID)
state := conn.ConnectionState()
context[4] = c2sIndicator
c2s, err := state.ExportKeyingMaterial(keyLabel, context, keyLength)
if err != nil {
return fmt.Errorf("key exchange: failed to export keying material: %w", err)
}
s.cipherC2S, err = aead(c2s)
if err != nil {
return fmt.Errorf("key exchange: failed to create c2s cipher: %w", err)
}
context[4] = s2cIndicator
s2c, err := state.ExportKeyingMaterial(keyLabel, context, keyLength)
if err != nil {
return fmt.Errorf("key exchange: failed to export keying material: %w", err)
}
s.cipherS2C, err = aead(s2c)
if err != nil {
return fmt.Errorf("key exchange: failed to create s2c cipher: %w", err)
}
return nil
}