sunset 0.4.0

A SSH library suitable for embedded and larger programs
Documentation
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Handles encryption/decryption and framing a payload in a SSH packet.

#![cfg_attr(fuzzing, allow(dead_code))]
#![cfg_attr(fuzzing, allow(unused_variables))]

#[allow(unused_imports)]
use {
    crate::error::{Error, Result, TrapBug},
    log::{debug, error, info, log, trace, warn},
};

use core::fmt;
use core::fmt::Debug;
use core::num::Wrapping;

use aes::cipher::{BlockSizeUser, KeyIvInit, KeySizeUser, StreamCipher};
use hmac::Mac;
use sha2::Digest as Sha2DigestForTrait;
use zeroize::ZeroizeOnDrop;

use crate::*;
use kex::{self, SessId};
use ssh_chapoly::SSHChaPoly;
use sshnames::*;

// TODO: check that Ctr32 is sufficient. Should be OK with SSH rekeying.
type Aes256Ctr32BE = ctr::Ctr32BE<aes::Aes256>;
type HmacSha256 = hmac::Hmac<sha2::Sha256>;

const SSH_MIN_PADLEN: usize = 4;
const SSH_MIN_BLOCK: usize = 8;
pub const SSH_LENGTH_SIZE: usize = 4;
pub const SSH_PAYLOAD_START: usize = SSH_LENGTH_SIZE + 1;

// TODO: should calculate/check these somehow
/// Largest is aes256ctr
const MAX_IV_LEN: usize = 32;
/// Largest is chacha. Also applies to MAC keys
const MAX_KEY_LEN: usize = 64;

/// Stateful [`Keys`], stores a sequence number as well, a single instance
/// is kept for the entire session.
#[derive(Debug)]
pub(crate) struct KeyState {
    enc: KeysSend,
    dec: KeysRecv,
    // Packet sequence numbers.
    // These reset on newkeys when strict kex is in effect.
    pub seq_encrypt: Wrapping<u32>,
    pub seq_decrypt: Wrapping<u32>,
    strict_kex: bool,
    done_first_kex: bool,
}

impl KeyState {
    /// A brand new `KeyState` with no encryption, zero sequence numbers
    pub fn new_cleartext() -> Self {
        KeyState {
            enc: KeysSend::new_cleartext(),
            dec: KeysRecv::new_cleartext(),
            seq_encrypt: Wrapping(0),
            seq_decrypt: Wrapping(0),
            strict_kex: false,
            done_first_kex: false,
        }
    }

    pub fn is_send_cleartext(&self) -> bool {
        matches!(self.enc.cipher, EncKey::NoCipher)
    }

    /// Updates with keys for sending.
    pub fn rekey_send(&mut self, keys: KeysSend, enable_strict: bool) {
        self.enc = keys;
        if enable_strict && !self.done_first_kex {
            self.strict_kex = true;
        }
        self.done_first_kex = true;
        if self.strict_kex {
            self.seq_encrypt = Wrapping(0);
        }
    }

    /// Updates with keys for receiving.
    ///
    /// Should occur after rekey_send, since NewKeys should
    /// have been sent prior to handling remote's NewKeys.
    pub fn rekey_recv(&mut self, keys: KeysRecv) {
        debug_assert!(
            !matches!(self.enc.cipher, EncKey::NoCipher),
            "Should have already performed rekey_enc"
        );

        self.dec = keys;
        self.done_first_kex = true;
        if self.strict_kex {
            self.seq_decrypt = Wrapping(0);
        }
    }

    pub fn recv_seq(&self) -> u32 {
        self.seq_decrypt.0
    }

    /// Decrypts the first block in the buffer
    ///
    /// Returning the length.
    pub fn decrypt_first_block(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        self.dec.decrypt_first_block(buf, self.seq_decrypt.0)
    }

    /// Decrypt and validate the remainder of the buffer.
    ///
    /// Decrypt bytes 4 onwards of the buffer and validate AEAD Tag or MAC.
    /// Ensures that the packet meets minimum length.
    pub fn decrypt(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let e = self.dec.decrypt(buf, self.seq_decrypt.0);
        self.seq_decrypt += 1;
        e
    }

