fcp_cryptoauth 0.4.0

Implementation of the Futuristic Connectivity Protocol's CryptoAuth layer (cryptographic authentication and encryption over unreliable channels).
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Creates and reads CryptoAuth Hello packets
use auth_failure::AuthFailure;
use authentication::{Credentials, ToAuthChallenge};
use cryptography::crypto_box::{Nonce, PrecomputedKey, PublicKey};
use cryptography::{
    crypto_box, open_packet_end, shared_secret_from_keys, shared_secret_from_password,
};
use handshake_packet::{HandshakePacket, HandshakePacketBuilder, HandshakePacketType};
use passwords::PasswordStore;
use session::{Session, SessionState};

/// Implements Hello packet creation, as defined by
/// https://github.com/fc00/spec/blob/10b349ab11/cryptoauth.md#hello-repeathello
///
/// # Examples
///
/// ```
/// use fcp_cryptoauth::cryptography::crypto_box::{gen_keypair, PublicKey};
/// use fcp_cryptoauth::authentication::Credentials;
/// use fcp_cryptoauth::session::{Session, SessionState};
/// use fcp_cryptoauth::keys::FromBase32;
/// use fcp_cryptoauth::handshake::create_next_handshake_packet;
///
/// let (my_pk, my_sk) = gen_keypair();
/// let their_pk = PublicKey::from_base32(b"2j1xz5k5y1xwz7kcczc4565jurhp8bbz1lqfu9kljw36p3nmb050.k").unwrap();
/// // Corresponding secret key: 824736a667d85582747fde7184201b17d0e655a7a3d9e0e3e617e7ca33270da8
/// let mut session = Session::new(my_pk, my_sk, their_pk, SessionState::UninitializedKnownPeer);
///
/// let login = "foo".to_owned().into_bytes();
/// let password = "bar".to_owned().into_bytes();
/// let challenge = Credentials::LoginPassword { login: login, password: password };
///
/// let hello = create_next_handshake_packet(&mut session, &challenge, &vec![]).unwrap();
/// let bytes = hello.raw;
/// ```
pub fn create_next_handshake_packet(
    session: &mut Session,
    challenge: &Credentials,
    data: &[u8],
) -> Option<HandshakePacket> {
    match session.state.clone() { // TODO: do not clone
        SessionState::UninitializedUnknownPeer => {
            panic!("Trying to send a packet to a totally unknown peer. We need at least a Challenge or a PasswordStore to do that.")
        },
        SessionState::UninitializedKnownPeer => {
            // If we have not sent or received anything yet, send Hello
            // and set the state to SentHello.
            let nonce = crypto_box::gen_nonce();
            let shared_secret_key = shared_secret_from_keys(
                        &session.my_temp_sk, &session.their_perm_pk);
            session.state = SessionState::SentHello {
                shared_secret_key: shared_secret_key,
                };
            Some(create_hello(session, &nonce, &challenge, false, data))
        },
        SessionState::SentHello { .. } => {
            // If we already sent Hello but nothing else, and not received
            // anything, repeat the Hello and keep the state unchanged.
            let nonce = crypto_box::gen_nonce();
            Some(create_hello(session, &nonce, &challenge, true, data))
        },
        SessionState::ReceivedHello { their_temp_pk, shared_secret_key } => {
            // If we received an Hello but nothing else, and did not
            // send any reply to the Hello, send Key and set the state
            // to SentKey
            let nonce = crypto_box::gen_nonce();
            let packet = create_key(session, &nonce, &shared_secret_key, false, data);
            session.state = SessionState::SentKey {
                their_temp_pk: their_temp_pk,
                shared_secret_key: shared_secret_key,
                };
            Some(packet)
        },
        SessionState::WaitingKey { .. } => {
            None
        },
        SessionState::SentKey { shared_secret_key, .. } => {
            // If we received an Hello but nothing else, and did not send
            // anything other than key, repeat Key and keep the state
            // unchanged.
            let nonce = crypto_box::gen_nonce();
            Some(create_key(session, &nonce, &shared_secret_key, true, data))
        },
        SessionState::Established { .. } => {
            panic!("Tried to create an handshake packet for an established session.")
        },
    }
}

