-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.go
More file actions
390 lines (360 loc) · 12.7 KB
/
Copy pathauth.go
File metadata and controls
390 lines (360 loc) · 12.7 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package twiddle
import (
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"errors"
"fmt"
"hash"
"time"
)
// Authentication mirrors TLS 1.3 psk_dhe_ke, using the fields TLS already
// provides rather than inventing carriers:
//
// key_share[X25519] <- a real ephemeral public key (forward secrecy)
// ticket (identity) <- AEAD(k_server, client_id ‖ psk ‖ issued_at ‖ padding)
// binder <- HMAC over the truncated hello, keyed from the psk
//
// The ticket is uniform BY CONSTRUCTION because it is AEAD ciphertext, which is
// exactly what a real session ticket is. That sidesteps the problem an ECDH
// value in this position would have: only about half of all field elements are
// valid Curve25519 u-coordinates, so a raw public key here is separable from
// random bytes by one Legendre-symbol test. See docs/uniform-ephemeral.md.
//
// The ephemeral moves to key_share, where a curve point is precisely what
// belongs and carries no anomaly at all. Every captured Chrome hello offers
// group 0x001d with a 32-byte key, so there is always a slot for it.
//
// Forward secrecy therefore comes from the key_share, not the psk -- the same
// division of labour TLS 1.3 uses, and the reason psk_dhe_ke exists.
const (
// TicketOverhead is nonce + GCM tag + the fixed plaintext fields.
ticketNonceLen = 12
ticketTagLen = 16
ticketFixed = 8 + 32 + 8 // client_id ‖ psk ‖ issued_at
MinTicketLen = ticketNonceLen + ticketTagLen + ticketFixed
// DefaultTicketLen is a fallback only. Ticket length is a FIDELITY parameter,
// not a free choice: it directly sets the emitted ClientHello size, because
// the ticket travels inside pre_shared_key. Measured, with the resulting
// resumption hello from the same client:
//
// cloudflare 176 B ticket -> 1711 B hello
// google 230 B ticket -> 1761 B hello
// microsoft 256 B ticket -> 1806 B hello
//
// So an egress claiming to be microsoft.com should issue 256-byte tickets.
// harvest/cmd/resume measures the right value for any host. It must also be
// stable per identity: a real server's ticket format does not vary
// connection to connection.
DefaultTicketLen = 176
GroupX25519 uint16 = 0x001d
)
// TicketKey is a server's long-term ticket-encryption key. It never leaves the
// egress; clients hold only issued tickets.
type TicketKey [32]byte
// Credential is what a client presents: an opaque ticket plus the psk it is
// paired with. The first arrives by provisioning; each connection's reply
// carries the next, exactly as NewSessionTicket does.
type Credential struct {
Ticket []byte
// FullTicket is the same clientID and psk sealed at FullTicketLen, for the
// full-handshake carrier, which cannot use Ticket: the two paths size
// tickets for incompatible reasons. See IssueFullFor and echcarrier.go.
//
// Nil is legal and means resumption-only -- a credential provisioned before
// the carrier existed. Twiddle refuses the full path rather than emitting
// an opening no server can authenticate.
FullTicket []byte
PSK [32]byte
}
func NewTicketKey() (*TicketKey, error) {
k := new(TicketKey)
if _, err := rand.Read(k[:]); err != nil {
return nil, err
}
return k, nil
}
func (k *TicketKey) aead() (cipher.AEAD, error) {
b, err := aes.NewCipher(k[:])
if err != nil {
return nil, err
}
return cipher.NewGCM(b)
}
// Issue mints a credential. ticketLen is the total on-wire ticket size; the
// plaintext is padded to fill it so every ticket this server issues is the same
// length, as a real server's would be.
func (k *TicketKey) Issue(clientID uint64, ticketLen int) (*Credential, error) {
return k.issueAt(clientID, ticketLen, time.Now())
}
func (k *TicketKey) issueAt(clientID uint64, ticketLen int, now time.Time) (*Credential, error) {
cred := &Credential{}
if _, err := rand.Read(cred.PSK[:]); err != nil {
return nil, err
}
var err error
if cred.Ticket, err = k.seal(clientID, cred.PSK, ticketLen, now); err != nil {
return nil, err
}
// Sealed at the SAME instant, deliberately. ReplayCache refuses a ticket
// older than the client's newest, so two tickets of one credential bearing
// different issue times would make whichever path the client used second
// look like a stale capture and fail.
if cred.FullTicket, err = k.seal(clientID, cred.PSK, FullTicketLen, now); err != nil {
return nil, err
}
return cred, nil
}
// IssueFullFor mints the full-handshake companion for an EXISTING ticket,
// which is how a credential provisioned before the carrier is upgraded.
//
// A client needs both tickets because the two paths size them for
// incompatible reasons. On the resumption path the length is a fidelity
// parameter -- the ticket sets the emitted hello size, so it must match the
// identity being impersonated. Inside the ECH payload it must instead fit
// Chrome's smallest bucket. Those constraints do not meet: a microsoft-sized
// 256-byte ticket fits no ECH bucket at all.
//
// It takes the ticket rather than the fields so the clientID, psk AND issue
// time can only come from the ticket being companioned. Passing those
// separately would make it possible to seal a companion with a different
// issue time, which ReplayCache would then read as a stale capture.
func (k *TicketKey) IssueFullFor(ticket []byte) ([]byte, error) {
clientID, psk, issued, err := k.Open(ticket)
if err != nil {
return nil, err
}
return k.seal(clientID, psk, FullTicketLen, issued)
}
// seal builds one ticket. The plaintext is padded to fill ticketLen so every
// ticket a server issues at a given length is that length, as a real server's
// would be.
func (k *TicketKey) seal(clientID uint64, psk [32]byte, ticketLen int, now time.Time) ([]byte, error) {
if ticketLen < MinTicketLen {
return nil, fmt.Errorf("twiddle: ticket length %d below minimum %d", ticketLen, MinTicketLen)
}
aead, err := k.aead()
if err != nil {
return nil, err
}
plain := make([]byte, ticketLen-ticketNonceLen-ticketTagLen)
binary.BigEndian.PutUint64(plain[0:8], clientID)
copy(plain[8:40], psk[:])
binary.BigEndian.PutUint64(plain[40:48], uint64(now.Unix()))
if _, err := rand.Read(plain[ticketFixed:]); err != nil {
return nil, err
}
nonce := make([]byte, ticketNonceLen)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
return aead.Seal(nonce, nonce, plain, nil), nil
}
// Open recovers a ticket's contents. Only the holder of the ticket key can do
// this, which is what keeps the authenticator verifiable by the server alone.
func (k *TicketKey) Open(ticket []byte) (clientID uint64, psk [32]byte, issued time.Time, err error) {
if len(ticket) < MinTicketLen {
return 0, psk, issued, errors.New("twiddle: ticket too short")
}
aead, err := k.aead()
if err != nil {
return 0, psk, issued, err
}
plain, err := aead.Open(nil, ticket[:ticketNonceLen], ticket[ticketNonceLen:], nil)
if err != nil {
return 0, psk, issued, errors.New("twiddle: ticket does not decrypt")
}
if len(plain) < ticketFixed {
return 0, psk, issued, errMalformed
}
clientID = binary.BigEndian.Uint64(plain[0:8])
copy(psk[:], plain[8:40])
issued = time.Unix(int64(binary.BigEndian.Uint64(plain[40:48])), 0)
return clientID, psk, issued, nil
}
func binderKey(psk []byte) []byte {
m := hmac.New(sha256.New, psk)
m.Write([]byte("twiddle/binder/v1"))
return m.Sum(nil)
}
func binderHash(binderLen int) (func() hash.Hash, error) {
switch binderLen {
case sha256.Size:
return sha256.New, nil
case sha512.Size384:
return sha512.New384, nil
default:
return nil, fmt.Errorf("twiddle: binder length %d is neither 32 (SHA-256) nor 48 (SHA-384)", binderLen)
}
}
// SetKeyShare replaces the X25519 entry's public key with a real ephemeral,
// leaving every other offered group untouched. Returns the private key.
func (h *ClientHello) SetKeyShare() (*ecdh.PrivateKey, error) {
e := h.Find(ExtKeyShare)
if e == nil {
return nil, errors.New("twiddle: hello has no key_share")
}
priv, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
pub := priv.PublicKey().Bytes()
d := e.Data
p := 2
for p+4 <= len(d) {
g := binary.BigEndian.Uint16(d[p : p+2])
n := int(binary.BigEndian.Uint16(d[p+2 : p+4]))
if p+4+n > len(d) {
return nil, errMalformed
}
if g == GroupX25519 && n == len(pub) {
copy(d[p+4:p+4+n], pub)
return priv, nil
}
p += 4 + n
}
return nil, errors.New("twiddle: hello offers no X25519 key_share")
}
// KeyShare returns the client's offered X25519 public key.
func (h *ClientHello) KeyShare() (*ecdh.PublicKey, error) {
e := h.Find(ExtKeyShare)
if e == nil {
return nil, errors.New("twiddle: hello has no key_share")
}
d := e.Data
p := 2
for p+4 <= len(d) {
g := binary.BigEndian.Uint16(d[p : p+2])
n := int(binary.BigEndian.Uint16(d[p+2 : p+4]))
if p+4+n > len(d) {
return nil, errMalformed
}
if g == GroupX25519 {
return ecdh.X25519().NewPublicKey(d[p+4 : p+4+n])
}
p += 4 + n
}
return nil, errors.New("twiddle: hello offers no X25519 key_share")
}
// SetTicketAuth installs the credential and computes the binder over the final
// byte layout. Call it last -- see Twiddle.
func (h *ClientHello) SetTicketAuth(cred *Credential, binderLen int) error {
newHash, err := binderHash(binderLen)
if err != nil {
return err
}
var age [4]byte
if _, err := rand.Read(age[:]); err != nil {
return err
}
setPSK(h, cred.Ticket, age, make([]byte, binderLen))
m := hmac.New(newHash, binderKey(cred.PSK[:]))
m.Write(truncateForBinder(h.Marshal(), binderLen))
setPSK(h, cred.Ticket, age, m.Sum(nil))
return nil
}
// AuthResult is what a verified opening yields.
type AuthResult struct {
ClientID uint64
PSK [32]byte
Issued time.Time
ClientEphemeral *ecdh.PublicKey
}
// VerifyTicketAuth authenticates a hello. maxAge bounds ticket lifetime; pass 0
// to skip the check.
func VerifyTicketAuth(h *ClientHello, k *TicketKey, maxAge time.Duration) (*AuthResult, error) {
return verifyAt(h, k, maxAge, time.Now())
}
func verifyAt(h *ClientHello, k *TicketKey, maxAge time.Duration, now time.Time) (*AuthResult, error) {
e := h.Find(ExtPreSharedKey)
if e == nil {
return nil, errors.New("twiddle: hello carries no pre_shared_key")
}
ticket, age, binder, err := parsePSK(e.Data)
if err != nil {
return nil, err
}
clientID, psk, issued, err := k.Open(ticket)
if err != nil {
return nil, err
}
if maxAge > 0 && now.Sub(issued) > maxAge {
return nil, fmt.Errorf("twiddle: ticket is %v old, limit %v", now.Sub(issued).Truncate(time.Second), maxAge)
}
newHash, err := binderHash(len(binder))
if err != nil {
return nil, err
}
probe := *h
probe.Extensions = append([]Extension(nil), h.Extensions...)
setPSK(&probe, ticket, age, make([]byte, len(binder)))
m := hmac.New(newHash, binderKey(psk[:]))
m.Write(truncateForBinder(probe.Marshal(), len(binder)))
if !hmac.Equal(m.Sum(nil), binder) {
return nil, errors.New("twiddle: binder does not verify")
}
eph, err := h.KeyShare()
if err != nil {
return nil, err
}
return &AuthResult{ClientID: clientID, PSK: psk, Issued: issued, ClientEphemeral: eph}, nil
}
// truncateForBinder drops the binders list, mirroring RFC 8446's Truncate().
func truncateForBinder(rec []byte, binderLen int) []byte {
cut := 2 + 1 + binderLen
if len(rec) < cut {
return rec
}
return rec[:len(rec)-cut]
}
// setPSK writes pre_shared_key and moves it to the end. RFC 8446 §4.2.11
// requires it last, and that is what makes the binder truncation well defined.
// obfuscated_ticket_age is caller-supplied because this runs twice per
// authentication and any field differing between the two calls would break
// verification.
func setPSK(h *ClientHello, ticket []byte, age [4]byte, binder []byte) {
d := make([]byte, 0, 11+len(ticket)+len(binder))
d = appendU16(d, uint16(len(ticket)+6))
d = appendU16(d, uint16(len(ticket)))
d = append(d, ticket...)
d = append(d, age[:]...)
d = appendU16(d, uint16(len(binder)+1))
d = append(d, byte(len(binder)))
d = append(d, binder...)
out := h.Extensions[:0:0]
for _, e := range h.Extensions {
if e.Type != ExtPreSharedKey {
out = append(out, e)
}
}
h.Extensions = append(out, Extension{ExtPreSharedKey, d})
}
func parsePSK(d []byte) (ticket []byte, age [4]byte, binder []byte, err error) {
if len(d) < 2 {
return nil, age, nil, errMalformed
}
idsEnd := 2 + int(binary.BigEndian.Uint16(d[0:2]))
if idsEnd+2 > len(d) || idsEnd < 4 {
return nil, age, nil, errMalformed
}
tl := int(binary.BigEndian.Uint16(d[2:4]))
if 4+tl+4 > len(d) {
return nil, age, nil, errMalformed
}
ticket = d[4 : 4+tl]
copy(age[:], d[4+tl:4+tl+4])
p := idsEnd + 2
if p >= len(d) {
return nil, age, nil, errMalformed
}
bl := int(d[p])
if p+1+bl > len(d) {
return nil, age, nil, errMalformed
}
return ticket, age, d[p+1 : p+1+bl], nil
}