    /// Encrypt the output buffer
    ///
    /// [`buf`] is the entire output buffer to encrypt in place.
    /// payload_len is the length of the payload portion
    /// This is stateful, updating the sequence number.
    pub fn encrypt(
        &mut self,
        payload_len: usize,
        buf: &mut [u8],
    ) -> Result<usize, Error> {
        let e = self.enc.encrypt(payload_len, buf, self.seq_encrypt.0);
        self.seq_encrypt += 1;
        e
    }

    pub fn size_block_dec(&self) -> usize {
        self.dec.cipher.size_block()
    }

    pub fn max_enc_payload(&self, total_avail: usize) -> usize {
        self.enc.max_enc_payload(total_avail)
    }
}

#[derive(Debug)]
pub(crate) struct KeysSend {
    cipher: EncKey,
    integ: IntegKey,
}

impl KeysSend {
    fn new_cleartext() -> Self {
        Self { cipher: EncKey::NoCipher, integ: IntegKey::NoInteg }
    }

    pub fn new<CS: CliServ>(
        kex_out: &kex::KexOutput,
        sess_id: &SessId,
        algos: &kex::Algos<CS>,
    ) -> Self {
        let mut key = [0u8; MAX_KEY_LEN];
        let mut iv = [0u8; MAX_IV_LEN];

        let [iv_e, k_e, i_e] =
            if CS::is_client() { ['A', 'C', 'E'] } else { ['B', 'D', 'F'] };

        // OK to unwrap here, have tests for all iv_len and key_len
        let cipher = {
            let ci = kex_out.compute_key(
                iv_e,
                algos.cipher_enc.iv_len(),
                &mut iv,
                sess_id,
            );
            let ck = kex_out.compute_key(
                k_e,
                algos.cipher_enc.key_len(),
                &mut key,
                sess_id,
            );
            EncKey::from_cipher(&algos.cipher_enc, ck, ci).unwrap()
        };

        let integ = {
            let ck = kex_out.compute_key(
                i_e,
                algos.integ_enc.key_len(),
                &mut key,
                sess_id,
            );
            IntegKey::from_integ(&algos.integ_enc, ck).unwrap()
        };

        Self { cipher, integ }
    }

    /// Padding is required to meet
    /// - minimum packet length
    /// - minimum padding size,
    /// - encrypted length being a multiple of block length
    fn calc_encrypt_pad(&self, payload_len: usize) -> usize {
        let size_block = self.cipher.size_block();
        // aead ciphers don't include the initial length field in encrypted blocks
        let len = 1
            + payload_len
            + if self.cipher.is_aead() { 0 } else { SSH_LENGTH_SIZE };

        // round padding length upwards so that len is a multiple of block size
        let mut padlen = size_block - len % size_block;

        // need at least 4 bytes padding
        if padlen < SSH_MIN_PADLEN {
            padlen += size_block
        }

        padlen
    }

    /// Returns the maximum payload that can fit in an available buffer
    /// after header, encryption, padding, mac
    pub fn max_enc_payload(&self, total_avail: usize) -> usize {
        // mac is independent of the rest
        let total_avail = total_avail.saturating_sub(self.integ.size_out());

        let overhead = SSH_LENGTH_SIZE + 1 + SSH_MIN_PADLEN;
        let mut space = total_avail;

        // multiple of block length
        let enc_len = if self.cipher.is_aead() {
            total_avail.saturating_sub(SSH_LENGTH_SIZE)
        } else {
            total_avail
        };

        // round down to block size
        let extra_block = enc_len % self.cipher.size_block();
        if extra_block != 0 {
            space = space.saturating_sub(extra_block);
        }

        space.saturating_sub(overhead)
    }

