forked from cloudflare/tls-tris
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ticket.go
452 lines (395 loc) · 12.8 KB
/
ticket.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"errors"
"io"
// [Psiphon]
"crypto/rand"
"crypto/x509"
"math/big"
math_rand "math/rand"
)
// [Psiphon]
var obfuscateSessionTickets = true
// A SessionTicketSealer provides a way to securely encapsulate
// session state for storage on the client. All methods are safe for
// concurrent use.
type SessionTicketSealer interface {
// Seal returns a session ticket value that can be later passed to Unseal
// to recover the content, usually by encrypting it. The ticket will be sent
// to the client to be stored, and will be sent back in plaintext, so it can
// be read and modified by an attacker.
Seal(cs *ConnectionState, content []byte) (ticket []byte, err error)
// Unseal returns a session ticket contents. The ticket can't be safely
// assumed to have been generated by Seal.
// If unable to unseal the ticket, the connection will proceed with a
// complete handshake.
Unseal(chi *ClientHelloInfo, ticket []byte) (content []byte, success bool)
}
// sessionState contains the information that is serialized into a session
// ticket in order to later resume a connection.
type sessionState struct {
vers uint16
cipherSuite uint16
usedEMS bool
masterSecret []byte
certificates [][]byte
// usedOldKey is true if the ticket from which this session came from
// was encrypted with an older key and thus should be refreshed.
usedOldKey bool
}
func (s *sessionState) equal(i interface{}) bool {
s1, ok := i.(*sessionState)
if !ok {
return false
}
if s.vers != s1.vers ||
s.usedEMS != s1.usedEMS ||
s.cipherSuite != s1.cipherSuite ||
!bytes.Equal(s.masterSecret, s1.masterSecret) {
return false
}
if len(s.certificates) != len(s1.certificates) {
return false
}
for i := range s.certificates {
if !bytes.Equal(s.certificates[i], s1.certificates[i]) {
return false
}
}
return true
}
func (s *sessionState) marshal() []byte {
length := 2 + 2 + 2 + len(s.masterSecret) + 2
for _, cert := range s.certificates {
length += 4 + len(cert)
}
// [Psiphon]
// Pad golang TLS session ticket to a more typical size.
if obfuscateSessionTickets {
paddedSizes := []int{160, 176, 192, 208, 218, 224, 240, 255}
initialSize := 120
randomInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(paddedSizes))))
index := 0
if err == nil {
index = int(randomInt.Int64())
} else {
index = math_rand.Intn(len(paddedSizes))
}
paddingSize := paddedSizes[index] - initialSize
length += paddingSize
}
ret := make([]byte, length)
x := ret
was_used := byte(0)
if s.usedEMS {
was_used = byte(0x80)
}
x[0] = byte(s.vers>>8) | byte(was_used)
x[1] = byte(s.vers)
x[2] = byte(s.cipherSuite >> 8)
x[3] = byte(s.cipherSuite)
x[4] = byte(len(s.masterSecret) >> 8)
x[5] = byte(len(s.masterSecret))
x = x[6:]
copy(x, s.masterSecret)
x = x[len(s.masterSecret):]
x[0] = byte(len(s.certificates) >> 8)
x[1] = byte(len(s.certificates))
x = x[2:]
for _, cert := range s.certificates {
x[0] = byte(len(cert) >> 24)
x[1] = byte(len(cert) >> 16)
x[2] = byte(len(cert) >> 8)
x[3] = byte(len(cert))
copy(x[4:], cert)
x = x[4+len(cert):]
}
return ret
}
func (s *sessionState) unmarshal(data []byte) alert {
if len(data) < 8 {
return alertDecodeError
}
s.vers = (uint16(data[0])<<8 | uint16(data[1])) & 0x7fff
s.cipherSuite = uint16(data[2])<<8 | uint16(data[3])
s.usedEMS = (data[0] & 0x80) == 0x80
masterSecretLen := int(data[4])<<8 | int(data[5])
data = data[6:]
if len(data) < masterSecretLen {
return alertDecodeError
}
s.masterSecret = data[:masterSecretLen]
data = data[masterSecretLen:]
if len(data) < 2 {
return alertDecodeError
}
numCerts := int(data[0])<<8 | int(data[1])
data = data[2:]
s.certificates = make([][]byte, numCerts)
for i := range s.certificates {
if len(data) < 4 {
return alertDecodeError
}
certLen := int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3])
data = data[4:]
if certLen < 0 {
return alertDecodeError
}
if len(data) < certLen {
return alertDecodeError
}
s.certificates[i] = data[:certLen]
data = data[certLen:]
}
// [Psiphon]
// Ignore padding for obfuscated session tickets
//if len(data) != 0 {
// return alertDecodeError
//}
return alertSuccess
}
// [Psiphon]
type ObfuscatedClientSessionState struct {
SessionTicket []uint8
Vers uint16
CipherSuite uint16
MasterSecret []byte
ServerCertificates []*x509.Certificate
VerifiedChains [][]*x509.Certificate
UseEMS bool
}
var obfuscatedSessionTicketCipherSuite = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
// [Psiphon]
// NewObfuscatedClientSessionState produces obfuscated session tickets.
//
// Obfuscated Session Tickets
//
// Obfuscated session tickets is a network traffic obfuscation protocol that appears
// to be valid TLS using session tickets. The client actually generates the session
// ticket and encrypts it with a shared secret, enabling a TLS session that entirely
// skips the most fingerprintable aspects of TLS.
// The scheme is described here:
// https://lists.torproject.org/pipermail/tor-dev/2016-September/011354.html
//
// Circumvention notes:
// - TLS session ticket implementations are widespread:
// https://istlsfastyet.com/#cdn-paas.
// - An adversary cannot easily block session ticket capability, as this requires
// a downgrade attack against TLS.
// - Anti-probing defence is provided, as the adversary must use the correct obfuscation
// shared secret to form valid obfuscation session ticket; otherwise server offers
// standard session tickets.
// - Limitation: an adversary with the obfuscation shared secret can decrypt the session
// ticket and observe the plaintext traffic. It's assumed that the adversary will not
// learn the obfuscated shared secret without also learning the address of the TLS
// server and blocking it anyway; it's also assumed that the TLS payload is not
// plaintext but is protected with some other security layer (e.g., SSH).
//
// Implementation notes:
// - The TLS ClientHello includes an SNI field, even when using session tickets, so
// the client should populate the ServerName.
// - Server should set its SetSessionTicketKeys with first a standard key, followed by
// the obfuscation shared secret.
// - Since the client creates the session ticket, it selects parameters that were not
// negotiated with the server, such as the cipher suite. It's implicitly assumed that
// the server can support the selected parameters.
// - Obfuscated session tickets are not supported for TLS 1.3 _clients_, which use a
// distinct scheme. Obfuscated session ticket support in this package is intended to
// support TLS 1.2 clients.
//
func NewObfuscatedClientSessionState(sharedSecret [32]byte) (*ObfuscatedClientSessionState, error) {
// Create a session ticket that wasn't actually issued by the server.
vers := uint16(VersionTLS12)
cipherSuite := obfuscatedSessionTicketCipherSuite
masterSecret := make([]byte, masterSecretLength)
_, err := rand.Read(masterSecret)
if err != nil {
return nil, err
}
serverState := &sessionState{
vers: vers,
cipherSuite: cipherSuite,
masterSecret: masterSecret,
certificates: nil,
}
c := &Conn{
config: &Config{
sessionTicketKeys: []ticketKey{ticketKeyFromBytes(sharedSecret)},
},
}
sessionTicket, err := c.encryptTicket(serverState.marshal())
if err != nil {
return nil, err
}
// ObfuscatedClientSessionState fields are used to construct
// ClientSessionState objects for use in ClientSessionCaches. The client will
// use this cache to pretend it got that session ticket from the server.
clientState := &ObfuscatedClientSessionState{
SessionTicket: sessionTicket,
Vers: vers,
CipherSuite: cipherSuite,
MasterSecret: masterSecret,
}
return clientState, nil
}
func ContainsObfuscatedSessionTicketCipherSuite(cipherSuites []uint16) bool {
for _, cipherSuite := range cipherSuites {
if cipherSuite == obfuscatedSessionTicketCipherSuite {
return true
}
}
return false
}
type sessionState13 struct {
vers uint16
suite uint16
ageAdd uint32
createdAt uint64
maxEarlyDataLen uint32
pskSecret []byte
alpnProtocol string
SNI string
}
func (s *sessionState13) equal(i interface{}) bool {
s1, ok := i.(*sessionState13)
if !ok {
return false
}
return s.vers == s1.vers &&
s.suite == s1.suite &&
s.ageAdd == s1.ageAdd &&
s.createdAt == s1.createdAt &&
s.maxEarlyDataLen == s1.maxEarlyDataLen &&
subtle.ConstantTimeCompare(s.pskSecret, s1.pskSecret) == 1 &&
s.alpnProtocol == s1.alpnProtocol &&
s.SNI == s1.SNI
}
func (s *sessionState13) marshal() []byte {
length := 2 + 2 + 4 + 8 + 4 + 2 + len(s.pskSecret) + 2 + len(s.alpnProtocol) + 2 + len(s.SNI)
x := make([]byte, length)
x[0] = byte(s.vers >> 8)
x[1] = byte(s.vers)
x[2] = byte(s.suite >> 8)
x[3] = byte(s.suite)
x[4] = byte(s.ageAdd >> 24)
x[5] = byte(s.ageAdd >> 16)
x[6] = byte(s.ageAdd >> 8)
x[7] = byte(s.ageAdd)
x[8] = byte(s.createdAt >> 56)
x[9] = byte(s.createdAt >> 48)
x[10] = byte(s.createdAt >> 40)
x[11] = byte(s.createdAt >> 32)
x[12] = byte(s.createdAt >> 24)
x[13] = byte(s.createdAt >> 16)
x[14] = byte(s.createdAt >> 8)
x[15] = byte(s.createdAt)
x[16] = byte(s.maxEarlyDataLen >> 24)
x[17] = byte(s.maxEarlyDataLen >> 16)
x[18] = byte(s.maxEarlyDataLen >> 8)
x[19] = byte(s.maxEarlyDataLen)
x[20] = byte(len(s.pskSecret) >> 8)
x[21] = byte(len(s.pskSecret))
copy(x[22:], s.pskSecret)
z := x[22+len(s.pskSecret):]
z[0] = byte(len(s.alpnProtocol) >> 8)
z[1] = byte(len(s.alpnProtocol))
copy(z[2:], s.alpnProtocol)
z = z[2+len(s.alpnProtocol):]
z[0] = byte(len(s.SNI) >> 8)
z[1] = byte(len(s.SNI))
copy(z[2:], s.SNI)
return x
}
func (s *sessionState13) unmarshal(data []byte) alert {
if len(data) < 24 {
return alertDecodeError
}
s.vers = uint16(data[0])<<8 | uint16(data[1])
s.suite = uint16(data[2])<<8 | uint16(data[3])
s.ageAdd = uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
s.createdAt = uint64(data[8])<<56 | uint64(data[9])<<48 | uint64(data[10])<<40 | uint64(data[11])<<32 |
uint64(data[12])<<24 | uint64(data[13])<<16 | uint64(data[14])<<8 | uint64(data[15])
s.maxEarlyDataLen = uint32(data[16])<<24 | uint32(data[17])<<16 | uint32(data[18])<<8 | uint32(data[19])
l := int(data[20])<<8 | int(data[21])
if len(data) < 22+l+2 {
return alertDecodeError
}
s.pskSecret = data[22 : 22+l]
z := data[22+l:]
l = int(z[0])<<8 | int(z[1])
if len(z) < 2+l+2 {
return alertDecodeError
}
s.alpnProtocol = string(z[2 : 2+l])
z = z[2+l:]
l = int(z[0])<<8 | int(z[1])
if len(z) != 2+l {
return alertDecodeError
}
s.SNI = string(z[2 : 2+l])
return alertSuccess
}
func (c *Conn) encryptTicket(serialized []byte) ([]byte, error) {
encrypted := make([]byte, ticketKeyNameLen+aes.BlockSize+len(serialized)+sha256.Size)
keyName := encrypted[:ticketKeyNameLen]
iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize]
macBytes := encrypted[len(encrypted)-sha256.Size:]
if _, err := io.ReadFull(c.config.rand(), iv); err != nil {
return nil, err
}
key := c.config.ticketKeys()[0]
copy(keyName, key.keyName[:])
block, err := aes.NewCipher(key.aesKey[:])
if err != nil {
return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error())
}
cipher.NewCTR(block, iv).XORKeyStream(encrypted[ticketKeyNameLen+aes.BlockSize:], serialized)
mac := hmac.New(sha256.New, key.hmacKey[:])
mac.Write(encrypted[:len(encrypted)-sha256.Size])
mac.Sum(macBytes[:0])
return encrypted, nil
}
func (c *Conn) decryptTicket(encrypted []byte) (serialized []byte, usedOldKey bool) {
if c.config.SessionTicketsDisabled ||
len(encrypted) < ticketKeyNameLen+aes.BlockSize+sha256.Size {
return nil, false
}
keyName := encrypted[:ticketKeyNameLen]
iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize]
macBytes := encrypted[len(encrypted)-sha256.Size:]
keys := c.config.ticketKeys()
keyIndex := -1
for i, candidateKey := range keys {
if bytes.Equal(keyName, candidateKey.keyName[:]) {
keyIndex = i
break
}
}
if keyIndex == -1 {
return nil, false
}
key := &keys[keyIndex]
mac := hmac.New(sha256.New, key.hmacKey[:])
mac.Write(encrypted[:len(encrypted)-sha256.Size])
expected := mac.Sum(nil)
if subtle.ConstantTimeCompare(macBytes, expected) != 1 {
return nil, false
}
block, err := aes.NewCipher(key.aesKey[:])
if err != nil {
return nil, false
}
ciphertext := encrypted[ticketKeyNameLen+aes.BlockSize : len(encrypted)-sha256.Size]
plaintext := ciphertext
cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext)
return plaintext, keyIndex > 0
}