/// Creates an Hello packet
fn create_hello(
    session: &Session,
    nonce: &crypto_box::Nonce,
    credentials: &Credentials,
    repeat: bool,
    data: &[u8],
) -> HandshakePacket {
    let packet_type = if repeat {
        HandshakePacketType::RepeatHello
    } else {
        HandshakePacketType::Hello
    };

    let shared_secret_key = credentials.make_shared_secret_key(session);
    let (msg_auth_code, my_encrypted_temp_pk, encrypted_data) =
        create_msg_end(session, nonce, &shared_secret_key, data);

    let packet = HandshakePacketBuilder::new()
        .packet_type(&packet_type)
        .auth_challenge(&credentials.to_auth_challenge_bytes(session))
        .random_nonce(&nonce.0)
        .sender_perm_pub_key(&session.my_perm_pk.0)
        .msg_auth_code(&msg_auth_code)
        .sender_encrypted_temp_pub_key(&my_encrypted_temp_pk)
        .encrypted_data(&encrypted_data)
        .finalize()
        .unwrap();
    packet
}

/// Creates a Key packet
fn create_key(
    session: &Session,
    nonce: &Nonce,
    shared_secret_key: &PrecomputedKey,
    repeat: bool,
    data: &[u8],
) -> HandshakePacket {
    let packet_type = if repeat {
        HandshakePacketType::RepeatKey
    } else {
        HandshakePacketType::Key
    };

    let (msg_auth_code, my_encrypted_temp_pk, encrypted_data) =
        create_msg_end(session, nonce, shared_secret_key, data);

    let packet = HandshakePacketBuilder::new()
        .packet_type(&packet_type)
        .auth_challenge(&Credentials::None.to_auth_challenge_bytes(session))
        .random_nonce(&nonce.0)
        .sender_perm_pub_key(&session.my_perm_pk.0)
        .msg_auth_code(&msg_auth_code)
        .sender_encrypted_temp_pub_key(&my_encrypted_temp_pk)
        .encrypted_data(&encrypted_data)
        .finalize()
        .unwrap();
    packet
}

/// Returns the msg_auth_code and sender_encrypted_temp_pk fields
/// of a packet.
fn create_msg_end(
    session: &Session,
    nonce: &Nonce,
    shared_secret_key: &PrecomputedKey,
    data: &[u8],
) -> (
    [u8; crypto_box::MACBYTES],
    [u8; crypto_box::PUBLICKEYBYTES],
    Vec<u8>,
) {
    // This part is a bit tricky. Hold on tight.

    let mut buf = Vec::with_capacity(crypto_box::PUBLICKEYBYTES + data.len());
    buf.extend_from_slice(&session.my_temp_pk.0);
    buf.extend_from_slice(data);

    // Here, we will encrypt the temp pub *key* using the *shared secret*.
    // This may seem counter-intuitive; but it is actually valid because
    // encryption keys and symmetric secrets all are 32-bits long.
    let authenticated_sealed_temp_pk = crypto_box::seal_precomputed(
        &buf,               // We encrypt the temp pub key
        &nonce,             // with the Nonce
        &shared_secret_key, // using the shared secret.
    );
    assert!(authenticated_sealed_temp_pk.len() >= 16 + 32 + data.len());

    // The seal_precomputed function will return a buffer containing
    // 16 bytes of MAC (msg auth code), followed by 32 bytes of encrypted data
    // (The implementations details given in paragraph 6 only apply to
    // the C API, not to the Rust API.)

    // And we can extract these
    let mut msg_auth_code = [0u8; 16];
    msg_auth_code.copy_from_slice(&authenticated_sealed_temp_pk[0..16]);
    let mut my_encrypted_temp_pk = [0u8; 32];
    my_encrypted_temp_pk.copy_from_slice(&authenticated_sealed_temp_pk[16..48]);
    let mut encrypted_data = Vec::with_capacity(authenticated_sealed_temp_pk.len() - 48);
    encrypted_data.extend_from_slice(&authenticated_sealed_temp_pk[48..]);

    // Remark: actually, we could do this faster. Here, we split the
    // sealed value into msg_auth_code, sender_encrypted_temp_pub_key,
    // and data;
    // but these too value are then concatenated in the same order in
    // the packet's serialization.
    // But I prefer to keep the code readable.

    (msg_auth_code, my_encrypted_temp_pk, encrypted_data)
}