    /// Encrypt a buffer in-place, adding packet size, padding, MAC etc.
    /// Returns the total length.
    /// Ensures that the packet meets minimum and other length requirements.
    fn encrypt(
        &mut self,
        payload_len: usize,
        buf: &mut [u8],
        seq: u32,
    ) -> Result<usize, Error> {
        let size_block = self.cipher.size_block();
        let size_integ = self.integ.size_out();
        let padlen = self.calc_encrypt_pad(payload_len);
        // len is everything except the MAC
        let len = SSH_LENGTH_SIZE + 1 + payload_len + padlen;

        if self.cipher.is_aead() {
            debug_assert_eq!((len - SSH_LENGTH_SIZE) % size_block, 0);
        } else {
            debug_assert_eq!(len % size_block, 0);
        };

        if len + size_integ > buf.len() {
            error!("Output buffer {} is too small for packet", buf.len());
            return error::NoRoom.fail();
        }

        // write the length
        let blen = ((len - SSH_LENGTH_SIZE) as u32).to_be_bytes();
        buf[..SSH_LENGTH_SIZE].copy_from_slice(&blen);
        // write random padding
        buf[SSH_LENGTH_SIZE] = padlen as u8;
        let pad_start = SSH_LENGTH_SIZE + 1 + payload_len;
        debug_assert_eq!(pad_start + padlen, len);
        random::fill_random(&mut buf[pad_start..pad_start + padlen])?;

        let (enc, rest) = buf.split_at_mut(len);
        let (mac, _) = rest.split_at_mut(size_integ);

        match self.integ {
            IntegKey::ChaPoly => {}
            IntegKey::NoInteg => {}
            IntegKey::HmacSha256(k) => {
                let mut h = HmacSha256::new_from_slice(&k).trap()?;
                h.update(&seq.to_be_bytes());
                h.update(enc);
                let result = h.finalize();
                mac.copy_from_slice(&result.into_bytes());
            }
        }

        match &mut self.cipher {
            EncKey::ChaPoly(k) => k.encrypt(seq, enc, mac).trap()?,
            EncKey::Aes256Ctr(a) => {
                a.apply_keystream(enc);
            }
            EncKey::NoCipher => {}
        }

        // ETM integ modes would go here.

        Ok(len + size_integ)
    }
}

#[derive(Debug)]
pub(crate) struct KeysRecv {
    cipher: DecKey,
    integ: IntegKey,
}

impl KeysRecv {
    fn new_cleartext() -> Self {
        Self { cipher: DecKey::NoCipher, integ: IntegKey::NoInteg }
    }

    pub fn new<CS: CliServ>(
        kex_out: &kex::KexOutput,
        sess_id: &SessId,
        algos: &kex::Algos<CS>,
    ) -> Self {
        let mut key = [0u8; MAX_KEY_LEN];
        let mut iv = [0u8; MAX_IV_LEN];

        let [iv_d, k_d, i_d] =
            if CS::is_client() { ['B', 'D', 'F'] } else { ['A', 'C', 'E'] };

        // OK to unwrap here, have tests for all iv_len and key_len
        let cipher = {
            let ci = kex_out.compute_key(
                iv_d,
                algos.cipher_dec.iv_len(),
                &mut iv,
                sess_id,
            );
            let ck = kex_out.compute_key(
                k_d,
                algos.cipher_dec.key_len(),
                &mut key,
                sess_id,
            );
            DecKey::from_cipher(&algos.cipher_dec, ck, ci).unwrap()
        };

        let integ = {
            let ck = kex_out.compute_key(
                i_d,
                algos.integ_dec.key_len(),
                &mut key,
                sess_id,
            );
            IntegKey::from_integ(&algos.integ_dec, ck).unwrap()
        };

        Self { cipher, integ }
    }

    /// Decrypts the first block in the buffer
    ///
    /// Returns the length of the
    /// total SSH packet (including length+mac) which is calculated
    /// from the decrypted first 4 bytes.
    /// Whether bytes `buf[4..block_size]` are decrypted depends on the cipher, they may be
    /// handled later by [`decrypt`]. Bytes `buf[0..4]` may be left unmodified.
    fn decrypt_first_block(
        &mut self,
        buf: &mut [u8],
        seq: u32,
    ) -> Result<usize, Error> {
        if buf.len() < self.cipher.size_block() {
            return Err(Error::bug());
        }

        #[cfg(fuzzing)]
        let len = u32::from_be_bytes(buf[..SSH_LENGTH_SIZE].try_into().unwrap());

        #[cfg(not(fuzzing))]
        let len = match &mut self.cipher {
            DecKey::ChaPoly(k) => k.packet_length(seq, buf).trap()?,
            DecKey::Aes256Ctr(a) => {
                a.apply_keystream(&mut buf[..16]);
                u32::from_be_bytes(buf[..SSH_LENGTH_SIZE].try_into().unwrap())
            }
            DecKey::NoCipher => {
                u32::from_be_bytes(buf[..SSH_LENGTH_SIZE].try_into().unwrap())
            }
        };

        let total_len = len
            .checked_add((SSH_LENGTH_SIZE + self.integ.size_out()) as u32)
            .ok_or(Error::BadDecrypt)?;

        Ok(total_len as usize)
    }

