diff --git a/.tangled/workflows/miri.yml b/.tangled/workflows/miri.yml new file mode 100644 index 0000000..12e9506 --- /dev/null +++ b/.tangled/workflows/miri.yml @@ -0,0 +1,21 @@ +when: + - event: ["push", "pull_request"] + branch: main + +engine: nixery + +dependencies: + nixpkgs: + - clang + - rustup + +steps: + - name: Install Nightly + command: | + rustup toolchain install nightly --component miri + rustup override set nightly + cargo miri setup + - name: Miri Test + command: cargo miri test --locked -p wharrgarbl-neko + environment: + RUSTFLAGS: -Zrandomize-layout diff --git a/src/handshake.rs b/src/handshake.rs index de24da8..aee21a5 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -36,7 +36,7 @@ where } neko.ad(&K::K::to_u8().to_le_bytes()); - neko.ad(&S::to_bytes()); + neko.ad(&S::BYTES); neko.ratchet(); Self { @@ -119,7 +119,7 @@ where } neko.ad(&K::K::to_u8().to_le_bytes()); - neko.ad(&S::to_bytes()); + neko.ad(&S::BYTES); neko.ratchet(); Self { diff --git a/src/lib.rs b/src/lib.rs index 1cd2e2a..58aa28d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,7 +2,7 @@ #![forbid(unsafe_code)] use ml_kem::{MlKem512, MlKem768}; -pub use wharrgarbl_neko::{Neko128, Neko256}; +pub use wharrgarbl_neko::{Neko128, Neko192, Neko256}; pub mod handshake; pub mod transport; @@ -33,5 +33,7 @@ pub mod utils { pub type NekoClientHandshake128 = handshake::ClientHandshake; pub type NekoServerHandshake128 = handshake::ServerHandshake; +pub type NekoClientHandshake192 = handshake::ClientHandshake; +pub type NekoServerHandshake192 = handshake::ServerHandshake; pub type NekoClientHandshake256 = handshake::ClientHandshake; pub type NekoServerHandshake256 = handshake::ServerHandshake; diff --git a/wharrgarbl-neko/SPEC.md b/wharrgarbl-neko/SPEC.md index c4bf526..33acef8 100644 --- a/wharrgarbl-neko/SPEC.md +++ b/wharrgarbl-neko/SPEC.md @@ -1,4 +1,4 @@ -# NEKO Specification +# NEKO Specification v0.2.1 NEKO is inspired by STROBE in that it uses Keccak in a duplex construction to perform encryption and message authentication. It has stripped down the amount of operation flags it uses and simplifies the internals, ridding the need to have "streaming" by instead opting for having different operating modes. @@ -28,11 +28,11 @@ A valid chain of operations can be \[`INIT`, `KEY`, `NONCE`, `AD`\]+\[`ENCRYPT`\ ## Construction -NEKO internally uses the Keccakf1600 state buffer directly, with its layout of `[u64; 25]`. It operates on blocks of `u64`, and mixes `[u8]` input into these blocks. If a block isn't "filled" completely, the remainder of that block is left as padding, with then the position incremented to point to the next block. It tracks a block counter and an op counter. +NEKO internally uses the Keccakp1600 state buffer directly, with its layout of `[u64; 25]`. It operates on blocks of `u64`, and mixes `[u8]` input into these blocks. If a block isn't "filled" completely, the remainder of that block is left as padding, with then the position incremented to point to the next block. It tracks a block counter and an op counter. -NEKO has two security levels, 128-bit and 256-bit security. Each level determines the *rate*, which is how many blocks are available for input, so 128 gives 21 blocks for input with 4 blocks for entropy/*capacity*, while 256 gives 17 blocks and 8 blocks for entropy/*capacity*. The input blocks are separated for data input with the last block reserved for encoding ops. 256 mode will require permuting more often than 128 mode, as it won't have as much input capacity before its input buffer is exhausted. +NEKO has three security levels, 128-bit, 192-bit and 256-bit security. Each level determines the *rate*, which is how many blocks are available for input, so 128 gives 21 blocks for input with 4 blocks for entropy/*capacity*, while 256 gives 17 blocks and 8 blocks for entropy/*capacity*. The input blocks are separated for data input with the last block reserved for encoding ops. 256 mode will require permuting more often than 128 mode, as it won't have as much input capacity before its input buffer is exhausted. -Ops are tracked with a stack, with a max of 4 ops being "stacked" before a permutation must occur. When a permutation starts, the ops encoding block is selected (position block + 1) and then it is XOR'd with the list of op bits on the \[0..4\] part of the block, going from first op to last, with the \[4..8\] part of the block XOR'd with the ops count, the block position on the first bytes, with then `0x80` & `0` on the last bytes. This creates the start of the padding structure. The padding terminator is then XOR'd on the last byte of the reserved block with a `0x80` value that is rotated by the position counter. If the input fills the buffer completely, the position+1 and reserved block are the same, so the combined XOR'd blocks will form a single block construction. The permutation is then executed with the f1600 function, after which the block & ops counters are reset along with the ops stack. +Ops are tracked with a stack, with a max of 4 ops being "stacked" before a permutation must occur. When a permutation starts, the ops encoding block is selected (position block + 1) and then it is XOR'd with the list of op bits on the \[0..4\] part of the block, going from first op to last, with the \[4..8\] part of the block XOR'd with the ops count, the block position on the first bytes, with then `0x80` & `0` on the last bytes. This creates the start of the padding structure. The padding terminator is then XOR'd on the last byte of the reserved block with a `0x80` value that is rotated by the position counter. If the input fills the buffer completely, the position+1 and reserved block are the same, so the combined XOR'd blocks will form a single block construction. The permutation is then executed with the p1600 function with 12 rounds (KangarooTwelve), after which the block & ops counters are reset along with the ops stack. After the permutation concludes, the op which triggered the permutation is then encoded into the stack. There are two ways a permutation is invoked: via a user OP, or from a *continuation* for ingesting more data. In the case of a user op, the counter is set to zero, and the stack fully zeroed so the op can encode its flags onto the first slot when it begins. In the case of a *continuation*, the counter is set to `1`, and the first slot is encoded with the `CONT` flag bits with the rest of the slots zeroed. This ensures that in **every** case, there will always be 3 remaining free slots to form a 4 op chain. @@ -90,7 +90,7 @@ Creating a new Neko State instance is qualified as an INIT operation. This means Then, we must encode the preamble & NEKO version onto the state buffer. The preamble is defined as `[0x01, RATE, 0x07, 0x60]`. The `RATE` is calculated as `(200 - SecLevel / 4) / 8 - 1` and encoded as a `u8` value. So for `Neko128`, the `RATE` should resolve to `20`, and `Neko256` should resolve to `16`. These represent the max buffer position that input data can be absorbed into before needing to permute. -The NEKO version string is then concatenated to the preamble. For version v0.2 of this specification, the string is `NEKOv0.2.0`, and it should be concatenated as a byte string. Then the combined preamble+version bytes should be written to the buffer in an `OVERWRITE` action. +The NEKO version string is then concatenated to the preamble. For version v0.2.1 of this specification, the string is `NEKOv0.2.1`, and it should be concatenated as a byte string. Then the combined preamble+version bytes should be written to the buffer in an `OVERWRITE` action. Additionally, a protocol byte string can be written to the state, following after the preamble+version with its own `OVERWRITE` action. @@ -114,3 +114,13 @@ With an initialised Neko state, the following operations are available to the us All user operations follow a chain of 4 ops. Non-permuting ops can *stack*, so they add to the stack if their inputs don't cause the state to permute. Permuting ops always *reset* the stack, as they permute the state. When the stack resets due to an op, the stack is cleared and the op that triggered the reset is encoded into the first slot. `INIT` is always the very first op, so `KEY` + `NONCE` + `AD` can be added as ops without triggering a permutation. If another non-permuting op were to be chained at this point (like `CLR`), this would cause a panic. To resolve this, call a permuting op like `ENC` or `RATCHET`, and the stack is reset to be just the permuting op on the stack, with three more free slots. A panic is a must, because any occasion that we are going over 4 chained ops is a misuse of the protocol and thus MUST fail quickly. Under normal usage, no sequence of ops should cause a chain of more than 4 to occur, and with large enough payloads, the state would be getting permuted enough to ensure this is not required. + +## Changes + +### v0.2 + +Initial publication and base specification. + +### v0.2.1 + +Changed from f1600 to p1600 with 12 rounds for Keccak permutation function, and introduced Neko192 (192-bit) strength. diff --git a/wharrgarbl-neko/src/kats.rs b/wharrgarbl-neko/src/kats.rs index 1de0c21..a0bb08a 100644 --- a/wharrgarbl-neko/src/kats.rs +++ b/wharrgarbl-neko/src/kats.rs @@ -1,7 +1,7 @@ use hybrid_array::Array; use zerocopy::IntoBytes; -use crate::{Neko128, Neko256, NekoState}; +use crate::{Neko128, Neko192, Neko256, NekoState}; extern crate alloc; @@ -15,7 +15,23 @@ fn neko_128_init_state() { assert_eq!(&first, b"\x01\x14\x07\x60NEKO"); // Values that don't fill the block entirely leave padding - assert_eq!(&second, b"v0.2.0\0\0"); + assert_eq!(&second, b"v0.2.1\0\0"); + assert_eq!(&third[..4], b"test"); + // The rest of the state is zeroed + assert_eq!(&neko.state[3..], &[0; 22]); +} + +#[test] +fn neko_192_init_state() { + let neko = NekoState::::new(b"test"); + + let first = neko.state[0].to_le_bytes(); + let second = neko.state[1].to_le_bytes(); + let third = neko.state[2].to_le_bytes(); + + assert_eq!(&first, b"\x01\x12\x07\x60NEKO"); + // Values that don't fill the block entirely leave padding + assert_eq!(&second, b"v0.2.1\0\0"); assert_eq!(&third[..4], b"test"); // The rest of the state is zeroed assert_eq!(&neko.state[3..], &[0; 22]); @@ -31,7 +47,7 @@ fn neko_256_init_state() { assert_eq!(&first, b"\x01\x10\x07\x60NEKO"); // Values that don't fill the block entirely leave padding - assert_eq!(&second, b"v0.2.0\0\0"); + assert_eq!(&second, b"v0.2.1\0\0"); assert_eq!(&third[..4], b"test"); // The rest of the state is zeroed assert_eq!(&neko.state[3..], &[0; 22]); @@ -114,29 +130,29 @@ fn non_cipher_flag_ops_dont_permute_by_default() { let expected_state = [ 0x0000000000000000, 0x0000000000000000, - 0x14fd15236a301dbc, - 0x3d7a0f031c2332c7, - 0x13d95db32a39a74c, - 0xbfce1f9678690375, - 0xc444bd0f9bb70133, - 0x59600201db93b1de, - 0x6bc376b646e898ea, - 0x2e8a6c345fd3dca3, - 0x9df94788a5fc9f4d, - 0x2541272cca7a631c, - 0xabc8b248a4e0eee3, - 0x2a6befaf570b0120, - 0x5e296ccc9b587798, - 0x9b9d5caef6fc7d3c, - 0x371099e20d7965db, - 0x52b7fecf8d06aed7, - 0xae285d1c6cada2c7, - 0x12d17a37884449ea, - 0x85846b16d640a55b, - 0x0e7d16c0c2bf5a3e, - 0xce32132c0b110014, - 0x6620fda4f7642f84, - 0xd1ea97aadb49a663, + 0xd3c9627ab3f60112, + 0xf9bc5a3ce86c0308, + 0x1b649c672f8291e7, + 0x348b76389636d1c5, + 0x7e7b242854a89160, + 0xc588e1bab9fff3f3, + 0x6869595e613dce2f, + 0x21aa5dd9c8ace1ed, + 0x976ac27c1542f2e3, + 0x271c24a505720c01, + 0x1cf4dbfd172716ec, + 0x5e338536048f69cd, + 0x198c6a958d8215a6, + 0x7e181ad612b4ec51, + 0xd3c7adc0e13f29fd, + 0x92adbe76b85f49a9, + 0xc05147b39c222c68, + 0xea1f4797623a1431, + 0x4d837d8b8ef79878, + 0x59b03ae6c5f3c16f, + 0x2b5da88884b6b1d9, + 0x04ecf618b84acb0a, + 0x58ae3cfc3b9574c2, ]; assert_eq!(&neko.state, &expected_state); @@ -187,31 +203,31 @@ fn cipher_ops_permute_state_by_default() { assert_eq!(neko.state[0..2].as_bytes(), &message); let expected_state = [ - 0x33e5964098e69bb2, - 0xe8aae76360864f1d, - 0x6c10b3c273ae582c, - 0xd9584d46c8025d46, - 0x8eeace52fffacd4c, - 0x2346ce9726155884, - 0x0f3427af0a3c77f1, - 0xe2706ecbbd9596b4, - 0x840b7500b73e537c, - 0x0015960758c2e30e, - 0xf2cd5efad521e8e2, - 0xca7199cf34822634, - 0xe21f1c3744135b1a, - 0xe91599f57a74f2c9, - 0x1395bb13bd8eec8d, - 0x8417dd11dfee0671, - 0x95d9c20086520a10, - 0x90cfb46fc5a4963d, - 0x2aaf5cd4d234a06d, - 0x5e4372caf96bd84a, - 0x6a858536f819bb62, - 0xf7f33ca323c59700, - 0x38b5d9a41b4d08e1, - 0x39c33af857ae9a82, - 0x39ed20d798ecd321, + 0x376ff3f6beb5164d, + 0x6fce4cdd41481b09, + 0x62c9980b6ebd4375, + 0x35bebdd63cbae3f2, + 0xe82c6eed7a9482b1, + 0xe3948f44d30e1b63, + 0x64f3fbd74d1485a9, + 0xe3a5c716bab805e0, + 0xdb50cee154ae7634, + 0xc5f16a574d98aaa0, + 0xa701afa0ce5e483a, + 0xffdb8ceedc0e2137, + 0x1ced87c9b390ad78, + 0xc066d80fecc4e712, + 0x4d8d46e5f5972a6d, + 0xa948bf5cb8e4442f, + 0x1f08d0ca81e27400, + 0x2234e5f1e79cc913, + 0x4238eb75cde4fa79, + 0xe163927593ef0bfa, + 0x1665d19a25c4a420, + 0x3ec458a9b98e00cb, + 0xf19ee10721f39c29, + 0x96f715bbe8f84a73, + 0xaec74c90f467207c, ]; assert_eq!(&neko.state, &expected_state); @@ -223,34 +239,89 @@ fn cipher_ops_permute_state_by_default() { let ratched_expected_state = [ 0x0000000000000000, 0x0000000000000000, - 0xe72010d5d3b254c0, - 0x34007830a1c7585d, - 0xbcd95dec900847a5, - 0xfe1be2676e130078, - 0xe6c29c4c48f292e6, - 0x3d711aed9763e259, - 0xa9b1329692f19ebd, - 0xf1378893d98ad184, - 0xe6f31bb95f5c361f, - 0x549decbceeac0f78, - 0x81b85f3f3d3a687d, - 0x7dac55db9b73bf34, - 0x6f07454e89ec5950, - 0x9abd19c6e33eec92, - 0x7358043c28de6955, - 0x625421243d6b4bd5, - 0xc986349494886128, - 0xc00e8e52d7734dff, - 0xbafa4f2b57d93144, - 0x022f1aa724503cd5, - 0x4b3633798cc9ae5e, - 0x532b723068ab8c72, - 0xa48327750108017c, + 0x01e23e724c12db57, + 0xe92a5c3fae8b582d, + 0x36454900c0add829, + 0x225646c8528ce4ff, + 0xe0cf79fd5e3e495a, + 0x77aed0a3813ef760, + 0xcbc0aa13baee85be, + 0x3fd706b857c5e671, + 0xfcbe3c0cefddfc6d, + 0xf8d1978f52c0d7e0, + 0x06c874e792fd7180, + 0xa6b978b38814727b, + 0x412d8e5666bde321, + 0x29e578d4ed104740, + 0x17b53fbaf1257b55, + 0x24cc8a75a308d641, + 0x3345c778c83c4882, + 0x1ea9692aff46faf8, + 0x68ce75a36d554dbc, + 0xe1faa52728b78408, + 0xdcabac6ec8e018e4, + 0xc631647d96ed3f06, + 0x8e29b59ab6a8956b, ]; assert_eq!(&neko.state, &ratched_expected_state); // The rest of the non-zeroed state should not match the previous state assert_ne!(&expected_state[2..], &ratched_expected_state[2..]); + + let large_message = r#"Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Ut augue lectus, rhoncus a pulvinar ut, lacinia non est. +Pellentesque imperdiet ornare blandit. Mauris dictum mollis blandit. +Ut a arcu tincidunt, ultricies arcu sed, auctor erat. +Nunc dignissim hendrerit porttitor. Nunc fermentum mi sed viverra euismod. +Cras vel diam tortor. Morbi scelerisque augue eget elit ultrices suscipit. +Nunc varius arcu sit amet neque faucibus, id iaculis ex porta. +Nullam non neque nec neque faucibus sollicitudin. +Phasellus eget ultrices purus. Aenean tincidunt nisl mi, vel tincidunt ante pretium eu. +In scelerisque, ex et porta varius, orci risus malesuada nibh, convallis euismod nibh ipsum non turpis."#; + + let mut large_encrypted_message = large_message.as_bytes().to_vec(); + + neko.encrypt(&mut large_encrypted_message); + + let expected_state = [ + 0x13412b65f7e20af3, + 0x6d3424b086abd336, + 0xcb9fc2f09e70d9a0, + 0x88c998c81951d0c2, + 0x059e869c2f7a61ce, + 0xc3659823ee130ee2, + 0xaa59c8ff1d95842f, + 0x940740fc352b4fae, + 0xdbd1854b5f012452, + 0xe14d604523a7c4b1, + 0x4a1a2305128b2afa, + 0xec94592e37b13bd9, + 0x2acce9aec73ec364, + 0x73324f4034356ff2, + 0x563ae980c6a2e903, + 0xdf6491d84e9a29dc, + 0xd86c5e19f7f243ca, + 0x18e7a1523d271264, + 0x41f808f2bb8d7c2c, + 0xfeea3498ca40ba48, + 0xb304f29eb1df2f33, + 0xce55d8a83bba04a4, + 0x452613733fbc50df, + 0xe137b9f22560f2d0, + 0xb12bb41da4aa156e, + ]; + + assert_eq!(&neko.state, &expected_state); + assert_ne!(large_message.as_bytes(), &large_encrypted_message); + + let tag = neko.create_mac(); + + let expected_tag: [u8; 16] = [ + 0x9b, 0x89, 0x06, 0xea, 0x70, 0xec, 0x90, 0xc1, 0x9e, 0x47, 0x62, 0xd7, 0x52, 0xcb, 0x0d, + 0xaa, + ]; + + assert_eq!(&tag, &expected_tag); } #[test] diff --git a/wharrgarbl-neko/src/lib.rs b/wharrgarbl-neko/src/lib.rs index 77a9f37..35d87f6 100644 --- a/wharrgarbl-neko/src/lib.rs +++ b/wharrgarbl-neko/src/lib.rs @@ -1,5 +1,4 @@ #![no_std] -#![forbid(unsafe_code)] mod flags; #[cfg(test)] @@ -13,7 +12,7 @@ use core::marker::PhantomData; use aead::{ KeySizeUser, common::IvSizeUser, - consts::{U4, U10, U16, U25, U32, U128, U256}, + consts::{U4, U10, U16, U25, U32, U128, U192, U256}, }; use ctutils::CtEq; use hybrid_array::Array; @@ -24,12 +23,13 @@ use crate::operators::{NekoOperate, NekoOperateMut}; pub use crate::traits::NekoSec; pub type Neko128 = U128; +pub type Neko192 = U192; pub type Neko256 = U256; pub type NekoNonce = Array as IvSizeUser>::IvSize>; pub type NekoKey = Array as KeySizeUser>::KeySize>; pub type NekoTag = Array; -pub static NEKO_VERSION: &str = "NEKOv0.2.0"; +pub static NEKO_VERSION: &str = "NEKOv0.2.1"; const U64_CHUNK: usize = core::mem::size_of::(); const MAX_OPS: usize = core::mem::size_of::(); @@ -76,9 +76,14 @@ impl NekoState { /// /// let neko = NekoState::::new(b"whimsical"); /// - /// assert_eq!(format!("{neko}"), "NEKOv0.2.0/1600-128"); + /// assert_eq!(format!("{neko}"), "NEKOv0.2.1/1600-128"); /// ``` pub fn new(protocol: &[u8]) -> Self { + const { + assert!(Sec::BLOCK_RATE < keccak::PLEN); + assert!(Sec::BLOCK_RATE < u8::MAX as usize); + }; + // OPS stack MUST be initialised with the INIT flag as the first op. let ops_stack = [ops::INIT.bits(), 0, 0, 0]; @@ -95,7 +100,7 @@ impl NekoState { // Preamble is defined with 0x01 as the first byte, the RATE as the second byte // and then 0x07 & 0x60 as the third & fourth byte. - let preamble: Array = Array::from([0x01, Sec::rate() as u8, 0x07, 0x60]); + let preamble: Array = Array::from([0x01, Sec::BLOCK_RATE as u8, 0x07, 0x60]); // This is safe because the specification version string is always 10 bytes long. let version: Array = Array::try_from(NEKO_VERSION.as_bytes()).unwrap(); @@ -114,6 +119,45 @@ impl NekoState { neko } + #[inline(always)] + #[must_use] + fn block(&self) -> usize { + let block = usize::from(self.raw_position()).div_ceil(U64_CHUNK); + debug_assert!(block <= Sec::BLOCK_RATE); + if block <= Sec::BLOCK_RATE { + block + } else { + // SAFETY: the type enforces that `block` is always smaller than `RATE` + unsafe { core::hint::unreachable_unchecked() }; + } + } + + #[inline(always)] + #[must_use] + fn raw_position(&self) -> u8 { + debug_assert!(self.position < u8::MAX as usize && self.position <= Sec::POS_RATE); + if self.position < u8::MAX as usize && self.position <= Sec::POS_RATE { + self.position as u8 + } else { + // SAFETY: the type enforces that `position` is always smaller than + // `RATE * U64_CHUNK` & `u8::MAX` + unsafe { core::hint::unreachable_unchecked() }; + } + } + + #[inline(always)] + fn advance_position(&mut self, advance: usize) { + let updated = self.position + advance; + assert!(updated <= Sec::POS_RATE); + self.position = updated; + } + + #[inline(always)] + #[must_use] + fn should_permute(&self) -> bool { + self.raw_position() == Sec::POS_RATE as u8 + } + #[inline] #[track_caller] fn begin_op(&mut self, red_flags: OpFlags) { @@ -132,10 +176,15 @@ impl NekoState { self.ops_stack[op_index] = red_flags.bits(); } - fn permutation_f(&mut self, continuation: OpFlags) { + fn permutation_p12(&mut self, continuation: OpFlags) { + const { + assert!(Sec::BLOCK_RATE < keccak::PLEN); + assert!(Sec::BLOCK_RATE < u8::MAX as usize); + }; + // Last byte is zeroed in case the terminator overlaps let permuter: Array = - Array([self.ops_count as u8, self.position as u8, 0x80u8.to_le(), 0]); + Array([self.ops_count as u8, self.raw_position(), 0x80u8.to_le(), 0]); let permuter_block = u64::from_ne_bytes(self.ops_stack.concat(permuter).0); @@ -144,11 +193,11 @@ impl NekoState { self.state[self.position.div_ceil(U64_CHUNK) + 1] ^= permuter_block; // Flip a bit in the last byte of the first entropy block with a 1 to act as the padding terminator. // The bit is selected via rotating right the value 0x80 (0b1000_0000) by the position counter. - self.state[Sec::rate()].as_mut_bytes()[7] ^= + self.state[Sec::BLOCK_RATE].as_mut_bytes()[7] ^= 0x80u8.to_le().rotate_right(self.position as u32); - // The state has been fully prepared, and now can be permuted by the F1600 function. - keccak::Keccak::new().with_f1600(|permute| permute(&mut self.state.0)); + // The state has been fully prepared, and now can be permuted by the p1600(12) function. + keccak::Keccak::new().with_p1600::<12>(|permute| permute(&mut self.state.0)); // Reset the state, zeroing all counters/stack unless a CONTINUATION, in which case // ops count is set to 1 and the first op slot is encoded with 0x01. @@ -159,10 +208,15 @@ impl NekoState { #[inline] fn zero_state(&mut self) { + const { + assert!(Sec::RATCHET < keccak::PLEN); + assert!(Sec::RATCHET < u8::MAX as usize); + }; // Select the amount of bytes to zero, according to Security level // 128 bits = 16 bytes to zero out to achieve forward secrecy + // 192 bits = 24 bytes to zero out to achieve forward secrecy // 256 bits = 32 bytes to zero out to achieve forward secrecy - let ratchet_bytes = Sec::ratchet_bytes(); + let ratchet_bytes = Sec::RATCHET; self.state[0..ratchet_bytes].iter_mut().for_each(|block| { *block = 0; @@ -203,7 +257,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn prf(&mut self, data: &mut [u8]) { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::PRF); @@ -215,7 +269,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn create_mac(&mut self) -> NekoTag { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::MAC); @@ -232,7 +286,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn verify_mac(&mut self, data: &NekoTag) -> aead::Result<()> { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::MAC); @@ -256,7 +310,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn encrypt(&mut self, data: &mut [u8]) { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::ENC); @@ -267,7 +321,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn decrypt(&mut self, data: &mut [u8]) { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::ENC); @@ -290,7 +344,7 @@ impl NekoState { /// /// **This is a PERMUTING operation** pub fn ratchet(&mut self) { - self.permutation_f(ops::RST); + self.permutation_p12(ops::RST); self.begin_op(ops::RATCHET); @@ -327,10 +381,10 @@ mod tests { let display = std::format!("{s}"); let debug = std::format!("{s:?}"); - assert_eq!(&display, "NEKOv0.2.0/1600-128"); + assert_eq!(&display, "NEKOv0.2.1/1600-128"); assert_eq!( &debug, - "NekoState { sec: 128, version: \"NEKOv0.2.0\", .. }" + "NekoState { sec: 128, version: \"NEKOv0.2.1\", .. }" ); } } diff --git a/wharrgarbl-neko/src/operators.rs b/wharrgarbl-neko/src/operators.rs index 18e84df..09f6d9d 100644 --- a/wharrgarbl-neko/src/operators.rs +++ b/wharrgarbl-neko/src/operators.rs @@ -1,6 +1,6 @@ use zerocopy::IntoBytes; -use crate::{NekoSec, NekoState, U64_CHUNK, ops}; +use crate::{NekoSec, NekoState, ops}; pub(crate) struct NekoOperateMut<'s, S: NekoSec> { neko: &'s mut NekoState, @@ -15,25 +15,30 @@ impl<'s, S: NekoSec> NekoOperateMut<'s, S> { #[inline(always)] fn operate_mut(&'s mut self, operation: fn((&mut u8, &mut u8))) { - loop { + const { + assert!(S::BLOCK_RATE < keccak::PLEN); + assert!(S::BLOCK_RATE < u8::MAX as usize); + }; + + while !self.data.is_empty() { + if self.neko.should_permute() { + self.neko.permutation_p12(ops::CONT); + } + + let block = self.neko.block(); + // Trans the neko - let transed_bytes = - self.neko.state[self.neko.position.div_ceil(U64_CHUNK)..S::rate()].as_mut_bytes(); + let transed_bytes = self.neko.state[block..S::BLOCK_RATE].as_mut_bytes(); - let take = transed_bytes + let advanced = transed_bytes .iter_mut() .zip(self.data.iter_mut()) .map(operation) .count(); - self.data = &mut self.data[take..]; + self.data = &mut self.data[advanced..]; - if !self.data.is_empty() { - self.neko.permutation_f(ops::CONT); - } else { - self.neko.position += take; - break; - } + self.neko.advance_position(advanced); } } @@ -80,25 +85,30 @@ impl<'s, S: NekoSec> NekoOperate<'s, S> { #[inline(always)] fn operate(&'s mut self, operation: fn((&mut u8, &u8))) { - loop { + const { + assert!(S::BLOCK_RATE < keccak::PLEN); + assert!(S::BLOCK_RATE < u8::MAX as usize); + }; + + while !self.data.is_empty() { + if self.neko.should_permute() { + self.neko.permutation_p12(ops::CONT); + } + + let block = self.neko.block(); + // Trans the neko - let transed_bytes = - self.neko.state[self.neko.position.div_ceil(U64_CHUNK)..S::rate()].as_mut_bytes(); + let transed_bytes = self.neko.state[block..S::BLOCK_RATE].as_mut_bytes(); - let take = transed_bytes + let advanced = transed_bytes .iter_mut() .zip(self.data) .map(operation) .count(); - self.data = &self.data[take..]; + self.data = &self.data[advanced..]; - if !self.data.is_empty() { - self.neko.permutation_f(ops::CONT); - } else { - self.neko.position += take; - break; - } + self.neko.advance_position(advanced); } } diff --git a/wharrgarbl-neko/src/traits.rs b/wharrgarbl-neko/src/traits.rs index 6c089c5..9b4f76d 100644 --- a/wharrgarbl-neko/src/traits.rs +++ b/wharrgarbl-neko/src/traits.rs @@ -1,19 +1,32 @@ -use aead::consts::{U128, U200, U256}; +use aead::consts::{U128, U192, U200, U256}; use hybrid_array::typenum::Unsigned; -pub trait NekoSec: Unsigned { - fn to_bytes() -> [u8; 2] { - Self::U16.to_le_bytes() - } +use crate::U64_CHUNK; - fn ratchet_bytes() -> usize { - Self::USIZE.wrapping_shr(6) - } +pub trait NekoSec: Unsigned { + const BLOCK_RATE: usize; + const POS_RATE: usize; + const RATCHET: usize; + const BYTES: [u8; 2]; +} - fn rate() -> usize { - (U200::USIZE - Self::USIZE / 4) / 8 - 1 - } +macro_rules! impl_nekosec_for { + ($($type:ident)+) => { + $( + impl NekoSec for $type { + const BLOCK_RATE: usize = calc_rate(Self::USIZE); + const POS_RATE: usize = Self::BLOCK_RATE * U64_CHUNK; + const BYTES: [u8; 2] = Self::U16.to_le_bytes(); + const RATCHET: usize = Self::USIZE.wrapping_shr(6); + } + )* + }; } -impl NekoSec for U128 {} -impl NekoSec for U256 {} +impl_nekosec_for!(U128 U192 U256); + +const fn calc_rate(sec: usize) -> usize { + let rate = (U200::USIZE - sec / 4) / 8 - 1; + assert!(rate < keccak::PLEN && rate < u8::MAX as usize); + rate +}