Skip to main content

jubarte_cli/update/
zipsign.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2// SPDX-FileCopyrightText: 2023-2025 René Kijewski
3//
4// SPDX-License-Identifier: Apache-2.0 AND LicenseRef-zipsign-MIT
5
6//! zipsign signature check for downloaded release archives (#1705).
7//!
8//! Adapted from zipsign-api 0.2.2 (`verify/`, `verify_unsign_tar.rs` and
9//! `constants.rs`), Copyright (c) 2023-2025 René Kijewski, licensed
10//! `MIT OR Apache-2.0 OR Apache-2.0 WITH LLVM-exception` and used here under
11//! MIT; the preserved notice is `LICENSES/LicenseRef-zipsign-MIT.txt`.
12//! zipsign-api pins ed25519-dalek 2, whose digest 0.10 brings block-buffer
13//! 0.10.4 (GHSA-qwgh-2vcv-g2f7); this port checks the same bytes with
14//! ed25519-dalek 3.
15//!
16//! `zipsign sign` writes two layouts:
17//!
18//! - `zipsign sign zip`: a 16-byte header ([`MAGIC`], then the signature
19//!   count as a little-endian `u16`), the 64-byte signatures, then the
20//!   archive. The signed message is everything after the signatures.
21//! - `zipsign sign tar`: the archive, then one more gzip member whose
22//!   comment holds the same header and signatures in base64, closed by that
23//!   member's start offset in 16 hex digits and [`GZIP_END`]. The signed
24//!   message is everything before that member. Gzip readers see an empty
25//!   last member, so the archive still extracts.
26//!
27//! Either way a signature is ed25519ph over SHA-512, with the archive's file
28//! name as its context. The archive's name picks the layout, as self_update's
29//! own archive detection does: `.tar.gz` and `.tgz` are tar, `.zip` is zip.
30//! The check reads a `.zip` on every platform, though only a build with
31//! self_update's `archive-zip` (Windows) can then extract it.
32
33use std::fs::File;
34use std::io::{ErrorKind, Read, Seek, SeekFrom};
35use std::path::Path;
36
37use base64::Engine;
38use ed25519_dalek::{Signature, VerifyingKey};
39use sha2::{Digest, Sha512};
40
41/// An ed25519 public key trusted to sign release archives: the 32-byte file
42/// `zipsign gen-key` writes.
43pub type ReleaseKey = [u8; 32];
44
45/// The signature block's magic: format 1, `ed25519ph`.
46const MAGIC: &[u8; 14] = b"\x0c\x04\x01ed25519ph\x00\x00";
47/// [`MAGIC`] and the little-endian `u16` signature count.
48const HEADER_SIZE: usize = 16;
49const SIGNATURE_LENGTH: usize = 64;
50/// The most signature bytes zipsign reads or writes.
51const BUF_LIMIT: usize = 1 << 16;
52
53/// The gzip member header zipsign opens its signature member with: deflate,
54/// a comment, mtime 2001-01-01T00:00:00Z, unknown OS.
55const GZIP_START: [u8; 10] = {
56    let [m1, m2, m3, m4] = 978_307_200_u32.to_le_bytes();
57    [0x1f, 0x8b, 0x08, 0x10, m1, m2, m3, m4, 0x00, 0xff]
58};
59/// The comment's NUL, an empty final stored deflate block, and a zero
60/// CRC-32 and size.
61const GZIP_END: [u8; 14] = [0x00, 0x01, 0x00, 0x00, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0];
62/// The 16 hex digits of the signature member's offset.
63const OFFSET_DIGITS: usize = 16;
64
65/// Check that one of `keys` signed the archive at `archive`, as
66/// `zipsign sign tar` or `zipsign sign zip` signs it: the context is the
67/// archive's file name, so the download must keep its release asset name.
68/// With no key there is nothing to check.
69///
70/// # Errors
71///
72/// A message naming why the archive is refused: its name is not UTF-8 or
73/// not `.tar.gz`/`.tgz`/`.zip`, it cannot be read, it carries no well-formed
74/// signature block, or no key verifies any of its signatures.
75pub fn verify_signature(archive: &Path, keys: &[ReleaseKey]) -> Result<(), String> {
76    if keys.is_empty() {
77        return Ok(());
78    }
79    let name = archive
80        .file_name()
81        .and_then(|name| name.to_str())
82        .ok_or("the archive's file name is not UTF-8, so it cannot be a signing context")?;
83    let keys = keys
84        .iter()
85        .enumerate()
86        .map(|(i, key)| {
87            VerifyingKey::from_bytes(key)
88                .map_err(|e| format!("release key #{i} is not an ed25519 public key: {e}"))
89        })
90        .collect::<Result<Vec<_>, _>>()?;
91    let mut file = File::open(archive).map_err(|e| format!("reading {name}: {e}"))?;
92    let (message, signatures) = if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
93        tar_message_and_signatures(&mut file)
94    } else if name.ends_with(".zip") {
95        zip_message_and_signatures(&mut file)
96    } else {
97        return Err(format!(
98            "{name}: zipsign signs only .tar.gz, .tgz and .zip archives"
99        ));
100    }
101    .map_err(|e| format!("{name}: {e}"))?;
102    let signed = keys.iter().any(|key| {
103        signatures.iter().any(|signature| {
104            key.verify_prehashed_strict(message.clone(), Some(name.as_bytes()), signature)
105                .is_ok()
106        })
107    });
108    if signed {
109        Ok(())
110    } else {
111        Err(format!(
112            "{name}: no trusted release key signed this archive"
113        ))
114    }
115}
116
117/// The SHA-512 of the archive bytes before the signature member, and the
118/// signatures that member carries.
119fn tar_message_and_signatures(file: &mut File) -> Result<(Sha512, Vec<Signature>), String> {
120    let mut tail = [0; OFFSET_DIGITS + GZIP_END.len()];
121    // 30 bytes: the cast cannot wrap.
122    let data_end = file
123        .seek(SeekFrom::End(-(tail.len() as i64)))
124        .map_err(|_| "no signature: the archive is too short")?;
125    file.read_exact(&mut tail).map_err(|e| e.to_string())?;
126    if tail[OFFSET_DIGITS..] != GZIP_END {
127        return Err("no signature: the last gzip member is not zipsign's".into());
128    }
129    let member_start = std::str::from_utf8(&tail[..OFFSET_DIGITS])
130        .ok()
131        .and_then(|digits| u64::from_str_radix(digits, 16).ok())
132        .ok_or("no signature: the signature member's offset is malformed")?;
133    let encoded_start = member_start
134        .checked_add(GZIP_START.len() as u64)
135        .ok_or("no signature: the signature member's offset is out of range")?;
136    let encoded_len = data_end
137        .checked_sub(encoded_start)
138        .and_then(|len| usize::try_from(len).ok())
139        .filter(|&len| len <= BUF_LIMIT)
140        .ok_or("no signature: the signature member's offset is out of range")?;
141
142    file.seek(SeekFrom::Start(member_start))
143        .map_err(|e| e.to_string())?;
144    let mut member = vec![0; GZIP_START.len() + encoded_len];
145    file.read_exact(&mut member).map_err(|e| e.to_string())?;
146    if member[..GZIP_START.len()] != GZIP_START {
147        return Err("no signature: the signature member's gzip header is not zipsign's".into());
148    }
149    let block = base64::engine::general_purpose::STANDARD
150        .decode(&member[GZIP_START.len()..])
151        .map_err(|_| "the signature block is not base64")?;
152    let (count, rest) = signature_header(&block)?;
153    if rest.len() != count * SIGNATURE_LENGTH {
154        return Err("the signature block's length does not match its signature count".into());
155    }
156    let signatures = signatures(rest);
157
158    file.rewind().map_err(|e| e.to_string())?;
159    let message = prehash(&mut file.take(member_start)).map_err(|e| e.to_string())?;
160    Ok((message, signatures))
161}
162
163/// The signatures at the head of a signed zip, and the SHA-512 of the
164/// archive after them.
165fn zip_message_and_signatures(file: &mut File) -> Result<(Sha512, Vec<Signature>), String> {
166    let mut header = [0; HEADER_SIZE];
167    file.read_exact(&mut header)
168        .map_err(|_| "no signature: the archive is too short")?;
169    let (count, _) = signature_header(&header)?;
170    let mut block = vec![0; count * SIGNATURE_LENGTH];
171    file.read_exact(&mut block)
172        .map_err(|_| "the archive ends inside its signatures")?;
173    let signatures = signatures(&block);
174    let message = prehash(file).map_err(|e| e.to_string())?;
175    Ok((message, signatures))
176}
177
178/// The signature count a block's header announces, and the bytes after the
179/// header.
180fn signature_header(block: &[u8]) -> Result<(usize, &[u8]), String> {
181    let Some((header, rest)) = block.split_first_chunk::<HEADER_SIZE>() else {
182        return Err("no signature: the signature block is too short".into());
183    };
184    // The header is the magic and a little-endian count, split by its type.
185    let [magic @ .., low, high] = header;
186    if magic != MAGIC {
187        return Err("no signature: the signature block's magic is not zipsign's".into());
188    }
189    let count = usize::from(u16::from_le_bytes([*low, *high]));
190    if count == 0 {
191        return Err("the signature block holds no signature".into());
192    }
193    if count * SIGNATURE_LENGTH > BUF_LIMIT {
194        return Err("the signature block announces too many signatures".into());
195    }
196    Ok((count, rest))
197}
198
199/// The 64-byte signatures in `bytes`, whose length the caller has checked.
200fn signatures(bytes: &[u8]) -> Vec<Signature> {
201    let (signatures, _) = bytes.as_chunks::<SIGNATURE_LENGTH>();
202    signatures.iter().map(Signature::from_bytes).collect()
203}
204
205fn prehash(input: &mut impl Read) -> std::io::Result<Sha512> {
206    let mut hash = Sha512::new();
207    let mut buf = [0; 1 << 14];
208    loop {
209        match input.read(&mut buf) {
210            Ok(0) => return Ok(hash),
211            Ok(n) => hash.update(&buf[..n]),
212            Err(e) if e.kind() == ErrorKind::Interrupted => {}
213            Err(e) => return Err(e),
214        }
215    }
216}