    /// Decrypt the whole packet buffer and validate AEAD Tag or MAC.
    ///
    /// Returns the payload length.
    /// Ensures that the packet meets minimum length.
    /// The first block_size bytes may have been already decrypted by
    /// [`decrypt_first_block`] depending on the cipher.
    fn decrypt(&mut self, buf: &mut [u8], seq: u32) -> Result<usize, Error> {
        let size_block = self.cipher.size_block();
        let size_integ = self.integ.size_out();

        if buf.len() < size_block + size_integ {
            debug!("Bad packet, {} smaller than block size", buf.len());
            return error::SSHProto.fail();
        }
        // "MUST be a multiple of the cipher block size".
        // encrypted length for aead ciphers doesn't include the length prefix.
        let sublength = if self.cipher.is_aead() { SSH_LENGTH_SIZE } else { 0 };
        let len = buf.len() - size_integ - sublength;

        if !len.is_multiple_of(size_block) {
            debug!("Bad packet, not multiple of block size");
            return error::SSHProto.fail();
        }

        let (data, mac) = buf.split_at_mut(buf.len() - size_integ);

        // roundtrip tests are exhaustive over short packet lengths
        debug_assert!(data.len() >= size_block);

        // ETM modes would check integrity here.

        #[cfg(not(fuzzing))]
        match &mut self.cipher {
            DecKey::ChaPoly(k) => {
                k.decrypt(seq, data, mac).map_err(|_| Error::BadDecrypt)?;
            }
            DecKey::Aes256Ctr(a) => {
                // safe index, checked data.len()
                a.apply_keystream(&mut data[16..]);
            }
            DecKey::NoCipher => {}
        }

        #[cfg(not(fuzzing))]
        match self.integ {
            IntegKey::ChaPoly => {}
            IntegKey::NoInteg => {}
            IntegKey::HmacSha256(k) => {
                let mut h = HmacSha256::new_from_slice(&k).trap()?;
                h.update(&seq.to_be_bytes());
                h.update(data);
                h.verify_slice(mac).map_err(|_| Error::BadDecrypt)?;
            }
        }

        let padlen = data[SSH_LENGTH_SIZE] as usize;
        if padlen < SSH_MIN_PADLEN {
            debug!("Packet padding too short");
            return error::SSHProto.fail();
        }

        let payload_len = buf
            .len()
            .checked_sub(SSH_LENGTH_SIZE + 1 + size_integ + padlen)
            .ok_or_else(|| {
                debug!("Bad padding length");
                error::SSHProto.build()
            })?;

        Ok(payload_len)
    }
}

/// Placeholder for a cipher type prior to creating an [`EncKey`] or [`DecKey`],
/// for use during key setup in [`kex`]
#[derive(Debug, Clone)]
pub(crate) enum Cipher {
    ChaPoly,
    Aes256Ctr,
    // TODO AesGcm etc
}

impl fmt::Display for Cipher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = match self {
            Self::ChaPoly => SSH_NAME_CHAPOLY,
            Self::Aes256Ctr => SSH_NAME_AES256_CTR,
        };
        write!(f, "{n}")
    }
}

impl Cipher {
    /// Creates a cipher key by algorithm name. Must be passed a known name.
    pub fn from_name(name: &'static str) -> Result<Self, Error> {
        match name {
            SSH_NAME_CHAPOLY => Ok(Cipher::ChaPoly),
            SSH_NAME_AES256_CTR => Ok(Cipher::Aes256Ctr),
            _ => Err(Error::bug()),
        }
    }

    /// Length in bytes
    pub fn key_len(&self) -> usize {
        match self {
            Cipher::ChaPoly => SSHChaPoly::KEY_LEN,
            Cipher::Aes256Ctr => aes::Aes256::key_size(),
        }
    }

    /// Length in bytes
    pub fn iv_len(&self) -> usize {
        match self {
            Cipher::ChaPoly => 0,
            Cipher::Aes256Ctr => aes::Aes256::block_size(),
        }
    }

