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;



/// Initializes fcp_cryptoauth. Must be called before any
/// feature is used.
///
/// Actually, its only purpose is to initialize the cryptographic
/// library.
pub fn init() {
    rust_sodium::init();
}

/// Main wrapper class around a connection.
/// Provides methods to encrypt and decrypt messages.
///
/// This structure does not store arbitrary-sized messages from the
/// network, only arrays whose size is statically known.
/// This means that it cannot be used by network attackers to
/// make it use all the memory on the system.
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> {
    /// Creates a new `CAWrapper` for a connection initiated by us.
    ///
    /// `my_credentials` is the login/password used to authenticate
    /// to the other peer.
    ///
    /// `allowed_peers` has the same function as for
    /// `new_incoming_connection` and may be used if the other peer resets
    /// the connection.
    /// If set to None, no authentication will be required for incoming
    /// peers.
    ///
    /// `peer_id` is an arbitrary value opaque to `fcp_cryptoauth`,
    /// used by the calling library to identify the peer.
    /// It does not have to be unique (even `()` works).
    /// It won't be sent over the network by `fcp_cryptoauth`.
    ///
    /// `session_handle`, if provided, is an integer that will be sent in
    /// the CA handshake packets to ask the peer to use is as a *prefix*
    /// to future CA packets.
    /// If provided, a `session_handle` will also be expected from the other
    /// peer, and available as `peer_session_handle`.
    /// In the FCP, this is used for all inner (end-to-end) CA sessions,
    /// and never for outer (point-to-point) sessions.
    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)))),
        }
    }


    /// Creates a new `CAWrapper` for a connection initiated by the peer.
    ///
    /// `my_credentials` is the login/password used to authenticate
    /// back to the peer, if we have to reset the connection.
    ///
    /// `allowed_peers` is a set of credentials the peer is allowed
    /// to use to identicate.
    /// Once a peer used one of these credentials, the associated value
    /// is used as its peer id so we know who this is.
    /// If set to None, no authentication will be required for incoming
    /// peers.
    ///
    /// `session_handle` is the same as for `new_outgoing_connection`.
    ///
    /// Returns `Err` if and only if the message is not a well-formed
    /// Hello packet or the peer is not in the `allowed_peers`.
    /// Otherwise, returns `Ok((wrapper, piggybacked_message))`.
    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))
    }

    /// Takes an unencrypted message and returns one (eventually more
    /// or zero) encrypted packet containing this message
    /// (eventually CryptoAuth-specific packets).
    ///
    /// Returns packets that should be sent.
    ///
    /// The encryption used by this method is guaranteed to be
    /// forward secret; if forward secrecy is not yet available for
    /// the current connection, messages will be dropped until it is.
    ///
    /// If you need neither forward secrecy or protection against the data
    /// being replayed and want to send a message as fast as possible,
    /// use `wrap_message_immediately`
    /// (for now, the only difference is for the calls to
    /// to `wrap_message` / `wrap_message_immediately` made before
    /// the handshake is finished).
    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))

            }
            _ => {} // forward-secrecy not yet available.
        };
        if self.session.my_last_nonce >= 0xfffffff0 {
            // Little nonce space left
            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(), // TODO: do not copy
            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); // TODO: do not copy
                final_msg
            },
        }
    }

    /// Similar to `wrap_message`, but tries to send the message
    /// faster, but does not guarantee forward secrecy
    /// of the message, and the content may be replayed by anyone.
    ///
    /// For now, the behavior of `wrap_message` and
    /// `wrap_message_immediately` only differs on the first wrapped
    /// message: a wrapped message is not forward secret if and only if
    /// it is passed to the first call of `wrap_message_immediately`
    /// of the session and `wrap_message` has never been called before.
    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 {
            // Little nonce space left
            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(_) => {
                // It is an inner CA session, we have to extract the
                // session handle
                let handle = Some(BigEndian::read_u32(&content[0..4]));
                let new_content = content[4..].to_vec(); // TODO: do not copy
                (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, .. } => {
                // TODO: factorize with Established
                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() { // TODO: do not 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])
                }
            },
        }
    }

    /// Takes an encrypted packet and returns one (eventually more or
    /// zero) decrypted message, which should be considered as incoming
    /// messages.
    ///
    /// A decrypted message can be trusted as coming from the
    /// associated peer (packets which cannot be authenticated are not
    /// decrypted).
    ///
    /// The argument must be a full CryptoAuth packet. On UDP, this
    /// means that the argument must be the *full* content of *one*
    /// UDP datagram.
    ///
    /// For now, there is no case where this returns more than
    /// one message.
    ///
    /// Errors (authentication failures) may be unwrapped without
    /// further action safely. However, it would be a good style to log
    /// them in your application's DEBUG logs.
    pub fn unwrap_message(&mut self, packet: Vec<u8>) -> Result<Vec<Vec<u8>>, AuthFailure> {
        let (packet, packet_type) = if packet.len() < 120 {
            // Cannot be a handshake packet
            // This case disjunction is useless in theory, but it
            // avoids having a temporary HandshakePacket object
            // that is broken (eg. panics if printed)
            (packet, Err(0))
        }
        else {
            // May be a handshake packet
            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) => {
                // Not a handshake packet
                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)
            },
        }
    }

    /// Passes control to the wrapper so it can perform internal
    /// maintainance, eg. repeat packets that have not been responded
    /// to.
    ///
    /// Returns packets that should be sent to the other peer.
    ///
    /// This function should be called from time to time if no message
    /// was wrapped or unwrapped.
    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![]
            },
        }
    }

    /// Returns the state of the connection.
    pub fn connection_state(&self) -> ConnectionState {
        ConnectionState::from(&self.session.state)
    }

    /// Returns the public key of the other peer.
    pub fn their_pk(&self) -> &PublicKey {
        &self.session.their_perm_pk
    }

    /// Returns the peer id of the other peer.
    pub fn peer_id(&self) -> &Option<PeerId> {
        &self.peer_id
    }

    /// Returns the peer id of the other peer.
    pub fn peer_session_handle(&self) -> Option<u32> {
        self.peer_session_handle.clone()
    }
}