/// Returns the public key of a Hello
///
/// Returns None if and only if it was not a Hello packet.
pub fn pre_parse_hello_packet(packet: &HandshakePacket) -> Option<PublicKey> {
    match packet.packet_type() {
        Ok(HandshakePacketType::Hello) | Ok(HandshakePacketType::RepeatHello) => {
            Some(PublicKey::from_slice(&packet.sender_perm_pub_key()).unwrap())
        }
        _ => None,
    }
}

/// Read a network packet.
///
/// The peer result is None only if this is a key packet.
pub fn parse_handshake_packet<Peer: Clone>(
    session: &mut Session,
    password_store: &PasswordStore<Peer>,
    packet: &HandshakePacket,
) -> Result<(Option<Peer>, Vec<u8>), AuthFailure> {
    let packet_type = match packet.packet_type() {
        Err(_) => panic!("Non-handshake packet passed to parse_handshake_packet"),
        Ok(packet_type) => packet_type,
    };

    match packet_type {
        HandshakePacketType::Hello | HandshakePacketType::RepeatHello => {
            let (peer, data) = parse_hello_packet(session, password_store, packet)?;
            Ok((Some(peer), data))
        }
        HandshakePacketType::Key | HandshakePacketType::RepeatKey => {
            let data = parse_key_packet(session, packet)?;
            Ok((None, data))
        }
    }
}

/// Read a network packet without checking authentication.
///
/// The peer result is None only if this is a key packet.
pub fn parse_handshake_packet_no_auth<Peer: Clone>(
    session: &mut Session,
    packet: &HandshakePacket,
) -> Result<Vec<u8>, AuthFailure> {
    let packet_type = match packet.packet_type() {
        Err(_) => panic!("Non-handshake packet passed to parse_handshake_packet"),
        Ok(packet_type) => packet_type,
    };

    match packet_type {
        HandshakePacketType::Hello | HandshakePacketType::RepeatHello => {
            parse_authnone_hello_packet(session, packet)
        }
        HandshakePacketType::Key | HandshakePacketType::RepeatKey => {
            parse_key_packet(session, packet)
        }
    }
}

/// Read a network packet, assumed to be an Hello or a RepeatHello.
pub fn parse_hello_packet<Peer: Clone>(
    session: &mut Session,
    password_store: &PasswordStore<Peer>,
    packet: &HandshakePacket,
) -> Result<(Peer, Vec<u8>), AuthFailure> {
    match packet.packet_type() {
        Err(_) => panic!("Non-handshake packet passed to parse_hello_packet"),
        Ok(HandshakePacketType::Hello) | Ok(HandshakePacketType::RepeatHello) => {}
        _ => panic!("Non-hello handshake packet passed to parse_hello_packet"),
    };

    let (their_temp_pk, peer, data) =
        authenticate_packet_author(session, password_store, packet)?;

    // Below, we are sure this packet is from this peer.
    session.state = update_session_state_on_received_hello(session, packet, their_temp_pk);
    Ok((peer.clone(), data))
}

/// Read a network packet, assumed to be an Hello or a RepeatHello with
/// no authentication
pub fn parse_authnone_hello_packet(
    session: &mut Session,
    packet: &HandshakePacket,
) -> Result<Vec<u8>, AuthFailure> {
    match packet.packet_type() {
        Err(_) => panic!("Non-handshake packet passed to parse_authnone_hello_packet"),
        Ok(HandshakePacketType::Hello) | Ok(HandshakePacketType::RepeatHello) => {}
        _ => panic!("Non-hello handshake packet passed to parse_authnone_hello_packet"),
    };
    assert_eq!(session.their_perm_pk.0, packet.sender_perm_pub_key());

    let nonce = crypto_box::Nonce::from_slice(&packet.random_nonce()).unwrap();
    let shared_secret_key = shared_secret_from_keys(&session.my_perm_sk, &session.their_perm_pk);
    match open_packet_end(packet.sealed_data(), &shared_secret_key, &nonce) {
        Ok((their_temp_pk, data)) => {
            // authentication succeeded
            session.state = update_session_state_on_received_hello(session, packet, their_temp_pk);
            Ok(data)
        }
        Err(_) => Err(AuthFailure::CorruptedPacket(format!(
            "Could not decrypt authnone Hello packet end of:\n{:?}",
            packet
        ))),
    }
}

