forked from bifurcation/mint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
record-layer.go
241 lines (202 loc) · 6.13 KB
/
record-layer.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
package mint
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"fmt"
"io"
"sync"
)
const (
sequenceNumberLen = 8 // sequence number length
recordHeaderLen = 5 // record header length
maxFragmentLen = 1 << 14 // max number of bytes in a record
)
// struct {
// ContentType type;
// ProtocolVersion record_version = { 3, 1 }; /* TLS v1.x */
// uint16 length;
// opaque fragment[TLSPlaintext.length];
// } TLSPlaintext;
type tlsPlaintext struct {
// Omitted: record_version (static)
// Omitted: length (computed from fragment)
contentType recordType
fragment []byte
}
type recordLayer struct {
sync.Mutex
conn io.ReadWriter // The underlying connection
buffer []byte // The next record to send
nextData []byte // The next record to send
ivLength int // Length of the seq and nonce fields
seq []byte // Zero-padded sequence number
nonce []byte // Buffer for per-record nonces
cipher cipher.AEAD // AEAD cipher
}
func newRecordLayer(conn io.ReadWriter) *recordLayer {
r := recordLayer{}
r.conn = conn
r.ivLength = 0
return &r
}
func (r *recordLayer) Rekey(suite cipherSuite, key []byte, iv []byte) error {
switch suite {
case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
params := cipherSuiteMap[suite]
if len(key) != params.keyLen || len(iv) != params.ivLen {
return fmt.Errorf("tls.rekey: Crypto parameters are the wrong size")
}
aes, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCMWithNonceSize(aes, len(iv))
r.cipher = gcm
r.ivLength = len(iv)
default:
return fmt.Errorf("tls.rekey: Unsupported ciphersuite: %x", suite)
}
r.seq = bytes.Repeat([]byte{0}, r.ivLength)
r.nonce = make([]byte, r.ivLength)
copy(r.nonce, iv)
return nil
}
func (r *recordLayer) incrementSequenceNumber() {
if r.ivLength == 0 {
return
}
for i := r.ivLength - 1; i > r.ivLength-sequenceNumberLen; i-- {
r.seq[i]++
r.nonce[i] ^= (r.seq[i] - 1) ^ r.seq[i]
if r.seq[i] != 0 {
return
}
}
// Not allowed to let sequence number wrap.
// Instead, must renegotiate before it does.
// Not likely enough to bother.
panic("TLS: sequence number wraparound")
}
func (r *recordLayer) encrypt(pt *tlsPlaintext, padLen int) *tlsPlaintext {
// Expand the fragment to hold contentType, padding, and overhead
originalLen := len(pt.fragment)
plaintextLen := originalLen + 1 + padLen
ciphertextLen := plaintextLen + r.cipher.Overhead()
// Assemble the revised plaintext
out := &tlsPlaintext{
contentType: pt.contentType,
fragment: make([]byte, ciphertextLen),
}
copy(out.fragment, pt.fragment)
out.fragment[originalLen] = byte(pt.contentType)
for i := 1; i <= padLen; i++ {
out.fragment[originalLen+i] = 0
}
// Encrypt the fragment
payload := out.fragment[:plaintextLen]
r.cipher.Seal(payload[:0], r.nonce, payload, nil)
return out
}
func (r *recordLayer) decrypt(pt *tlsPlaintext) (*tlsPlaintext, int, error) {
decryptLen := len(pt.fragment) - r.cipher.Overhead()
out := &tlsPlaintext{
contentType: pt.contentType,
fragment: make([]byte, decryptLen),
}
// Decrypt
_, err := r.cipher.Open(out.fragment[:0], r.nonce, pt.fragment, nil)
if err != nil {
return nil, 0, fmt.Errorf("tls.record.decrypt: AEAD decrypt failed")
}
// Find the padding boundary
padLen := 0
for ; padLen < decryptLen+1 && out.fragment[decryptLen-padLen-1] == 0; padLen++ {
}
// Transfer the content type
newLen := decryptLen - padLen - 1
out.contentType = recordType(out.fragment[newLen])
// Truncate the message to remove contentType, padding, overhead
out.fragment = out.fragment[:newLen]
return out, padLen, nil
}
func (r *recordLayer) readFullBuffer(data []byte) error {
buffer := make([]byte, cap(data)+recordHeaderLen)
var index int
copy(buffer, r.nextData)
index = len(r.nextData)
for {
m, err := r.conn.Read(buffer[index:])
if m+index >= cap(data) {
// TODO(bradfitz,agl): slightly suspicious
// that we're throwing away r.Read's err here.
copy(data[:cap(data)], buffer)
r.nextData = buffer[cap(data) : m+index]
return nil
}
if err != nil {
return err
}
index = index + m
}
}
func (r *recordLayer) ReadRecord() (*tlsPlaintext, error) {
pt := &tlsPlaintext{}
header := make([]byte, recordHeaderLen)
err := r.readFullBuffer(header)
if err != nil {
return nil, err
}
// Validate content type
switch recordType(header[0]) {
default:
return nil, fmt.Errorf("tls.record: Unknown content type %02x", header[0])
case recordTypeAlert, recordTypeHandshake, recordTypeApplicationData:
pt.contentType = recordType(header[0])
}
// Validate version
if !allowWrongVersionNumber && (header[1] != 0x03 || header[2] != 0x01) {
return nil, fmt.Errorf("tls.record: Invalid version %02x%02x", header[1], header[2])
}
// Validate size < max
size := (int(header[3]) << 8) + int(header[4])
if size > maxFragmentLen {
return nil, fmt.Errorf("tls.record: Record size too big")
}
// Attempt to read fragment
pt.fragment = make([]byte, size)
err = r.readFullBuffer(pt.fragment[:0])
if err != nil {
return nil, err
}
// Attempt to decrypt fragment
if r.cipher != nil {
pt, _, err = r.decrypt(pt)
if err != nil {
return nil, err
}
}
logf(logTypeIO, "recordLayer.ReadRecord [%d] [%x]", pt.contentType, pt.fragment)
r.incrementSequenceNumber()
return pt, nil
}
func (r *recordLayer) WriteRecord(pt *tlsPlaintext) error {
return r.WriteRecordWithPadding(pt, 0)
}
func (r *recordLayer) WriteRecordWithPadding(pt *tlsPlaintext, padLen int) error {
if r.cipher != nil {
pt = r.encrypt(pt, padLen)
} else if padLen > 0 {
return fmt.Errorf("tls.record: Padding can only be done on encrypted records")
}
if len(pt.fragment) > maxFragmentLen {
return fmt.Errorf("tls.record: Record size too big")
}
length := len(pt.fragment)
header := []byte{byte(pt.contentType), 0x03, 0x01, byte(length >> 8), byte(length)}
record := append(header, pt.fragment...)
logf(logTypeIO, "recordLayer.WriteRecord [%d] [%x]", pt.contentType, pt.fragment)
r.incrementSequenceNumber()
_, err := r.conn.Write(record)
return err
}