-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathblocking.rs
483 lines (415 loc) · 14.7 KB
/
blocking.rs
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use core::sync::atomic::Ordering;
use crate::common::decrypted_buffer_info::DecryptedBufferInfo;
use crate::common::decrypted_read_handler::DecryptedReadHandler;
use crate::connection::{Handshake, State, decrypt_record};
use crate::key_schedule::KeySchedule;
use crate::key_schedule::{ReadKeySchedule, WriteKeySchedule};
use crate::read_buffer::ReadBuffer;
use crate::record::{ClientRecord, ClientRecordHeader};
use crate::record_reader::{RecordReader, RecordReaderBorrowMut};
use crate::write_buffer::{WriteBuffer, WriteBufferBorrowMut};
use embedded_io::Error as _;
use embedded_io::{BufRead, ErrorType, Read, Write};
use portable_atomic::AtomicBool;
pub use crate::TlsError;
pub use crate::config::*;
/// Type representing a TLS connection. An instance of this type can
/// be used to establish a TLS connection, write and read encrypted data over this connection,
/// and closing to free up the underlying resources.
pub struct TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
delegate: Socket,
opened: AtomicBool,
key_schedule: KeySchedule<CipherSuite>,
record_reader: RecordReader<'a>,
record_write_buf: WriteBuffer<'a>,
decrypted: DecryptedBufferInfo,
}
impl<'a, Socket, CipherSuite> TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn is_opened(&mut self) -> bool {
*self.opened.get_mut()
}
/// Create a new TLS connection with the provided context and a blocking I/O implementation
///
/// NOTE: The record read buffer should be sized to fit an encrypted TLS record. The size of this record
/// depends on the server configuration, but the maximum allowed value for a TLS record is 16640 bytes,
/// which should be a safe value to use.
///
/// The write record buffer can be smaller than the read buffer. During writes [`TLS_RECORD_OVERHEAD`] bytes of
/// overhead is added per record, so the buffer must at least be this large. Large writes are split into multiple
/// records if depending on the size of the write buffer.
/// The largest of the two buffers will be used to encode the TLS handshake record, hence either of the
/// buffers must at least be large enough to encode a handshake.
pub fn new(
delegate: Socket,
record_read_buf: &'a mut [u8],
record_write_buf: &'a mut [u8],
) -> Self {
Self {
delegate,
opened: AtomicBool::new(false),
key_schedule: KeySchedule::new(),
record_reader: RecordReader::new(record_read_buf),
record_write_buf: WriteBuffer::new(record_write_buf),
decrypted: DecryptedBufferInfo::default(),
}
}
/// Open a TLS connection, performing the handshake with the configuration provided when
/// creating the connection instance.
///
/// Returns an error if the handshake does not proceed. If an error occurs, the connection
/// instance must be recreated.
pub fn open<Provider>(&mut self, mut context: TlsContext<Provider>) -> Result<(), TlsError>
where
Provider: CryptoProvider<CipherSuite = CipherSuite>,
{
let mut handshake: Handshake<CipherSuite> = Handshake::new();
if let (Ok(verifier), Some(server_name)) = (
context.crypto_provider.verifier(),
context.config.server_name,
) {
verifier.set_hostname_verification(server_name)?;
}
let mut state = State::ClientHello;
while state != State::ApplicationData {
let next_state = state.process_blocking(
&mut self.delegate,
&mut handshake,
&mut self.record_reader,
&mut self.record_write_buf,
&mut self.key_schedule,
context.config,
&mut context.crypto_provider,
)?;
trace!("State {:?} -> {:?}", state, next_state);
state = next_state;
}
*self.opened.get_mut() = true;
Ok(())
}
/// Encrypt and send the provided slice over the connection. The connection
/// must be opened before writing.
///
/// The slice may be buffered internally and not written to the connection immediately.
/// In this case [`Self::flush()`] should be called to force the currently buffered writes
/// to be written to the connection.
///
/// Returns the number of bytes buffered/written.
pub fn write(&mut self, buf: &[u8]) -> Result<usize, TlsError> {
if self.is_opened() {
if !self
.record_write_buf
.contains(ClientRecordHeader::ApplicationData)
{
self.flush()?;
self.record_write_buf
.start_record(ClientRecordHeader::ApplicationData)?;
}
let buffered = self.record_write_buf.append(buf);
if self.record_write_buf.is_full() {
self.flush()?;
}
Ok(buffered)
} else {
Err(TlsError::MissingHandshake)
}
}
/// Force all previously written, buffered bytes to be encoded into a tls record and written
/// to the connection.
pub fn flush(&mut self) -> Result<(), TlsError> {
if !self.record_write_buf.is_empty() {
let key_schedule = self.key_schedule.write_state();
let slice = self.record_write_buf.close_record(key_schedule)?;
self.delegate
.write_all(slice)
.map_err(|e| TlsError::Io(e.kind()))?;
key_schedule.increment_counter();
self.delegate.flush().map_err(|e| TlsError::Io(e.kind()))?;
}
Ok(())
}
fn create_read_buffer(&mut self) -> ReadBuffer {
self.decrypted.create_read_buffer(self.record_reader.buf)
}
/// Read and decrypt data filling the provided slice.
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, TlsError> {
if buf.is_empty() {
return Ok(0);
}
let mut buffer = self.read_buffered()?;
let len = buffer.pop_into(buf);
trace!("Copied {} bytes", len);
Ok(len)
}
/// Reads buffered data. If nothing is in memory, it'll wait for a TLS record and process it.
pub fn read_buffered(&mut self) -> Result<ReadBuffer, TlsError> {
if self.is_opened() {
while self.decrypted.is_empty() {
self.read_application_data()?;
}
Ok(self.create_read_buffer())
} else {
Err(TlsError::MissingHandshake)
}
}
fn read_application_data(&mut self) -> Result<(), TlsError> {
let buf_ptr_range = self.record_reader.buf.as_ptr_range();
let key_schedule = self.key_schedule.read_state();
let record = self
.record_reader
.read_blocking(&mut self.delegate, key_schedule)?;
let mut handler = DecryptedReadHandler {
source_buffer: buf_ptr_range,
buffer_info: &mut self.decrypted,
is_open: self.opened.get_mut(),
};
decrypt_record(key_schedule, record, |_key_schedule, record| {
handler.handle(record)
})?;
Ok(())
}
fn close_internal(&mut self) -> Result<(), TlsError> {
self.flush()?;
let is_opened = self.is_opened();
let (write_key_schedule, read_key_schedule) = self.key_schedule.as_split();
let slice = self.record_write_buf.write_record(
&ClientRecord::close_notify(is_opened),
write_key_schedule,
Some(read_key_schedule),
)?;
self.delegate
.write_all(slice)
.map_err(|e| TlsError::Io(e.kind()))?;
self.key_schedule.write_state().increment_counter();
self.flush()?;
Ok(())
}
/// Close a connection instance, returning the ownership of the I/O provider.
pub fn close(mut self) -> Result<Socket, (Socket, TlsError)> {
match self.close_internal() {
Ok(()) => Ok(self.delegate),
Err(e) => Err((self.delegate, e)),
}
}
pub fn split(
&mut self,
) -> (
TlsReader<'_, Socket, CipherSuite>,
TlsWriter<'_, Socket, CipherSuite>,
)
where
Socket: Clone,
{
let (wks, rks) = self.key_schedule.as_split();
let reader = TlsReader {
opened: &self.opened,
delegate: self.delegate.clone(),
key_schedule: rks,
record_reader: self.record_reader.reborrow_mut(),
decrypted: &mut self.decrypted,
};
let writer = TlsWriter {
opened: &self.opened,
delegate: self.delegate.clone(),
key_schedule: wks,
record_write_buf: self.record_write_buf.reborrow_mut(),
};
(reader, writer)
}
}
impl<'a, Socket, CipherSuite> ErrorType for TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
type Error = TlsError;
}
impl<'a, Socket, CipherSuite> Read for TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
TlsConnection::read(self, buf)
}
}
impl<'a, Socket, CipherSuite> BufRead for TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
self.read_buffered().map(|mut buf| buf.peek_all())
}
fn consume(&mut self, amt: usize) {
self.create_read_buffer().pop(amt);
}
}
impl<'a, Socket, CipherSuite> Write for TlsConnection<'a, Socket, CipherSuite>
where
Socket: Read + Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
TlsConnection::write(self, buf)
}
fn flush(&mut self) -> Result<(), Self::Error> {
TlsConnection::flush(self)
}
}
pub struct TlsReader<'a, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
opened: &'a AtomicBool,
delegate: Socket,
key_schedule: &'a mut ReadKeySchedule<CipherSuite>,
record_reader: RecordReaderBorrowMut<'a>,
decrypted: &'a mut DecryptedBufferInfo,
}
impl<Socket, CipherSuite> AsRef<Socket> for TlsReader<'_, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
fn as_ref(&self) -> &Socket {
&self.delegate
}
}
impl<'a, Socket, CipherSuite> TlsReader<'a, Socket, CipherSuite>
where
Socket: Read + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn create_read_buffer(&mut self) -> ReadBuffer {
self.decrypted.create_read_buffer(self.record_reader.buf)
}
/// Reads buffered data. If nothing is in memory, it'll wait for a TLS record and process it.
pub fn read_buffered(&mut self) -> Result<ReadBuffer, TlsError> {
if self.opened.load(Ordering::Acquire) {
while self.decrypted.is_empty() {
self.read_application_data()?;
}
Ok(self.create_read_buffer())
} else {
Err(TlsError::MissingHandshake)
}
}
fn read_application_data(&mut self) -> Result<(), TlsError> {
let buf_ptr_range = self.record_reader.buf.as_ptr_range();
let record = self
.record_reader
.read_blocking(&mut self.delegate, self.key_schedule)?;
let mut opened = self.opened.load(Ordering::Acquire);
let mut handler = DecryptedReadHandler {
source_buffer: buf_ptr_range,
buffer_info: self.decrypted,
is_open: &mut opened,
};
let result = decrypt_record(self.key_schedule, record, |_key_schedule, record| {
handler.handle(record)
});
if !opened {
self.opened.store(false, Ordering::Release);
}
result
}
}
pub struct TlsWriter<'a, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
opened: &'a AtomicBool,
delegate: Socket,
key_schedule: &'a mut WriteKeySchedule<CipherSuite>,
record_write_buf: WriteBufferBorrowMut<'a>,
}
impl<Socket, CipherSuite> AsRef<Socket> for TlsWriter<'_, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
fn as_ref(&self) -> &Socket {
&self.delegate
}
}
impl<Socket, CipherSuite> ErrorType for TlsWriter<'_, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
type Error = TlsError;
}
impl<Socket, CipherSuite> ErrorType for TlsReader<'_, Socket, CipherSuite>
where
CipherSuite: TlsCipherSuite + 'static,
{
type Error = TlsError;
}
impl<'a, Socket, CipherSuite> Read for TlsReader<'a, Socket, CipherSuite>
where
Socket: Read + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
if buf.is_empty() {
return Ok(0);
}
let mut buffer = self.read_buffered()?;
let len = buffer.pop_into(buf);
trace!("Copied {} bytes", len);
Ok(len)
}
}
impl<'a, Socket, CipherSuite> BufRead for TlsReader<'a, Socket, CipherSuite>
where
Socket: Read + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
self.read_buffered().map(|mut buf| buf.peek_all())
}
fn consume(&mut self, amt: usize) {
self.create_read_buffer().pop(amt);
}
}
impl<'a, Socket, CipherSuite> Write for TlsWriter<'a, Socket, CipherSuite>
where
Socket: Write + 'a,
CipherSuite: TlsCipherSuite + 'static,
{
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
if self.opened.load(Ordering::Acquire) {
if !self
.record_write_buf
.contains(ClientRecordHeader::ApplicationData)
{
self.flush()?;
self.record_write_buf
.start_record(ClientRecordHeader::ApplicationData)?;
}
let buffered = self.record_write_buf.append(buf);
if self.record_write_buf.is_full() {
self.flush()?;
}
Ok(buffered)
} else {
Err(TlsError::MissingHandshake)
}
}
fn flush(&mut self) -> Result<(), Self::Error> {
if !self.record_write_buf.is_empty() {
let slice = self.record_write_buf.close_record(self.key_schedule)?;
self.delegate
.write_all(slice)
.map_err(|e| TlsError::Io(e.kind()))?;
self.key_schedule.increment_counter();
self.delegate.flush().map_err(|e| TlsError::Io(e.kind()))?;
}
Ok(())
}
}