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
extern crate hex;
extern crate byteorder;
extern crate rust_sodium;
pub mod auth_failure;
pub mod cryptography;
pub mod passwords;
pub mod keys;
pub mod handshake_packet;
pub mod session;
pub mod authentication;
pub mod handshake;
pub mod connection;
pub mod connection_state;
pub use keys::{FromBase32, FromHex, publickey_to_ipv6addr};
use std::collections::HashMap;
use byteorder::{ByteOrder, BigEndian};
use passwords::PasswordStore;
use session::{Session, SessionState};
use handshake_packet::{HandshakePacket, HandshakePacketType};
pub use authentication::Credentials;
pub use auth_failure::AuthFailure;
pub use cryptography::{PublicKey, SecretKey, gen_keypair};
pub use connection_state::ConnectionState;
pub fn init() {
rust_sodium::init();
}
pub struct CAWrapper<PeerId: Clone> {
my_credentials: Credentials,
password_store: Option<PasswordStore<PeerId>>,
peer_id: Option<PeerId>,
my_session_handle: Option<u32>,
peer_session_handle: Option<u32>,
session: Session,
}
impl<PeerId: Clone> CAWrapper<PeerId> {
pub fn new_outgoing_connection(
my_pk: PublicKey, my_sk: SecretKey,
their_pk: PublicKey,
my_credentials: Credentials,
allowed_peers: Option<HashMap<Credentials, PeerId>>,
peer_id: PeerId,
session_handle: Option<u32>,
) -> CAWrapper<PeerId> {
let password_store = allowed_peers.map(PasswordStore::from);
CAWrapper {
my_credentials: my_credentials,
password_store: password_store,
peer_id: Some(peer_id),
my_session_handle: session_handle,
peer_session_handle: None,
session: Session::new(my_pk, my_sk, their_pk, SessionState::UninitializedKnownPeer),
}
}
fn parse_hello(session: &mut Session, password_store: &Option<PasswordStore<PeerId>>, packet: &HandshakePacket) -> Result<(Option<PeerId>, Vec<u8>), AuthFailure> {
match *password_store {
Some(ref password_store) => {
let (peer_id, data) = try!(handshake::parse_hello_packet(session, password_store, &packet));
Ok((Some(peer_id.clone()), data))
},
None => Ok((None, try!(handshake::parse_authnone_hello_packet(session, &packet)))),
}
}
pub fn new_incoming_connection(
my_pk: PublicKey, my_sk: SecretKey,
my_credentials: Credentials,
allowed_peers: Option<HashMap<Credentials, PeerId>>,
session_handle: Option<u32>,
packet: Vec<u8>,
) -> Result<(CAWrapper<PeerId>, Vec<u8>), AuthFailure> {
let packet = HandshakePacket { raw: packet };
match packet.packet_type() {
Ok(HandshakePacketType::Hello) | Ok(HandshakePacketType::RepeatHello) => (),
_ => return Err(AuthFailure::UnexpectedPacket(format!("Incoming connection started with a non-Hello packet ({:?}).", packet.packet_type()))),
}
let password_store = allowed_peers.map(PasswordStore::from);
let their_pk = match handshake::pre_parse_hello_packet(&packet) {
Some(their_pk) => their_pk,
None => panic!("pre_parse_hello_packet should not return None on Hello packets.'"),
};
let mut session = Session::new(
my_pk, my_sk, their_pk, SessionState::UninitializedUnknownPeer);
let (peer_id, content) = try!(CAWrapper::parse_hello(&mut session, &password_store, &packet));
let mut wrapper = CAWrapper {
my_credentials: my_credentials,
password_store: password_store,
peer_id: peer_id,
my_session_handle: session_handle,
peer_session_handle: None,
session: session,
};
let (handle, new_content) = wrapper.extract_session_handle(content);
wrapper.peer_session_handle = handle;
Ok((wrapper, new_content))
}
pub fn wrap_message(&mut self, msg: &[u8]) -> Vec<Vec<u8>> {
let mut packets = self.upkeep();
match self.session.state {
SessionState::Established { ref shared_secret_key, ref initiator_is_me, .. } => {
packets.push(connection::seal_message(
&mut self.session.my_last_nonce, shared_secret_key, *initiator_is_me, msg))
}
_ => {}
};
if self.session.my_last_nonce >= 0xfffffff0 {
self.session.reset();
packets.append(&mut self.upkeep());
}
packets
}
fn prefix_session_handle(&self, msg: &[u8]) -> Vec<u8> {
match self.my_session_handle {
None => msg.to_vec(),
Some(handle) => {
let mut final_msg = vec![0; msg.len()+4];
BigEndian::write_u32(&mut final_msg[0..4], handle);
final_msg[4..].copy_from_slice(msg);
final_msg
},
}
}
pub fn wrap_message_immediately(&mut self, msg: &[u8]) -> Vec<Vec<u8>> {
let mut packets = Vec::new();
match self.session.state {
SessionState::UninitializedUnknownPeer => {
panic!("A CAWrapper's Session state should never be UninitializedUnknownPeer.")
},
SessionState::UninitializedKnownPeer |
SessionState::SentHello { .. } |
SessionState::ReceivedHello { .. } |
SessionState::WaitingKey { .. } |
SessionState::SentKey { .. } => {
let final_msg = self.prefix_session_handle(msg);
if let Some(packet) = handshake::create_next_handshake_packet(&mut self.session, &self.my_credentials, &final_msg) {
packets.push(packet.raw);
}
},
SessionState::Established { ref shared_secret_key, ref initiator_is_me, .. } => {
packets.push(connection::seal_message(
&mut self.session.my_last_nonce, &shared_secret_key, *initiator_is_me, msg))
},
};
if self.session.my_last_nonce >= 0xfffffff0 {
self.session.reset();
packets.append(&mut self.upkeep());
}
packets
}
fn extract_session_handle(&self, content: Vec<u8>) -> (Option<u32>, Vec<u8>) {
match self.my_session_handle {
Some(_) => {
let handle = Some(BigEndian::read_u32(&content[0..4]));
let new_content = content[4..].to_vec();
(handle, new_content)
}
None => (None, content)
}
}
fn unwrap_data_packet(&mut self, packet_first_four_bytes: u32, packet: Vec<u8>) -> Result<Vec<Vec<u8>>, AuthFailure> {
handshake::finalize(&mut self.session);
match self.session.state {
SessionState::UninitializedUnknownPeer |
SessionState::UninitializedKnownPeer |
SessionState::SentHello { .. } |
SessionState::WaitingKey { .. } |
SessionState::ReceivedHello { .. } => {
if packet_first_four_bytes == 0 {
Err(AuthFailure::PacketTooShort(format!("Size: {}, but I am in state {:?}", packet.len(), self.session.state)))
}
else {
Err(AuthFailure::UnexpectedPacket(format!("Received a non-handshake packet while doing handshake (first four bytes: {:?}u32)", packet_first_four_bytes)))
}
},
SessionState::SentKey { ref shared_secret_key, .. } => {
let content = try!(connection::open_packet(
&mut self.session.their_nonce_offset,
&mut self.session.their_nonce_bitfield,
&shared_secret_key,
false,
&packet));
let (handle, new_content) = self.extract_session_handle(content);
self.peer_session_handle = handle;
Ok(vec![new_content])
},
SessionState::Established { ref shared_secret_key, ref initiator_is_me, .. } => {
Ok(vec![try!(connection::open_packet(
&mut self.session.their_nonce_offset,
&mut self.session.their_nonce_bitfield,
&shared_secret_key,
*initiator_is_me,
&packet))])
},
}
}
pub fn unwrap_hello_packet(&mut self, packet: Vec<u8>) -> Result<Vec<Vec<u8>>, AuthFailure> {
let (peer_id, content) = try!(CAWrapper::parse_hello(
&mut self.session, &self.password_store, &HandshakePacket { raw: packet }));
let (handle, new_content) = self.extract_session_handle(content);
self.peer_session_handle = handle;
self.peer_id = peer_id.clone();
if new_content.len() == 0 {
Ok(Vec::new())
}
else {
Ok(vec![new_content])
}
}
pub fn unwrap_key_packet(&mut self, packet: Vec<u8>) -> Result<Vec<Vec<u8>>, AuthFailure> {
match self.session.state.clone() {
SessionState::UninitializedUnknownPeer |
SessionState::UninitializedKnownPeer |
SessionState::ReceivedHello { .. } => {
Err(AuthFailure::UnexpectedPacket("Received a key packet while expecting a hello.".to_owned()))
},
SessionState::SentKey { .. } |
SessionState::Established { .. } => {
Err(AuthFailure::UnexpectedPacket("Received a key packet while expecting a data packet.".to_owned()))
},
SessionState::WaitingKey { .. } |
SessionState::SentHello { .. } => {
let content = try!(handshake::parse_key_packet(
&mut self.session, &HandshakePacket { raw: packet }));
let (handle, new_content) = self.extract_session_handle(content);
self.peer_session_handle = handle;
if new_content.len() == 0 {
Ok(Vec::new())
}
else {
Ok(vec![new_content])
}
},
}
}
pub fn unwrap_message(&mut self, packet: Vec<u8>) -> Result<Vec<Vec<u8>>, AuthFailure> {
let (packet, packet_type) = if packet.len() < 120 {
(packet, Err(0))
}
else {
let handshake_packet = HandshakePacket { raw: packet };
let packet_type = handshake_packet.packet_type();
let packet = handshake_packet.raw;
(packet, packet_type)
};
match packet_type {
Err(packet_first_four_bytes) => {
self.unwrap_data_packet(packet_first_four_bytes, packet)
},
Ok(HandshakePacketType::Hello) | Ok(HandshakePacketType::RepeatHello) => {
self.unwrap_hello_packet(packet)
}
Ok(HandshakePacketType::Key) | Ok(HandshakePacketType::RepeatKey) => {
self.unwrap_key_packet(packet)
},
}
}
pub fn upkeep(&mut self) -> Vec<Vec<u8>> {
match self.session.state {
SessionState::UninitializedUnknownPeer => {
panic!("A CAWrapper's Session state should never be UninitializedUnknownPeer.")
},
SessionState::UninitializedKnownPeer |
SessionState::SentHello { .. } |
SessionState::WaitingKey { .. } |
SessionState::ReceivedHello { .. } |
SessionState::SentKey { .. } => {
let msg = self.prefix_session_handle(&vec![]);
if let Some(packet) = handshake::create_next_handshake_packet(&mut self.session, &self.my_credentials, &msg) {
vec![packet.raw]
}
else {
vec![]
}
},
SessionState::Established { .. } => {
vec![]
},
}
}
pub fn connection_state(&self) -> ConnectionState {
ConnectionState::from(&self.session.state)
}
pub fn their_pk(&self) -> &PublicKey {
&self.session.their_perm_pk
}
pub fn peer_id(&self) -> &Option<PeerId> {
&self.peer_id
}
pub fn peer_session_handle(&self) -> Option<u32> {
self.peer_session_handle.clone()
}
}