From 43d589c32d1cc0f6fab9f390db3faa77fd8561b6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:50:12 -0600 Subject: [PATCH] Run WinZip AES-CTR on the processor's AES instructions zipview no longer forbids unsafe: its inflate backend already relies on it, and the processor's AES instructions need it. src/accel.rs runs the CTR keystream on ARMv8 AES (AESE/AESMC) or x86 AES-NI (AESENC/AESENCLAST), eight counter blocks at a time so the AES unit never waits on a single block, after checking for the instructions at run time; without them the T-table code runs as before. The unsafe is limited to that module's intrinsic calls and 16-byte loads and stores, each with a SAFETY comment, which clippy::undocumented_unsafe_blocks now requires. rust-version goes to 1.87, where intrinsics are safe to call inside a target_feature function. The reference test now checks both the public function and the portable path. AES-128-CTR: M4 921 -> 13984 MB/s, M5 415 -> 6386, i7-8700K 241 -> 2449. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 2 +- README.md | 10 ++- src/accel.rs | 204 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 34 +++++++-- 4 files changed, 237 insertions(+), 13 deletions(-) create mode 100644 src/accel.rs diff --git a/Cargo.toml b/Cargo.toml index 59b5e60..701125c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "zipview" version = "0.1.0" edition = "2024" -rust-version = "1.85" +rust-version = "1.87" authors = ["zipview contributors"] license = "GPL-3.0" description = "Read-only, allocation-bounded ZIP container reader. No extraction, no writing, no filesystem access." diff --git a/README.md b/README.md index a2a495b..eaf00f9 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,12 @@ the one part of this problem where a subtle bug is both likely and hard to find. It runs on the `zlib-rs` backend, a Rust port of zlib, for speed: it inflates 2.3–2.6× faster than flate2's default `miniz_oxide` on Apple M4/M5 cores. -`#![forbid(unsafe_code)]`. Every field is read through bounds-checked helpers, so -a truncated or hostile archive yields `Err`, never a panic. That covers this -crate's own code: `zlib-rs` uses `unsafe` internally for its SIMD paths, which -`miniz_oxide` does not. +Every field is read through bounds-checked helpers, so a truncated or hostile +archive yields `Err`, never a panic. Parsing has no `unsafe`. The crate's only +`unsafe` is in `src/accel.rs`, which runs the processor's AES instructions +(ARMv8 AES, x86 AES-NI) after checking for them at run time; without them the +portable table-driven code runs, and the tests hold both to the same reference. +`zlib-rs` uses `unsafe` internally for its SIMD paths too. - **The central directory is the only source of sizes and offsets.** Local headers are checked for their signature and nothing else: a streamed entry diff --git a/src/accel.rs b/src/accel.rs new file mode 100644 index 0000000..06a5b8e --- /dev/null +++ b/src/accel.rs @@ -0,0 +1,204 @@ +// zipview -- read-only ZIP container reader +// Copyright (C) 2026 zipview contributors +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along +// with this program. If not, see . + +//! The processor's own AES instructions, where it has them. +//! +//! This is the crate's only `unsafe`: calling an instruction the compiler +//! cannot assume the processor has, and reading and writing whole 16-byte +//! words of a buffer. Every entry point checks for the instructions at run +//! time and returns `false` without them, so the caller falls back to the +//! portable code, which the tests hold to the same reference. + +/// XORs `data` with the WinZip AES-CTR keystream, whose little-endian counter +/// starts at one, under the expanded key `rk` of `nr` rounds, using the +/// processor's AES instructions. `false`, with `data` untouched, when it has +/// none. +pub(crate) fn aes_ctr_xor(rk: &[u32; 60], nr: usize, data: &mut [u8]) -> bool { + imp::aes_ctr_xor(rk, nr, data) +} + +/// The round keys as the 16-byte blocks the instructions take: each round's +/// four big-endian words in order. +#[cfg_attr( + not(any(target_arch = "aarch64", target_arch = "x86_64")), + allow(dead_code) +)] +fn key_bytes(rk: &[u32; 60]) -> [[u8; 16]; 15] { + let mut out = [[0u8; 16]; 15]; + for (block, words) in out.iter_mut().zip(rk.chunks_exact(4)) { + for (bytes, w) in block.chunks_exact_mut(4).zip(words) { + bytes.copy_from_slice(&w.to_be_bytes()); + } + } + out +} + +/// How many counter blocks go through the rounds together. An AES round +/// instruction takes a few cycles to finish but a new one can start every +/// cycle, so eight independent blocks keep the unit busy. +#[cfg_attr( + not(any(target_arch = "aarch64", target_arch = "x86_64")), + allow(dead_code) +)] +const LANES: usize = 8; + +#[cfg(target_arch = "aarch64")] +mod imp { + use super::{LANES, key_bytes}; + use std::arch::aarch64::*; + + pub(super) fn aes_ctr_xor(rk: &[u32; 60], nr: usize, data: &mut [u8]) -> bool { + if !std::arch::is_aarch64_feature_detected!("aes") { + return false; + } + let keys = key_bytes(rk); + // SAFETY: the processor has the AES instructions (checked above), and + // NEON is part of every 64-bit ARM processor + unsafe { + match nr { + 10 => run::<10>(&keys, data), + 12 => run::<12>(&keys, data), + _ => run::<14>(&keys, data), + } + } + true + } + + /// `AESE` is AddRoundKey, SubBytes and ShiftRows, and `AESMC` is + /// MixColumns, so a round is the pair; the last round has no MixColumns + /// and adds the final key on its own. + #[target_feature(enable = "aes,neon")] + unsafe fn run(keys: &[[u8; 16]; 15], data: &mut [u8]) { + let rk: [uint8x16_t; 15] = std::array::from_fn(|r| { + // SAFETY: reads the 16 bytes of `keys[r]` + unsafe { vld1q_u8(keys[r].as_ptr()) } + }); + let block = |counter: u128| -> uint8x16_t { + let b = counter.to_le_bytes(); + // SAFETY: reads the 16 bytes of `b` + unsafe { vld1q_u8(b.as_ptr()) } + }; + let mut counter = 1u128; + let mut groups = data.chunks_exact_mut(16 * LANES); + for group in &mut groups { + let mut s: [uint8x16_t; LANES] = + std::array::from_fn(|i| block(counter.wrapping_add(i as u128))); + counter = counter.wrapping_add(LANES as u128); + for key in &rk[..NR - 1] { + for b in &mut s { + *b = vaesmcq_u8(vaeseq_u8(*b, *key)); + } + } + for (i, b) in s.iter().enumerate() { + let ks = veorq_u8(vaeseq_u8(*b, rk[NR - 1]), rk[NR]); + let p = group[16 * i..].as_mut_ptr(); + // SAFETY: `group` holds LANES blocks of 16 bytes, so the 16 + // at `p` are inside it + unsafe { vst1q_u8(p, veorq_u8(vld1q_u8(p), ks)) }; + } + } + for chunk in groups.into_remainder().chunks_mut(16) { + let mut b = block(counter); + counter = counter.wrapping_add(1); + for key in &rk[..NR - 1] { + b = vaesmcq_u8(vaeseq_u8(b, *key)); + } + let ks = veorq_u8(vaeseq_u8(b, rk[NR - 1]), rk[NR]); + let mut bytes = [0u8; 16]; + // SAFETY: writes the 16 bytes of `bytes` + unsafe { vst1q_u8(bytes.as_mut_ptr(), ks) }; + for (c, k) in chunk.iter_mut().zip(bytes) { + *c ^= k; + } + } + } +} + +#[cfg(target_arch = "x86_64")] +mod imp { + use super::{LANES, key_bytes}; + use std::arch::x86_64::*; + + pub(super) fn aes_ctr_xor(rk: &[u32; 60], nr: usize, data: &mut [u8]) -> bool { + if !std::arch::is_x86_feature_detected!("aes") { + return false; + } + let keys = key_bytes(rk); + // SAFETY: the processor has AES-NI (checked above), and SSE2 is part + // of every x86-64 processor + unsafe { + match nr { + 10 => run::<10>(&keys, data), + 12 => run::<12>(&keys, data), + _ => run::<14>(&keys, data), + } + } + true + } + + /// `AESENC` is a whole round (ShiftRows, SubBytes, MixColumns, + /// AddRoundKey) and `AESENCLAST` the last one, without MixColumns. + #[target_feature(enable = "aes,sse2")] + unsafe fn run(keys: &[[u8; 16]; 15], data: &mut [u8]) { + let rk: [__m128i; 15] = std::array::from_fn(|r| { + // SAFETY: reads the 16 bytes of `keys[r]`; loadu needs no alignment + unsafe { _mm_loadu_si128(keys[r].as_ptr().cast()) } + }); + // the counter's low 64 bits are its first eight bytes, as stored + let block = |counter: u128| _mm_set_epi64x((counter >> 64) as i64, counter as i64); + let mut counter = 1u128; + let mut groups = data.chunks_exact_mut(16 * LANES); + for group in &mut groups { + let mut s: [__m128i; LANES] = std::array::from_fn(|i| { + _mm_xor_si128(block(counter.wrapping_add(i as u128)), rk[0]) + }); + counter = counter.wrapping_add(LANES as u128); + for key in &rk[1..NR] { + for b in &mut s { + *b = _mm_aesenc_si128(*b, *key); + } + } + for (i, b) in s.iter().enumerate() { + let ks = _mm_aesenclast_si128(*b, rk[NR]); + let p = group[16 * i..].as_mut_ptr().cast::<__m128i>(); + // SAFETY: `group` holds LANES blocks of 16 bytes, so the 16 + // at `p` are inside it; loadu and storeu need no alignment + unsafe { _mm_storeu_si128(p, _mm_xor_si128(_mm_loadu_si128(p), ks)) }; + } + } + for chunk in groups.into_remainder().chunks_mut(16) { + let mut b = _mm_xor_si128(block(counter), rk[0]); + counter = counter.wrapping_add(1); + for key in &rk[1..NR] { + b = _mm_aesenc_si128(b, *key); + } + let ks = _mm_aesenclast_si128(b, rk[NR]); + let mut bytes = [0u8; 16]; + // SAFETY: writes the 16 bytes of `bytes` + unsafe { _mm_storeu_si128(bytes.as_mut_ptr().cast(), ks) }; + for (c, k) in chunk.iter_mut().zip(bytes) { + *c ^= k; + } + } + } +} + +#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] +mod imp { + pub(super) fn aes_ctr_xor(_: &[u32; 60], _: usize, _: &mut [u8]) -> bool { + false + } +} diff --git a/src/lib.rs b/src/lib.rs index 41224a0..51d4481 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,8 +53,10 @@ //! //! Every field is read through bounds-checked helpers, so a truncated or //! hostile archive yields `Err`, never a panic or an out-of-bounds read. -//! There is no `unsafe` in this crate. Inflation is done by `flate2` on its -//! `zlib-rs` backend, which does use `unsafe` internally, for speed. +//! Parsing has no `unsafe`. The only `unsafe` in the crate is in `accel`, +//! which runs the processor's own AES instructions where it has them, checked +//! for at run time, with the portable code as the fallback. Inflation is done +//! by `flate2` on its `zlib-rs` backend, which also uses `unsafe`, for speed. //! //! - The central directory is the single source of truth for sizes and //! offsets. Local headers are checked only for their signature; their size @@ -110,8 +112,10 @@ //! because a reader that parsed headers safely but trusted the payload offset //! would pass an enumeration-only target. -#![forbid(unsafe_code)] -#![warn(missing_docs)] +#![deny(unsafe_op_in_unsafe_fn)] +#![warn(missing_docs, clippy::undocumented_unsafe_blocks)] + +mod accel; use std::borrow::Cow; @@ -1472,14 +1476,22 @@ fn aes_encrypt( pub fn decrypt_winzip_ctr(key: &[u8], ciphertext: &[u8]) -> Option> { let (rk, nr) = aes_expand_key(key)?; let mut out = ciphertext.to_vec(); - match nr { - 10 => ctr_xor::<10>(&rk, &mut out), - 12 => ctr_xor::<12>(&rk, &mut out), - _ => ctr_xor::<14>(&rk, &mut out), + if !accel::aes_ctr_xor(&rk, nr, &mut out) { + ctr_xor_portable(&rk, nr, &mut out); } Some(out) } +/// [`ctr_xor`] for a key of `nr` rounds: the keystream from table lookups, for +/// processors without AES instructions. +fn ctr_xor_portable(rk: &[u32; 60], nr: usize, data: &mut [u8]) { + match nr { + 10 => ctr_xor::<10>(rk, data), + 12 => ctr_xor::<12>(rk, data), + _ => ctr_xor::<14>(rk, data), + } +} + /// How many counter blocks CTR encrypts side by side. Two keep the 64-bit ARM /// cores' load units busy (Apple M4/M5: two run 13% faster than four, 50% /// faster than one). x86-64's sixteen registers can't hold more than one @@ -2134,6 +2146,12 @@ mod tests { want, "key {key_len}" ); + // The table-driven keystream too, which processors with AES + // instructions never run through the public function. + let (rk, nr) = aes_expand_key(&key).unwrap(); + let mut portable = data.clone(); + ctr_xor_portable(&rk, nr, &mut portable); + assert_eq!(portable, want, "portable, key {key_len}"); for len in (0..200).chain([4095, 4096, 4097, 65_535, 65_536, 65_537]) { assert_eq!( decrypt_winzip_ctr(&key, &data[..len]).unwrap(),