Swatches: the .ase reader refuses files with more than 10,000 groups (#5811)

photocraft_psd::ase::parse counted colors toward MAX_SWATCHES but not
group starts, so the number of groups it read grew with the file's
size. An empty group start is six bytes, and parse held about 64 bytes
for each: in a test build, parsing a 60 MB file of 10,000,000 empty
group starts raised the process's peak memory from 63 MB to 705 MB.
swatches.import reads files of up to 512 MiB, and read_file built a
group for each group start before the import refused more than 10,000
groups.

parse now counts group starts and returns LimitExceeded past
MAX_GROUPS (10,000), the most groups the Swatches panel holds. Files
with at most 10,000 groups parse as before, so every file the import
accepted still loads. Files with more were refused before as well; now
parse refuses them before it holds more than 10,000 groups. write also
refuses more than MAX_GROUPS groups, as it refuses more than
MAX_SWATCHES colors.

ase_group_cap_is_enforced_on_hostile_input parses 10,001 empty group
starts and expects LimitExceeded, then parses the same file with one
block fewer and expects all 10,000 groups. too_many_groups checks that
write refuses 10,001 groups and that 10,000 groups are written and
read back.
This commit is contained in:
.CooCoo authored and GitHub committed 2026-10-18 03:34:00 -04:00
1 parent 0f0f58c2ab
commit ea647146db
2 files changed
+51 -4

No files matched your search

+25 -4
View File
@@ -22,6 +22,8 @@ use crate::io::{Reader, WriteExt};
pub const SIGNATURE: &[u8; 4] = b"ASEF";
/// Most colour entries read from one file.
pub const MAX_SWATCHES: usize = 100_000;
/// Most groups read from one file.
pub const MAX_GROUPS: usize = 10_000;
/// Longest name read or written, in UTF-16 code units.
pub const MAX_NAME_UNITS: usize = 1024;
// `put_name` writes the name length as `units.len() as u16 + 1`, so the cap must leave room in a
@@ -172,9 +174,9 @@ fn read_color(body: &mut Reader<'_>) -> Result<AseSwatch> {
}
/// Parse an `.ase` file. A wrong signature or version, a truncated block, a block count beyond
/// the data or more than [`MAX_SWATCHES`] colours is an error; never panics. Unknown block
/// types are skipped, a group end without a start is ignored, and a group left open at the end
/// (or a group started inside another) is closed.
/// the data, more than [`MAX_SWATCHES`] colors or more than [`MAX_GROUPS`] groups is an error;
/// never panics. Unknown block types are skipped, a group end without a start is ignored, and a
/// group left open at the end (or a group started inside another) is closed.
pub fn parse(data: &[u8]) -> Result<AseFile> {
let mut r = Reader::new(data);
let sig: [u8; 4] = r.array()?;
@@ -192,12 +194,17 @@ pub fn parse(data: &[u8]) -> Result<AseFile> {
let mut entries = Vec::new();
let mut open: Option<(String, Vec<AseSwatch>)> = None;
let mut total = 0usize;
let mut groups = 0usize;
for _ in 0..count {
let kind = r.u16()?;
let len = u64::from(r.u32()?);
let mut body = r.sub(len)?;
match kind {
GROUP_START => {
groups += 1;
if groups > MAX_GROUPS {
return Err(PsdError::LimitExceeded("too many groups in an .ase file"));
}
if let Some((name, swatches)) = open.take() {
entries.push(AseEntry::Group { name, swatches });
}
@@ -279,11 +286,15 @@ fn put_color(out: &mut Vec<u8>, s: &AseSwatch) -> Result<()> {
}
/// Write an `.ase` file (version 1.0). Fails only when a block or the block count overflows the
/// format's 32-bit fields or there are more than [`MAX_SWATCHES`] colours.
/// format's 32-bit fields or there are more than [`MAX_SWATCHES`] colors or more than
/// [`MAX_GROUPS`] groups.
pub fn write(file: &AseFile) -> Result<Vec<u8>> {
if file.swatch_count() > MAX_SWATCHES {
return Err(PsdError::LimitExceeded("too many swatches for an .ase file"));
}
if file.entries.iter().filter(|e| matches!(e, AseEntry::Group { .. })).count() > MAX_GROUPS {
return Err(PsdError::LimitExceeded("too many groups for an .ase file"));
}
let mut body = Vec::with_capacity(64 * file.swatch_count().max(1));
let mut blocks = 0u64;
for e in &file.entries {
@@ -415,4 +426,14 @@ mod tests {
let f = AseFile { entries: vec![AseEntry::Group { name: "g".into(), swatches: vec![s; MAX_SWATCHES + 1] }] };
assert!(write(&f).is_err());
}
#[test]
fn too_many_groups() {
let g = AseEntry::Group { name: "g".into(), swatches: vec![] };
let mut f = AseFile { entries: vec![g; MAX_GROUPS + 1] };
assert!(write(&f).is_err());
// At the limit the file is written, and every group reads back.
f.entries.pop();
assert_eq!(parse(&write(&f).unwrap()).unwrap().entries.len(), MAX_GROUPS);
}
}
+26
View File
@@ -444,6 +444,32 @@ fn ase_swatch_cap_is_enforced_on_hostile_input() {
assert!(ase::parse(&f).is_ok(), "a file exactly at MAX_SWATCHES must still parse");
}
/// A file with more group starts than [`ase::MAX_GROUPS`] must be refused. Each block here is an
/// empty group start, six bytes long.
#[test]
fn ase_group_cap_is_enforced_on_hostile_input() {
let mut block = Vec::new();
block.extend_from_slice(&0xC001u16.to_be_bytes()); // block type: group start
block.extend_from_slice(&0u32.to_be_bytes()); // empty body: no name
let total = ase::MAX_GROUPS + 1;
let mut f = b"ASEF".to_vec();
f.extend_from_slice(&1u16.to_be_bytes()); // major
f.extend_from_slice(&0u16.to_be_bytes()); // minor
f.extend_from_slice(&(total as u32).to_be_bytes());
for _ in 0..total {
f.extend_from_slice(&block);
}
assert!(matches!(ase::parse(&f), Err(PsdError::LimitExceeded(_))), "a file over MAX_GROUPS must be refused");
// With one block fewer the file is exactly at the cap and parses.
f.truncate(f.len() - block.len());
let trimmed = total - 1;
// signature (4) + major (2) + minor (2) puts the block count at offset 8.
f[8..12].copy_from_slice(&(trimmed as u32).to_be_bytes());
let parsed = ase::parse(&f).expect("a file exactly at MAX_GROUPS must still parse");
assert_eq!(parsed.entries.len(), ase::MAX_GROUPS, "every group up to the cap is kept");
}
/// A name longer than [`ase::MAX_NAME_UNITS`] is truncated on read rather than refused: the file
/// is legal, only the name is long, and `read_name` is the only thing standing between the declared
/// length and the string it builds.