/// Read a network packet, assumed to be an Key or RepeatKey
pub fn parse_key_packet(
    session: &mut Session,
    packet: &HandshakePacket,
) -> Result<Vec<u8>, AuthFailure> {
    match packet.packet_type() {
        Err(_) => panic!("Non-handshake packet passed to parse_key_packet"),
        Ok(HandshakePacketType::Key) | Ok(HandshakePacketType::RepeatKey) => {}
        _ => panic!("Non-key handshake packet passed to parse_key_packet"),
    };

    // If this is a key packet, do not check its auth.
    match session.state.clone() {
        // TODO: do not clone
        SessionState::WaitingKey {
            shared_secret_key, ..
        }
        | SessionState::SentHello {
            shared_secret_key, ..
        }
        | SessionState::Established {
            handshake_shared_secret_key: shared_secret_key,
            ..
        } => {
            // Obviously, only allow key packets if we sent an hello.
            // Also make sure the packet is authenticated with the
            // shared secret.
            let nonce = crypto_box::Nonce::from_slice(&packet.random_nonce()).unwrap();
            match open_packet_end(packet.sealed_data(), &shared_secret_key, &nonce) {
                Ok((their_temp_pk, data)) => {
                    // authentication succeeded
                    session.state =
                        update_session_state_on_received_key(session, packet, their_temp_pk);
                    Ok(data)
                }
                Err(_) => Err(AuthFailure::CorruptedPacket(
                    "Could not decrypt Key packet end.".to_owned(),
                )),
            }
        }
        _ => Err(AuthFailure::UnexpectedPacket(format!(
            "Got a key packet in session state {:?}",
            session.state
        ))),
    }
}

// Should only be called for authenticated packets.
fn update_session_state_on_received_hello(
    session: &mut Session,
    packet: &HandshakePacket,
    their_temp_pk: PublicKey,
) -> SessionState {
    // This function is a huge case disjunction. I am very sorry if you
    // have to read this, but we have to do it at some point.
    assert!(
        packet.packet_type() == Ok(HandshakePacketType::Hello)
            || packet.packet_type() == Ok(HandshakePacketType::RepeatHello)
    );
    match session.state.clone() {
        // TODO: do not clone
        SessionState::SentHello {
            shared_secret_key, ..
        } => {
            // We both sent a hello. Break the tie by making the
            // one with the lower key win.
            if session.my_perm_pk < session.their_perm_pk {
                // I win. Keep my hello.
                SessionState::WaitingKey {
                    their_temp_pk: their_temp_pk,
                    shared_secret_key: shared_secret_key,
                }
            } else {
                // They win. Keep theirs
                session.reset();
                SessionState::ReceivedHello {
                    their_temp_pk: their_temp_pk,
                    shared_secret_key: shared_secret_from_keys(&session.my_perm_sk, &their_temp_pk),
                }
            }
        }
        SessionState::UninitializedUnknownPeer => SessionState::ReceivedHello {
            their_temp_pk: their_temp_pk,
            shared_secret_key: shared_secret_from_keys(&session.my_perm_sk, &their_temp_pk),
        },
        SessionState::UninitializedKnownPeer { .. }
        | SessionState::ReceivedHello { .. }
        | SessionState::WaitingKey { .. }
        | SessionState::SentKey { .. }
        | SessionState::Established { .. } => {
            // Reset the session
            session.reset();
            SessionState::ReceivedHello {
                their_temp_pk: their_temp_pk,
                shared_secret_key: shared_secret_from_keys(&session.my_perm_sk, &their_temp_pk),
            }
        }
    }
}