    /// Returns the [`Integ`] for this cipher, or None if not aead
    pub fn integ(&self) -> Option<Integ> {
        match self {
            Cipher::ChaPoly => Some(Integ::ChaPoly),
            Cipher::Aes256Ctr => None,
        }
    }
}

#[derive(Clone, ZeroizeOnDrop)]
pub(crate) enum EncKey {
    ChaPoly(SSHChaPoly),
    Aes256Ctr(Aes256Ctr32BE),
    // AesGcm(Todo?)
    NoCipher,
}

impl Debug for EncKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = match self {
            Self::ChaPoly(_) => "ChaPoly",
            Self::Aes256Ctr(_) => "Aes256Ctr",
            Self::NoCipher => "NoCipher",
        };
        f.write_fmt(format_args!("EncKey::{n}"))
    }
}

// TODO: could probably unify EncKey and DecKey as "CipherKey".
// Ring had sealing/opening keys which are separate, but RustCrypto
// uses the same structs in both directions.

impl EncKey {
    /// Construct a key
    pub fn from_cipher<'a>(
        cipher: &Cipher,
        key: &'a [u8],
        iv: &'a [u8],
    ) -> Result<Self, Error> {
        match cipher {
            Cipher::ChaPoly => {
                Ok(EncKey::ChaPoly(SSHChaPoly::new_from_slice(key).trap()?))
            }
            Cipher::Aes256Ctr => Ok(EncKey::Aes256Ctr(
                Aes256Ctr32BE::new_from_slices(key, iv).trap()?,
            )),
        }
    }
    pub fn is_aead(&self) -> bool {
        match self {
            EncKey::ChaPoly(_) => true,
            EncKey::Aes256Ctr(_a) => false,
            EncKey::NoCipher => false,
        }
    }
    pub fn size_block(&self) -> usize {
        match self {
            EncKey::ChaPoly(_) => SSH_MIN_BLOCK,
            EncKey::Aes256Ctr(_) => aes::Aes256::block_size(),
            EncKey::NoCipher => SSH_MIN_BLOCK,
        }
    }
}

#[derive(Clone, ZeroizeOnDrop)]
pub(crate) enum DecKey {
    ChaPoly(SSHChaPoly),
    Aes256Ctr(Aes256Ctr32BE),
    // AesGcm256
    // AesCtr256
    NoCipher,
}

impl Debug for DecKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = match self {
            Self::ChaPoly(_) => "ChaPoly",
            Self::Aes256Ctr(_) => "Aes256Ctr",
            Self::NoCipher => "NoCipher",
        };
        f.write_fmt(format_args!("DecKey::{n}"))
    }
}

impl DecKey {
    /// Construct a key
    pub fn from_cipher<'a>(
        cipher: &Cipher,
        key: &'a [u8],
        iv: &'a [u8],
    ) -> Result<Self, Error> {
        match cipher {
            Cipher::ChaPoly => {
                Ok(DecKey::ChaPoly(SSHChaPoly::new_from_slice(key).trap()?))
            }
            Cipher::Aes256Ctr => Ok(DecKey::Aes256Ctr(
                Aes256Ctr32BE::new_from_slices(key, iv).trap()?,
            )),
        }
    }
    pub fn is_aead(&self) -> bool {
        match self {
            DecKey::ChaPoly(_) => true,
            DecKey::Aes256Ctr(_a) => false,
            DecKey::NoCipher => false,
        }
    }
    pub fn size_block(&self) -> usize {
        match self {
            DecKey::ChaPoly(_) => SSH_MIN_BLOCK,
            DecKey::Aes256Ctr(_) => aes::Aes256::block_size(),
            DecKey::NoCipher => SSH_MIN_BLOCK,
        }
    }
}

/// Placeholder for a [`IntegKey`] type prior to keying. For use during key setup in [`kex`]
#[derive(Debug, Clone)]
pub(crate) enum Integ {
    ChaPoly,
    HmacSha256,
    // aesgcm?
}

