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
|
package org.bouncycastle.crypto.tls;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bouncycastle.crypto.Digest;
/**
* An implementation of the TLS 1.0/1.1/1.2 record layer, allowing downgrade to SSLv3.
*/
class RecordStream {
private static int PLAINTEXT_LIMIT = (1 << 14);
private static int COMPRESSED_LIMIT = PLAINTEXT_LIMIT + 1024;
private static int CIPHERTEXT_LIMIT = COMPRESSED_LIMIT + 1024;
private TlsProtocol handler;
private InputStream input;
private OutputStream output;
private TlsCompression pendingCompression = null, readCompression = null, writeCompression = null;
private TlsCipher pendingCipher = null, readCipher = null, writeCipher = null;
private long readSeqNo = 0, writeSeqNo = 0;
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private TlsContext context = null;
private TlsHandshakeHash hash = null;
private ProtocolVersion readVersion = null, writeVersion = null;
private boolean restrictReadVersion = true;
RecordStream(TlsProtocol handler, InputStream input, OutputStream output) {
this.handler = handler;
this.input = input;
this.output = output;
this.readCompression = new TlsNullCompression();
this.writeCompression = this.readCompression;
this.readCipher = new TlsNullCipher(context);
this.writeCipher = this.readCipher;
}
void init(TlsContext context) {
this.context = context;
this.hash = new DeferredHash();
this.hash.init(context);
}
ProtocolVersion getReadVersion() {
return readVersion;
}
void setReadVersion(ProtocolVersion readVersion) {
this.readVersion = readVersion;
}
void setWriteVersion(ProtocolVersion writeVersion) {
this.writeVersion = writeVersion;
}
/**
* RFC 5246 E.1. "Earlier versions of the TLS specification were not fully clear on what the
* record layer version number (TLSPlaintext.version) should contain when sending ClientHello
* (i.e., before it is known which version of the protocol will be employed). Thus, TLS servers
* compliant with this specification MUST accept any value {03,XX} as the record layer version
* number for ClientHello."
*/
void setRestrictReadVersion(boolean enabled) {
this.restrictReadVersion = enabled;
}
void notifyHelloComplete() {
this.hash = this.hash.commit();
}
void setPendingConnectionState(TlsCompression tlsCompression, TlsCipher tlsCipher) {
this.pendingCompression = tlsCompression;
this.pendingCipher = tlsCipher;
}
void sentWriteCipherSpec() throws IOException {
if (pendingCompression == null || pendingCipher == null) {
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
this.writeCompression = this.pendingCompression;
this.writeCipher = this.pendingCipher;
this.writeSeqNo = 0;
}
void receivedReadCipherSpec() throws IOException {
if (pendingCompression == null || pendingCipher == null) {
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
this.readCompression = this.pendingCompression;
this.readCipher = this.pendingCipher;
this.readSeqNo = 0;
}
void finaliseHandshake() throws IOException {
if (readCompression != pendingCompression || writeCompression != pendingCompression
|| readCipher != pendingCipher || writeCipher != pendingCipher) {
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
pendingCompression = null;
pendingCipher = null;
}
public void readRecord() throws IOException {
short type = TlsUtils.readUint8(input);
// TODO In earlier RFCs, it was "SHOULD ignore"; should this be version-dependent?
/*
* RFC 5246 6. If a TLS implementation receives an unexpected record type, it MUST send an
* unexpected_message alert.
*/
checkType(type, AlertDescription.unexpected_message);
if (!restrictReadVersion) {
int version = TlsUtils.readVersionRaw(input);
if ((version & 0xffffff00) != 0x0300) {
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
} else {
ProtocolVersion version = TlsUtils.readVersion(input);
if (readVersion == null) {
readVersion = version;
} else if (!version.equals(readVersion)) {
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
int length = TlsUtils.readUint16(input);
byte[] plaintext = decodeAndVerify(type, input, length);
handler.processRecord(type, plaintext, 0, plaintext.length);
}
protected byte[] decodeAndVerify(short type, InputStream input, int len) throws IOException {
checkLength(len, CIPHERTEXT_LIMIT, AlertDescription.record_overflow);
byte[] buf = TlsUtils.readFully(len, input);
byte[] decoded = readCipher.decodeCiphertext(readSeqNo++, type, buf, 0, buf.length);
checkLength(decoded.length, COMPRESSED_LIMIT, AlertDescription.record_overflow);
/*
* TODO RFC5264 6.2.2. Implementation note: Decompression functions are responsible for
* ensuring that messages cannot cause internal buffer overflows.
*/
OutputStream cOut = readCompression.decompress(buffer);
if (cOut != buffer) {
cOut.write(decoded, 0, decoded.length);
cOut.flush();
decoded = getBufferContents();
}
/*
* RFC 5264 6.2.2. If the decompression function encounters a TLSCompressed.fragment that
* would decompress to a length in excess of 2^14 bytes, it should report a fatal
* decompression failure error.
*/
checkLength(decoded.length, PLAINTEXT_LIMIT, AlertDescription.decompression_failure);
return decoded;
}
protected void writeRecord(short type, byte[] plaintext, int plaintextOffset, int plaintextLength)
throws IOException {
/*
* RFC 5264 6. Implementations MUST NOT send record types not defined in this document
* unless negotiated by some extension.
*/
checkType(type, AlertDescription.internal_error);
/*
* RFC 5264 6.2.1 The length should not exceed 2^14.
*/
checkLength(plaintextLength, PLAINTEXT_LIMIT, AlertDescription.internal_error);
/*
* RFC 5264 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
* or ChangeCipherSpec content types.
*/
if (plaintextLength < 1 && type != ContentType.application_data) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
if (type == ContentType.handshake) {
updateHandshakeData(plaintext, plaintextOffset, plaintextLength);
}
OutputStream cOut = writeCompression.compress(buffer);
byte[] ciphertext;
if (cOut == buffer) {
ciphertext = writeCipher.encodePlaintext(writeSeqNo++, type, plaintext, plaintextOffset, plaintextLength);
} else {
cOut.write(plaintext, plaintextOffset, plaintextLength);
cOut.flush();
byte[] compressed = getBufferContents();
/*
* RFC5264 6.2.2. Compression must be lossless and may not increase the content length
* by more than 1024 bytes.
*/
checkLength(compressed.length, plaintextLength + 1024, AlertDescription.internal_error);
ciphertext = writeCipher.encodePlaintext(writeSeqNo++, type, compressed, 0, compressed.length);
}
/*
* RFC 5264 6.2.3. The length may not exceed 2^14 + 2048.
*/
checkLength(ciphertext.length, CIPHERTEXT_LIMIT, AlertDescription.internal_error);
byte[] record = new byte[ciphertext.length + 5];
TlsUtils.writeUint8(type, record, 0);
TlsUtils.writeVersion(writeVersion, record, 1);
TlsUtils.writeUint16(ciphertext.length, record, 3);
System.arraycopy(ciphertext, 0, record, 5, ciphertext.length);
output.write(record);
output.flush();
}
void updateHandshakeData(byte[] message, int offset, int len) {
hash.update(message, offset, len);
}
/**
* 'sender' only relevant to SSLv3
*/
byte[] getCurrentHash(byte[] sender) {
TlsHandshakeHash d = hash.fork();
if (context.getServerVersion().isSSL()) {
if (sender != null) {
d.update(sender, 0, sender.length);
}
}
return doFinal(d);
}
protected void close() throws IOException {
IOException e = null;
try {
input.close();
} catch (IOException ex) {
e = ex;
}
try {
output.close();
} catch (IOException ex) {
e = ex;
}
if (e != null) {
throw e;
}
}
protected void flush() throws IOException {
output.flush();
}
private byte[] getBufferContents() {
byte[] contents = buffer.toByteArray();
buffer.reset();
return contents;
}
private static byte[] doFinal(Digest d) {
byte[] bs = new byte[d.getDigestSize()];
d.doFinal(bs, 0);
return bs;
}
private static void checkType(short type, short alertDescription) throws IOException {
switch (type) {
case ContentType.change_cipher_spec:
case ContentType.alert:
case ContentType.handshake:
case ContentType.application_data:
break;
default:
throw new TlsFatalAlert(alertDescription);
}
}
private static void checkLength(int length, int limit, short alertDescription) throws IOException {
if (length > limit) {
throw new TlsFatalAlert(alertDescription);
}
}
}
|