// Should only be called for authenticated packets.
fn update_session_state_on_received_key(
    session: &Session,
    packet: &HandshakePacket,
    their_temp_pk: PublicKey,
) -> SessionState {
    assert!(
        packet.packet_type() == Ok(HandshakePacketType::Key)
            || packet.packet_type() == Ok(HandshakePacketType::RepeatKey)
    );
    match session.state {
        SessionState::WaitingKey {
            ref shared_secret_key,
            ..
        }
        | SessionState::SentHello {
            ref shared_secret_key,
            ..
        } => SessionState::Established {
            their_temp_pk: their_temp_pk,
            handshake_shared_secret_key: shared_secret_key.clone(),
            shared_secret_key: shared_secret_from_keys(&session.my_temp_sk, &their_temp_pk),
            initiator_is_me: true,
        },
        SessionState::UninitializedUnknownPeer
        | SessionState::UninitializedKnownPeer { .. }
        | SessionState::ReceivedHello { .. }
        | SessionState::SentKey { .. }
        | SessionState::Established { .. } => {
            // We did not expect a Key. Keep the session unchanged
            session.state.clone() // TODO: do not clone
        }
    }
}

/// Tries to authenticate the author of the packet against the
/// `password_store`. If authentication was successful, returns
/// `Some((their_temp_pk, peer, data))`
fn authenticate_packet_author<'a, Peer: Clone>(
    session: &Session,
    password_store: &'a PasswordStore<Peer>,
    packet: &HandshakePacket,
) -> Result<(PublicKey, &'a Peer, Vec<u8>), AuthFailure> {
    let mut hash_code = [0u8; 7];
    hash_code.copy_from_slice(&packet.auth_challenge()[1..8]);
    let candidates_opt = match packet.auth_challenge()[0] {
        0x00 => return Err(AuthFailure::AuthNone), // No auth, not supported.
        0x01 => {
            // Password only
            password_store.get_candidate_peers_from_password_doublehash_slice(&hash_code)
        }
        0x02 => {
            // Login + Password
            password_store.get_candidate_peers_from_login_hash_slice(&hash_code)
        }
        method => return Err(AuthFailure::UnknownAuthMethod(method)),
    };
    let candidates = match candidates_opt {
        Some(candidates) => candidates,
        None => {
            let err_msg = match packet.auth_challenge()[0] {
                0x01 => "No candidate peer for password-only authorization.",
                0x02 => "No candidate peer for login-password authorization.",
                _ => panic!("The impossible happened."),
            };
            return Err(AuthFailure::InvalidCredentials(err_msg.to_owned()));
        }
    };

    let their_perm_pk = crypto_box::PublicKey::from_slice(&packet.sender_perm_pub_key()).unwrap();
    if session.their_perm_pk != their_perm_pk {
        // Wrong key. Drop the packet.
        return Err(AuthFailure::WrongPublicKey);
    }

    let nonce = crypto_box::Nonce::from_slice(&packet.random_nonce()).unwrap();

    for &(ref password, ref peer) in candidates {
        let shared_secret_key =
            shared_secret_from_password(password, &session.my_perm_sk, &their_perm_pk);
        match open_packet_end(packet.sealed_data(), &shared_secret_key, &nonce) {
            Ok((their_temp_pk, data)) => return Ok((their_temp_pk, peer, data)),
            Err(_) => {}
        }
    }
    let err_msg = match packet.auth_challenge()[0] {
        0x01 => "Could not open packet using password-only authorization.",
        0x02 => "Could not open packet using login-password authorization.",
        _ => panic!("The impossible happened."),
    };
    return Err(AuthFailure::InvalidCredentials(err_msg.to_owned()));
}

/// Should be called when the first (authenticated) non-handshake packet arrives.
/// Otherwise, this is a no-op.
pub fn finalize(session: &mut Session) {
    match session.state.clone() {
        // TODO: do not clone
        SessionState::SentKey {
            their_temp_pk,
            shared_secret_key,
            ..
        } => {
            session.state = SessionState::Established {
                their_temp_pk: their_temp_pk,
                handshake_shared_secret_key: shared_secret_key,
                shared_secret_key: shared_secret_from_keys(&session.my_temp_sk, &their_temp_pk),
                initiator_is_me: false,
            };
        }
        _ => {}
    }
}