impl Integ {
    /// Matches a MAC name. Should not be called for AEAD ciphers, instead use [`EncKey::integ`] etc
    pub fn from_name(name: &'static str) -> Result<Self, Error> {
        match name {
            SSH_NAME_HMAC_SHA256 => Ok(Integ::HmacSha256),
            _ => Err(Error::bug()),
        }
    }
    /// length in bytes
    fn key_len(&self) -> usize {
        match self {
            Integ::ChaPoly => 0,
            Integ::HmacSha256 => 32,
        }
    }
}

impl fmt::Display for Integ {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = match self {
            Self::ChaPoly => SSH_NAME_CHAPOLY,
            Self::HmacSha256 => SSH_NAME_HMAC_SHA256,
        };
        write!(f, "{n}")
    }
}

#[derive(Clone)]
pub(crate) enum IntegKey {
    ChaPoly,
    HmacSha256([u8; 32]),
    // aesgcm?
    NoInteg,
}

impl Debug for IntegKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = match self {
            Self::ChaPoly => "ChaPoly",
            Self::HmacSha256(_) => "HmacSha256",
            Self::NoInteg => "NoInteg",
        };
        f.write_fmt(format_args!("IntegKey::{n}"))
    }
}

impl IntegKey {
    pub fn from_integ(integ: &Integ, key: &[u8]) -> Result<Self, Error> {
        match integ {
            Integ::ChaPoly => Ok(IntegKey::ChaPoly),
            Integ::HmacSha256 => Ok(IntegKey::HmacSha256(key.try_into().trap()?)),
        }
    }
    pub fn size_out(&self) -> usize {
        match self {
            IntegKey::ChaPoly => SSHChaPoly::TAG_LEN,
            IntegKey::HmacSha256(_) => sha2::Sha256::output_size(),
            IntegKey::NoInteg => 0,
        }
    }
}

#[cfg(test)]
mod tests {
    use core::marker::PhantomData;

    use crate::encrypt::*;
    use crate::error::Error;
    use crate::kex::KexOutput;
    use crate::sshnames::SSH_NAME_CURVE25519;
    use crate::sunsetlog::*;
    #[allow(unused_imports)]
    use pretty_hex::PrettyHex;
    use sha2::Sha256;

    // setting `corrupt` tests that incorrect mac is detected
    fn do_roundtrips(
        keys_enc: &mut KeyState,
        keys_dec: &mut KeyState,
        corrupt: bool,
    ) {
        for i in 0usize..80 {
            let mut v: std::vec::Vec<u8> = (0u8..i as u8 + 60).collect();
            let orig_payload = v[SSH_PAYLOAD_START..SSH_PAYLOAD_START + i].to_vec();

            let written = keys_enc.encrypt(i, v.as_mut_slice()).unwrap();

            v.truncate(written);

            if corrupt {
                // flip a bit of the payload
                v[SSH_PAYLOAD_START] ^= 4;
            }

            let l = keys_dec.decrypt_first_block(v.as_mut_slice()).unwrap();
            assert_eq!(l, v.len());

            let dec = keys_dec.decrypt(v.as_mut_slice());

            if corrupt {
                assert!(matches!(dec, Err(Error::BadDecrypt)));
                return;
            }
            let payload_len = dec.unwrap();
            assert_eq!(payload_len, i);
            let dec_payload = v[SSH_PAYLOAD_START..SSH_PAYLOAD_START + i].to_vec();
            assert_eq!(orig_payload, dec_payload);
        }
    }

    #[test]
    fn roundtrip_nocipher() {
        // check padding works
        let mut ke = KeyState::new_cleartext();
        let mut kd = KeyState::new_cleartext();
        do_roundtrips(&mut ke, &mut kd, false);
    }

    #[test]
    #[should_panic]
    fn roundtrip_nocipher_corrupt() {
        // test the test, cleartext has no mac
        let mut ke = KeyState::new_cleartext();
        let mut kd = KeyState::new_cleartext();
        do_roundtrips(&mut ke, &mut kd, true);
    }

