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
use std::io::{Read, ErrorKind};
use std::{io, cmp, mem, u16, ptr};
use sodiumoxide::crypto::secretbox;
use crypto::{CYPHER_HEADER_SIZE, MAX_PACKET_SIZE, MAX_PACKET_USIZE, PlainHeader,
decrypt_header_inplace, decrypt_packet_inplace};
const READ_BUFFER_SIZE: usize = CYPHER_HEADER_SIZE + MAX_PACKET_USIZE;
pub const FINAL_ERROR: &'static str = "final";
pub const INVALID_LENGTH: &'static str = "length";
pub const UNAUTHENTICATED_HEADER: &'static str = "header_auth";
pub const UNAUTHENTICATED_PACKET: &'static str = "packet_auth";
pub struct ReaderBuffer {
buffer: [u8; READ_BUFFER_SIZE],
last: u16,
offset: u16,
header_index: u16,
mode: ReaderBufferMode,
err: BufErr,
}
#[derive(PartialEq, Debug)]
enum ReaderBufferMode {
WaitingForHeader,
WaitingForPacket,
Readable,
}
use self::ReaderBufferMode::*;
#[derive(PartialEq)]
enum BufErr {
None,
InvalidLength,
FinalHeader,
UnauthenticatedHeader,
UnauthenticatedPacket,
}
impl ReaderBufferMode {
fn is_waiting(&self) -> bool {
match *self {
Readable => false,
_ => true,
}
}
}
impl ReaderBuffer {
pub fn new() -> ReaderBuffer {
ReaderBuffer {
buffer: [0; CYPHER_HEADER_SIZE + MAX_PACKET_USIZE],
last: 0,
offset: 0,
header_index: 0,
mode: WaitingForHeader,
err: BufErr::None,
}
}
fn decrypt_header_at(&mut self,
key: &secretbox::Key,
nonce: &mut secretbox::Nonce,
header_index: u16)
-> bool {
unsafe {
decrypt_header_inplace(&mut *(self.buffer.as_mut_ptr().offset(header_index as isize) as
*mut [u8; CYPHER_HEADER_SIZE]),
&key.0,
&mut nonce.0)
}
}
fn plain_header_at(&self, header_index: u16) -> PlainHeader {
unsafe {
mem::transmute::<[u8;
secretbox::MACBYTES + 2],
PlainHeader>(*(self.buffer.as_ptr().offset(header_index as isize) as
*const [u8; secretbox::MACBYTES + 2]))
}
}
fn cypher_packet_len_at(&mut self, header_index: u16) -> u16 {
self.plain_header_at(header_index).get_packet_len()
}
fn shift_left(&mut self, offset: u16) {
unsafe {
ptr::copy(self.buffer.as_ptr().offset(offset as isize),
self.buffer.as_mut_ptr(),
(self.last - offset) as usize);
}
self.last -= offset;
self.offset = CYPHER_HEADER_SIZE as u16;
self.header_index = 0;
}
fn decrypt_packet_at(&mut self,
key: &secretbox::Key,
nonce: &mut secretbox::Nonce,
header_index: u16)
-> bool {
let plain_header = self.plain_header_at(header_index);
let packet_len = plain_header.get_packet_len();
debug_assert!(packet_len <= MAX_PACKET_SIZE);
unsafe {
if !decrypt_packet_inplace(self.buffer
.as_mut_ptr()
.offset(header_index as isize +
CYPHER_HEADER_SIZE as isize),
&plain_header,
&key.0,
&mut nonce.0) {
return false;
}
}
self.offset = CYPHER_HEADER_SIZE as u16;
self.header_index = header_index;
self.mode = Readable;
true
}
fn set_err(&mut self, e: BufErr) -> io::Error {
let ret = make_io_error(&e);
self.err = e;
ret
}
pub fn read_to(&mut self,
out: &mut [u8],
key: &secretbox::Key,
nonce: &mut secretbox::Nonce)
-> usize {
debug_assert!(self.mode == Readable);
let tmp = self.header_index;
let packet_len = self.cypher_packet_len_at(tmp);
let remaining_plaintext = self.header_index + CYPHER_HEADER_SIZE as u16 + packet_len -
self.offset;
let max_readable = cmp::min(out.len() as u16, remaining_plaintext);
unsafe {
ptr::copy_nonoverlapping(self.buffer.as_ptr().offset(self.offset as isize),
out.as_mut_ptr(),
max_readable as usize);
}
let offset = self.offset + max_readable;
if (out.len() as u16) < remaining_plaintext {
self.offset = offset;
return max_readable as usize;
} else {
if self.last < offset + CYPHER_HEADER_SIZE as u16 {
self.mode = WaitingForHeader;
} else {
if !self.decrypt_header_at(key, nonce, offset) {
self.set_err(BufErr::UnauthenticatedHeader);
return max_readable as usize;
}
let plain_header = self.plain_header_at(offset);
if plain_header.is_final_header() {
self.set_err(BufErr::FinalHeader);
return max_readable as usize;
}
let cypher_packet_len = self.cypher_packet_len_at(offset);
if cypher_packet_len > MAX_PACKET_SIZE {
self.set_err(BufErr::InvalidLength);
return max_readable as usize;
}
if cypher_packet_len + offset + (CYPHER_HEADER_SIZE as u16) > self.last {
self.mode = WaitingForPacket;
} else {
if !self.decrypt_packet_at(key, nonce, offset) {
self.set_err(BufErr::UnauthenticatedPacket);
return max_readable as usize;
}
}
}
self.shift_left(offset);
return max_readable as usize;
}
}
pub fn fill<R: Read>(&mut self,
reader: &mut R,
key: &secretbox::Key,
nonce: &mut secretbox::Nonce)
-> io::Result<bool> {
debug_assert!(self.mode == WaitingForHeader || self.mode == WaitingForPacket);
let read = reader.read(&mut self.buffer[self.last as usize..])?;
if read == 0 {
return Ok(true);
}
self.last += read as u16;
if self.last < CYPHER_HEADER_SIZE as u16 {
debug_assert!(self.mode == WaitingForHeader);
return Ok(false);
} else {
if self.mode == WaitingForHeader {
if !self.decrypt_header_at(key, nonce, 0) {
return Err(self.set_err(BufErr::UnauthenticatedHeader));
}
}
let plain_header = self.plain_header_at(0);
if plain_header.is_final_header() {
return Err(self.set_err(BufErr::FinalHeader));
}
let cypher_packet_len = self.cypher_packet_len_at(0);
if cypher_packet_len > MAX_PACKET_SIZE {
return Err(self.set_err(BufErr::InvalidLength));
}
if self.last < CYPHER_HEADER_SIZE as u16 + cypher_packet_len {
self.mode = WaitingForPacket;
return Ok(false);
} else {
if !self.decrypt_packet_at(key, nonce, 0) {
return Err(self.set_err(BufErr::UnauthenticatedPacket));
}
return Ok(false);
}
}
}
}
pub fn do_read<R: Read>(out: &mut [u8],
reader: &mut R,
key: &secretbox::Key,
nonce: &mut secretbox::Nonce,
buffer: &mut ReaderBuffer)
-> io::Result<usize> {
match buffer.err {
BufErr::None => {
let mut total_read = 0;
if buffer.mode.is_waiting() {
if buffer.fill(reader, key, nonce)? {
return Ok(0);
}
}
while let Readable = buffer.mode {
if buffer.err != BufErr::None {
break;
}
if total_read >= out.len() {
break;
}
total_read += buffer.read_to(&mut out[total_read..], key, nonce);
}
if total_read == 0 {
Err(io::Error::new(ErrorKind::WouldBlock, "need_data"))
} else {
Ok(total_read)
}
}
_ => Err(make_io_error(&buffer.err)),
}
}
fn make_io_error(e: &BufErr) -> io::Error {
match e {
&BufErr::FinalHeader => io::Error::new(ErrorKind::Other, FINAL_ERROR),
&BufErr::InvalidLength => io::Error::new(ErrorKind::InvalidData, INVALID_LENGTH),
&BufErr::UnauthenticatedHeader => {
io::Error::new(ErrorKind::InvalidData, UNAUTHENTICATED_HEADER)
}
&BufErr::UnauthenticatedPacket => {
io::Error::new(ErrorKind::InvalidData, UNAUTHENTICATED_PACKET)
}
&BufErr::None => {
unreachable!();
}
}
}