#[test]
fn test_parse_handshake_password() {
    use hex::FromHex as VecFromHex;
    use keys::{FromBase32, FromHex};

    let my_sk = crypto_box::SecretKey::from_hex(
        b"ac3e53b518e68449692b0b2f2926ef2fdc1eac5b9dbd10a48114263b8c8ed12e",
    )
    .unwrap();
    let my_pk = crypto_box::PublicKey::from_base32(
        b"2wrpv8p4tjwm532sjxcbqzkp7kdwfwzzbg7g0n5l6g3s8df4kvv0.k",
    )
    .unwrap();
    let their_pk = crypto_box::PublicKey::from_base32(
        b"2j1xz5k5y1xwz7kcczc4565jurhp8bbz1lqfu9kljw36p3nmb050.k",
    )
    .unwrap();
    // Corresponding secret key: 824736a667d85582747fde7184201b17d0e655a7a3d9e0e3e617e7ca33270da8
    let mut session = Session::new(
        my_pk,
        my_sk,
        their_pk,
        SessionState::UninitializedUnknownPeer,
    );

    let raw = Vec::from_hex("0000000101ed58a609bc994800000000551ae6bc4940ff2e1f4e9cba228ebe0a18ed77a2ee0a7bb10286fe4b2c3e74fe4f5ceb2f524c81fabe8a94fa41daa65394900f53079d0a1497cdd55def51daf65a45027745706d1673d7a3c8946fa043923e46772284475b26ea71f504055537547c4276d92a013740ab42c612516c69ad8b524d11b55eff7f8976512248806104f0ec4f3e62f8f40926af4cfcad7e79").unwrap();
    let packet = HandshakePacket { raw: raw };
    let mut store = PasswordStore::new();
    store.add_peer(
        Some(&"foo".as_bytes().to_vec()),
        "bar".as_bytes().to_vec(),
        "my friend".to_owned(),
    );

    assert_eq!(packet.sender_perm_pub_key(), session.their_perm_pk.0);
    match parse_handshake_packet(&mut session, &store, &packet) {
        Err(_) => assert!(false),
        Ok((peer, _data)) => assert_eq!(peer, Some("my friend".to_owned())),
    }
}

#[test]
fn test_parse_handshake_login() {
    use hex::FromHex as VecFromHex;
    use keys::{FromBase32, FromHex};

    let my_sk = crypto_box::SecretKey::from_hex(
        b"ac3e53b518e68449692b0b2f2926ef2fdc1eac5b9dbd10a48114263b8c8ed12e",
    )
    .unwrap();
    let my_pk = crypto_box::PublicKey::from_base32(
        b"2wrpv8p4tjwm532sjxcbqzkp7kdwfwzzbg7g0n5l6g3s8df4kvv0.k",
    )
    .unwrap();
    let their_pk = crypto_box::PublicKey::from_base32(
        b"2j1xz5k5y1xwz7kcczc4565jurhp8bbz1lqfu9kljw36p3nmb050.k",
    )
    .unwrap();
    // Corresponding secret key: 824736a667d85582747fde7184201b17d0e655a7a3d9e0e3e617e7ca33270da8
    let mut session = Session::new(
        my_pk,
        my_sk,
        their_pk,
        SessionState::UninitializedUnknownPeer,
    );

    let raw = Vec::from_hex("000000010226b46b68ffc68f00000000172d7a21645efff9ef874a9094351e870f622537ea208e7f0286fe4b2c3e74fe4f5ceb2f524c81fabe8a94fa41daa65394900f53079d0a14aa670e527964f576521d63c72b1398c19438ea7b661c7dec59e67b86bddf128705108782d53d22742a6b5d2baa6b23af26e154f87678322f0e43eea7a82563e655c36d6126881ec44d0e44ba659c21cafdb3a8017c4ccdc7").unwrap();
    let packet = HandshakePacket { raw: raw };
    let mut store = PasswordStore::new();
    store.add_peer(
        Some(&"foo".as_bytes().to_vec()),
        "bar".as_bytes().to_vec(),
        "my friend".to_owned(),
    );

    assert_eq!(packet.sender_perm_pub_key(), session.their_perm_pk.0);
    match parse_handshake_packet(&mut session, &store, &packet) {
        Err(_) => assert!(false),
        Ok((peer, _data)) => assert_eq!(peer, Some("my friend".to_owned())),
    }
}