    // returns combinations of ciphers as Some(), as well as a single
    // None for no-cipher
    fn algo_combos() -> impl Iterator<Item = Option<kex::Algos<Client>>> {
        // TODO make this combinatorial
        // order is enc, dec
        const COMBOS: [(Cipher, Integ, Cipher, Integ); 4] = [
            (
                Cipher::Aes256Ctr,
                Integ::HmacSha256,
                Cipher::Aes256Ctr,
                Integ::HmacSha256,
            ),
            (Cipher::ChaPoly, Integ::ChaPoly, Cipher::ChaPoly, Integ::ChaPoly),
            (Cipher::Aes256Ctr, Integ::HmacSha256, Cipher::ChaPoly, Integ::ChaPoly),
            (Cipher::ChaPoly, Integ::ChaPoly, Cipher::Aes256Ctr, Integ::HmacSha256),
        ];
        COMBOS
            .iter()
            .map(|(ce, ie, cd, id)| {
                Some(kex::Algos {
                    kex: kex::SharedSecret::from_name(SSH_NAME_CURVE25519).unwrap(),
                    hostsig: sign::SigType::Ed25519,
                    cipher_enc: ce.clone(),
                    cipher_dec: cd.clone(),
                    integ_enc: ie.clone(),
                    integ_dec: id.clone(),
                    discard_next: false,
                    send_ext_info: true,
                    strict_kex: false,
                    _cs: PhantomData,
                })
            })
            // and plaintext
            .chain(core::iter::once(None))
    }

    #[test]
    fn algo_roundtrips() {
        init_test_log();

        for mut algos in algo_combos() {
            let mut keys_enc = KeyState::new_cleartext();
            let mut keys_dec = KeyState::new_cleartext();
            if let Some(algos) = algos.take() {
                // arbitrary keys
                let h = SessId::from_slice(&Sha256::digest(
                    "some exchange hash".as_bytes(),
                ))
                .unwrap();
                let sess_id =
                    SessId::from_slice(&Sha256::digest("some sessid".as_bytes()))
                        .unwrap();
                let sharedkey = b"hello";
                let ko = KexOutput::new_test(sharedkey, &h);
                let ko_b = KexOutput::new_test(sharedkey, &h);

                trace!("algos enc {algos:?}");
                let enc = KeysSend::new(&ko, &sess_id, &algos);
                keys_enc.rekey_send(enc, algos.strict_kex);

                // client and server enc/dec keys are derived differently, we need them
                // to match for this test
                let algos = algos.test_swap_to_server();
                trace!("algos dec {algos:?}");
                // rekey_send here only because it's required
                // before rekey_recv.
                let e = KeysSend::new(&ko, &sess_id, &algos);
                keys_dec.rekey_send(e, algos.strict_kex);
                let dec = KeysRecv::new(&ko_b, &sess_id, &algos);
                keys_dec.rekey_recv(dec);
            } else {
                trace!("Trying cleartext");
            }

            do_roundtrips(&mut keys_enc, &mut keys_dec, false);
            // corrupt test only for non-plaintext
            if algos.is_some() {
                do_roundtrips(&mut keys_enc, &mut keys_dec, true);
            }
        }
    }

    #[test]
    fn max_enc_payload() {
        init_test_log();
        for algos in algo_combos() {
            let mut keys = KeyState::new_cleartext();
            if let Some(algos) = algos {
                // arbitrary keys
                let h = SessId::from_slice(&Sha256::digest(b"some exchange hash"))
                    .unwrap();
                let sess_id =
                    SessId::from_slice(&Sha256::digest(b"some sessid")).unwrap();
                let sharedkey = b"hello";
                let ko = KexOutput::new_test(sharedkey, &h);
                let enc = KeysSend::new(&ko, &sess_id, &algos);
                let dec = KeysRecv::new(&ko, &sess_id, &algos);

                keys.rekey_send(enc, algos.strict_kex);
                keys.rekey_recv(dec);
                trace!("algos {algos:?}");
                trace!("integ {}", keys.enc.integ.size_out());
            } else {
                trace!("cleartext");
            }

            let mut buf = [0u8; 100];

            for i in 1..80 {
                let p = keys.max_enc_payload(i);
                trace!("i {i} p {p}");
                if p > 0 {
                    let l = keys.encrypt(p, &mut buf).unwrap();
                    trace!("i {i} p {p} l {l}");
                    assert!(l <= i);
                    assert!(l >= i.saturating_sub(keys.enc.cipher.size_block()));

                    // check a larger payload would bump the packet size
                    let l = keys.encrypt(p + 1, &mut buf).unwrap();
                    assert!(l > i);
                }
            }
        }
    }
}