diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9891e7830..3c3c7b538 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -3019,7 +3019,10 @@ original jar is already in the build's local repository (the Maven local reposit or a Gradle cache), every entry the JVM would load must hold the same content in it and in the service's jar, whatever unix mode the entry carries; the record's members and signature files (`META-INF/*.SF`, `.RSA`, `.DSA`, `.EC`) are exempt and directory -entries may differ. A difference means the project builds with a jar that is not the +entries may differ. The manifest of a jar the patch service signed again may differ +as that signing leaves it (digest lines changed for the patched members and added for +the others, sections added for entries it did not list), by the rule under +[Agent mode](#agent-mode-apply-scan---mode-agent). A difference means the project builds with a jar that is not the one the patch was made from (an internal rebuild under the same coordinates, say), so the service's jar would change more than the patch: the vendoring is refused with `vendor_prebuilt_integrity_mismatch`, the detail naming up to three such members, and @@ -3632,6 +3635,52 @@ differ. A copy that differs fails with `jvm_agent_service_jar_mismatch`, naming to three added, missing or changed members, and is left as it is; the other copies are still swapped. +One member outside the patch may change, in one way: `META-INF/MANIFEST.MF` of a jar +the patch service signed again. A signed jar's manifest holds each entry's digests and +its signature files vouch for the manifest, so patching a class of a signed security +provider (Bouncy Castle's `bcprov`) means signing the jar again, as a whole: +upstream's signature files are replaced by the service's (`META-INF/SOCKET.SF`, +`SOCKET.RSA`) and every file entry is listed under the signing digest. A current JDK +ignores SHA-1 digests, so a manifest that holds only those gains a SHA-256 line in +every section, and an entry upstream never listed gains a section. The service's jar +must carry a signature file, and its manifest may differ from the installed jar's +only as follows; anything else is the refusal above with the reason added: + +1. The main-attributes section is byte for byte the same. +2. The section of a member the record does not touch keeps every line, byte for byte + and in order. It may gain digest attributes, each of which must equal the digest + of that member in the service's jar. +3. The section of a member the record changes may also change the values of its + digest attributes. Every digest in it must equal the member's in the service's + jar, and no other attribute may change. +4. A section is added only for a member the record adds or changes, or for an entry + that both jars hold with identical bytes and the installed manifest did not list. + It holds a `Name` and verified digests alone. +5. No section is removed. + +A digest attribute is one the JDK reads when it verifies a jar: `SHA-256-Digest`, +`SHA-384-Digest`, `SHA-512-Digest`, `SHA1-Digest`, `SHA-1-Digest`, `MD5-Digest`, +matched without regard to case. An added or changed attribute of any other name is a +refusal, the other digests the JDK reads (`SHA-224-Digest`, the SHA-3 ones) among +them: the service writes none. The manifest is read as the JAR +specification lays it out (lines end in `\r\n`, `\n` or `\r`, a leading space +continues a line wrapped at 72 bytes, a blank line ends a section) and its sections +are compared as the bytes in the file. Blank lines are not compared, so a terminator +added before appended sections changes nothing, and a last line of the installed +manifest with no terminator, which a JVM ignores, may be dropped. The signature +itself is not verified; that is the JVM's. A rollback finds the original of such a +copy by the same rule. + +A jar whose patch record itself lists `META-INF/MANIFEST.MF` is refused for now when +the service signed it again. The manifest is then a member the record changes, held +to its `afterHash`, and the signed manifest is that blob with its digests completed, +not the blob. Accepting it needs the record's blob wherever a member is held to its +`afterHash`, and `rollback`, `vex` and the vendored check do not have it at hand. + +A jar past a limit while its manifest is read is `jvm_jar_too_large` (vendored: +`vendor_artifact_too_large`), never a mismatch; the manifest has no limit of its own +below those of the jar. + Jars are read within fixed limits, counted on the bytes actually inflated and on the archive's own entry count, never on the sizes an archive declares: 200,000 entries and 64 MiB of central directory (both read from the end record the zip reader would diff --git a/crates/socket-patch-core/src/patch/jar_manifest.rs b/crates/socket-patch-core/src/patch/jar_manifest.rs new file mode 100644 index 000000000..77159d645 --- /dev/null +++ b/crates/socket-patch-core/src/patch/jar_manifest.rs @@ -0,0 +1,941 @@ +//! The one way a patched jar's `META-INF/MANIFEST.MF` may differ from the +//! original's: what signing the patched jar again does to it. +//! +//! A signed jar's manifest holds a section per entry with the entry's +//! digests, and its signature files vouch for the manifest. Changing a class +//! therefore breaks the signature, and a JVM that requires one (a JCE +//! provider such as Bouncy Castle's) refuses the jar. So the patch service +//! signs such a jar again, as a whole, the way `jarsigner` does: upstream's +//! signature files go, its own are added, and every file entry is listed +//! in the manifest under the signing digest. A current JDK ignores SHA-1 +//! digests, so a jar whose manifest holds only those gets a SHA-256 line in +//! every section, and an entry upstream never listed gets a section of its +//! own. Signature files are already outside the "everything else is the +//! original's" comparison ([`super::jar_members::unpatched_difference`]); +//! the manifest is a member like any other, so that comparison refuses it. +//! +//! [`resigned`] accepts exactly that manifest and nothing wider. +//! The patched jar must carry a signature file, and against the original +//! manifest: +//! +//! 1. the main section is byte for byte the same; +//! 2. the section of a member the record does not touch keeps every line, +//! byte for byte and in order; it may gain digest attributes, each of +//! which must be the digest of that member in the patched jar (which +//! also shows, under a second hash, that the member is unchanged); +//! 3. the section of a member the record changes may also change the +//! values of its digest attributes; every digest in it must be the +//! member's, and no other attribute may change; +//! 4. a section is added only for a member the record adds or changes, or +//! for an entry both jars hold with the same bytes that the original +//! manifest did not list; it holds a `Name` and verified digests alone; +//! 5. no section is removed. +//! +//! A record that lists the manifest itself is outside this: the manifest +//! is then a member the record changes, held to its `afterHash` like any +//! other, and a jar signed again does not carry that blob byte for byte. +//! +//! A digest attribute is one the JDK reads when it verifies a jar: +//! `SHA-256-Digest`, `SHA-384-Digest`, `SHA-512-Digest`, `SHA1-Digest`, +//! `SHA-1-Digest`, `MD5-Digest`. An added attribute of any other name is a +//! refusal. +//! +//! Sections are compared as the byte ranges the file holds, never as +//! re-serialised text. The file is read as the JAR specification lays it +//! out: lines end in `\r\n`, `\n` or `\r`, a line that starts with a space +//! continues the one before (lines wrap at 72 bytes), and a blank line ends +//! a section; blank lines themselves are not compared, so a terminator +//! added before appended sections changes nothing. A last line with no +//! terminator is one a JVM ignores, and is dropped from the original +//! before the comparison. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use base64::Engine as _; + +use super::jar_members::{Digests, Jar, JarError}; +use crate::manifest::schema::PatchFileInfo; +use crate::patch::apply::normalize_file_path; + +pub(crate) const MANIFEST: &str = "META-INF/MANIFEST.MF"; + +/// One attribute of a section: its name, its value with continuation lines +/// joined, and the bytes it takes in the file (terminators included). +struct Attribute<'a> { + name: &'a [u8], + value: Vec, + raw: &'a [u8], +} + +/// One per-entry section: the bytes of its lines, and its attributes. +struct Section<'a> { + raw: &'a [u8], + attributes: Vec>, +} + +/// A manifest: the main section and the per-entry ones by entry name. +struct Sections<'a> { + main: &'a [u8], + entries: BTreeMap, Section<'a>>, +} + +/// The end of the line that starts at `at`: `(content end, next line)`. +fn line_end(text: &[u8], at: usize) -> (usize, usize) { + let mut end = at; + while end < text.len() && text[end] != b'\n' && text[end] != b'\r' { + end += 1; + } + let next = match text.get(end) { + Some(b'\r') if text.get(end + 1) == Some(&b'\n') => end + 2, + Some(_) => end + 1, + None => end, + }; + (end, next) +} + +/// The attributes of one section's bytes. +fn attributes(section: &[u8]) -> Result>, String> { + let mut out: Vec> = Vec::new(); + let mut start = 0; + let mut at = 0; + while at < section.len() { + let (end, next) = line_end(section, at); + let line = §ion[at..end]; + if let Some(more) = line.strip_prefix(b" ") { + let last = out.last_mut().ok_or("it starts with a continuation line")?; + last.value.extend_from_slice(more); + last.raw = §ion[start..next]; + } else { + let colon = line + .windows(2) + .position(|w| w == b": ") + .ok_or("it holds a line that is not `Name: value`")?; + start = at; + out.push(Attribute { + name: &line[..colon], + value: line[colon + 2..].to_vec(), + raw: §ion[at..next], + }); + } + at = next; + } + Ok(out) +} + +/// Split a manifest into its sections, each parsed once. +fn sections(manifest: &[u8]) -> Result, String> { + let mut runs: Vec<&[u8]> = Vec::new(); + let mut start = None; + let mut at = 0; + let mut leading_blank = false; + while at < manifest.len() { + let (end, next) = line_end(manifest, at); + if end == at { + match start.take() { + Some(from) => runs.push(&manifest[from..at]), + None if runs.is_empty() => leading_blank = true, + None => {} + } + } else if start.is_none() { + start = Some(at); + } + at = next; + } + if let Some(from) = start { + runs.push(&manifest[from..]); + } + let mut runs = runs.into_iter(); + // A manifest that opens with a blank line has an empty main section. + let main = match leading_blank { + true => &manifest[..0], + false => runs.next().unwrap_or(&manifest[..0]), + }; + let mut entries = BTreeMap::new(); + for raw in runs { + let attributes = attributes(raw)?; + let name = match attributes.first() { + Some(first) if first.name.eq_ignore_ascii_case(b"Name") => first.value.clone(), + _ => return Err("a section does not start with `Name:`".to_string()), + }; + let shown = String::from_utf8_lossy(&name).into_owned(); + if entries.insert(name, Section { raw, attributes }).is_some() { + return Err(format!("it holds two sections for `{shown}`")); + } + } + Ok(Sections { main, entries }) +} + +/// The algorithm of a digest attribute this reads, as +/// [`Jar::member_digest`] names it. The JDK reads a few more +/// (`SHA-224-Digest`, the SHA-3 ones); the patch service writes none of +/// them, and one that is added or changed is refused like any attribute +/// that is not a digest. +fn digest_algorithm(attribute: &[u8]) -> Option<&'static str> { + [ + ("SHA-256-Digest", "SHA-256"), + ("SHA-384-Digest", "SHA-384"), + ("SHA-512-Digest", "SHA-512"), + ("SHA1-Digest", "SHA-1"), + ("SHA-1-Digest", "SHA-1"), + ("MD5-Digest", "MD5"), + ] + .into_iter() + .find(|(name, _)| attribute.eq_ignore_ascii_case(name.as_bytes())) + .map(|(_, algorithm)| algorithm) +} + +/// `manifest` without a last line that has no terminator (a JVM ignores it). +fn terminated(manifest: &[u8]) -> &[u8] { + match manifest.iter().rposition(|b| *b == b'\n' || *b == b'\r') { + Some(last) => &manifest[..=last], + None => &manifest[..0], + } +} + +/// The digest attributes of `is` that must be the member's own, when `is` +/// is `was` as signing again leaves a section: every line of `was` kept in +/// order, digest attributes added, and, for a member the record `changes`, +/// digest values changed. Attribute names are matched as a manifest reads +/// them, without regard to case. `Err` says what else differs. +fn follows<'s, 'a>( + was: &[Attribute<'a>], + is: &'s [Attribute<'a>], + changes: bool, +) -> Result>, String> { + let mut kept = 0; + let mut verify = Vec::new(); + for attribute in is { + let digest = digest_algorithm(attribute.name).is_some(); + match was.get(kept) { + Some(old) if old.raw == attribute.raw => { + kept += 1; + if changes && digest { + verify.push(attribute); + } + } + Some(old) if changes && digest && old.name.eq_ignore_ascii_case(attribute.name) => { + kept += 1; + verify.push(attribute); + } + _ if digest => verify.push(attribute), + _ => { + return Err(format!( + "adds or changes `{}`, which is not a digest", + String::from_utf8_lossy(attribute.name) + )) + } + } + } + match was.get(kept) { + Some(old) => Err(format!( + "changes or drops its `{}` line", + String::from_utf8_lossy(old.name) + )), + None => Ok(verify), + } +} + +/// What a patched jar's manifest is to the original's. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Resigned { + /// The patched jar carries no signature file: its manifest is a member + /// like any other, and a difference in it an ordinary one. + Unsigned, + /// The manifest is the original's as signing the jar again leaves it. + Accepted, + /// It is not: why. + Refused(String), +} + +/// Why the comparison stopped: a jar past a limit, or a difference. +enum Stop { + Limit(JarError), + Why(String), +} + +impl From for Stop { + fn from(why: String) -> Self { + Stop::Why(why) + } +} + +/// A read that failed: a limit stays a limit, anything else is `why`. +fn stop(e: JarError, why: impl FnOnce(&JarError) -> String) -> Stop { + match e.is_too_large() { + true => Stop::Limit(e), + false => Stop::Why(why(&e)), + } +} + +/// Each of `digests` is the digest of `member` in `jar`. Its SHA-256 is +/// the one the comparison already has (`known`); only another algorithm +/// inflates the member again. +fn digests_hold( + jar: &mut Jar, + known: &Digests, + member: &str, + digests: &[&Attribute<'_>], +) -> Result<(), Stop> { + for attribute in digests { + let algorithm = digest_algorithm(attribute.name).expect("a digest attribute"); + let actual = match algorithm { + "SHA-256" => known.get(member).map(|digest| digest.to_vec()), + _ => jar + .member_digest(member, algorithm) + .map_err(|e| stop(e, |e| format!("`{member}` could not be hashed ({e})")))?, + }; + let actual = actual.ok_or_else(|| { + format!("it has a section for `{member}`, which the jar does not hold") + })?; + let declared = base64::engine::general_purpose::STANDARD + .decode(&attribute.value) + .ok(); + if declared.as_deref() != Some(actual.as_slice()) { + return Err(Stop::Why(format!( + "its {algorithm} digest of `{member}` does not match the member in the jar" + ))); + } + } + Ok(()) +} + +/// Whether `patched`'s manifest is the original's as signing the patched +/// jar again leaves it, for the record `files` (see the module docs). Each +/// jar comes with its members' content digests. `Err` is a jar past a +/// limit: that is the caller's too-large refusal, never a difference. +pub(crate) fn resigned( + original: (&[u8], &Digests), + patched: (&[u8], &Digests), + files: &HashMap, +) -> Result { + let mut jar = Jar::of_bytes(patched.0)?; + if !jar.has_signature_file() { + return Ok(Resigned::Unsigned); + } + match compare(original, patched.1, &mut jar, files) { + Ok(()) => Ok(Resigned::Accepted), + Err(Stop::Why(why)) => Ok(Resigned::Refused(why)), + Err(Stop::Limit(e)) => Err(e), + } +} + +fn compare( + original: (&[u8], &Digests), + members: &Digests, + jar: &mut Jar, + files: &HashMap, +) -> Result<(), Stop> { + let before = Jar::of_bytes(original.0) + .and_then(|mut jar| jar.member_bytes(MANIFEST)) + .map_err(|e| stop(e, |e| format!("the original manifest cannot be read ({e})")))? + .ok_or_else(|| "the original jar has no manifest".to_string())?; + let after = jar + .member_bytes(MANIFEST) + .map_err(|e| stop(e, |e| format!("the patched manifest cannot be read ({e})")))? + .ok_or_else(|| "the patched jar has no manifest".to_string())?; + let old = + sections(terminated(&before)).map_err(|why| format!("the original manifest: {why}"))?; + let new = sections(&after).map_err(|why| format!("the patched manifest: {why}"))?; + if old.main != new.main { + return Err(Stop::Why("its main attributes differ".to_string())); + } + let touched: HashSet<&[u8]> = files + .keys() + .map(|key| normalize_file_path(key).as_bytes()) + .collect(); + let names: std::collections::BTreeSet<&Vec> = + old.entries.keys().chain(new.entries.keys()).collect(); + for name in names { + let member = String::from_utf8_lossy(name); + // The record adds the member or changes its bytes. + let changes = touched.contains(name.as_slice()); + match (old.entries.get(name), new.entries.get(name)) { + (Some(_), None) => { + return Err(Stop::Why(format!("it drops the section for `{member}`"))) + } + (None, Some(is)) => { + let unchanged = matches!( + (original.1.get(name), members.get(name)), + (Some(was), Some(is)) if was == is + ); + if !changes && !unchanged { + return Err(Stop::Why(format!( + "it adds a section for `{member}`, which is neither a member the patch \ + adds or changes nor an unchanged entry of the original jar" + ))); + } + let digests: Vec<&Attribute<'_>> = is.attributes.iter().skip(1).collect(); + if digests.is_empty() || digests.iter().any(|a| digest_algorithm(a.name).is_none()) + { + return Err(Stop::Why(format!( + "its section for `{member}` is new and holds other than digests" + ))); + } + digests_hold(jar, members, &member, &digests)?; + } + (Some(was), Some(is)) if was.raw == is.raw && !changes => {} + (Some(was), Some(is)) => { + let digests = follows(&was.attributes, &is.attributes, changes).map_err(|why| { + format!( + "its section for `{member}` {why}{}", + match changes { + true => "", + false => ", though the patch does not touch the member", + } + ) + })?; + digests_hold(jar, members, &member, &digests)?; + } + (None, None) => unreachable!("a name comes from one of the two manifests"), + } + } + Ok(()) +} + +/// A real signed jar and its re-signed, patched twin, for the tests of the +/// comparisons that use the rule. +#[cfg(test)] +pub(crate) mod fixture { + use super::*; + use crate::hash::git_sha256::compute_git_sha256_from_bytes; + use std::io::{Read as _, Write as _}; + + /// A jar `jarsigner` signed (alias `upstream`, SHA-256 digests), and + /// the same jar with `org/example/B.class` changed, upstream's + /// signature files dropped and `jarsigner` run again under the alias + /// `SOCKET`: what the patch service's re-signing produces. See + /// `tests/data/resigned-provider/make.sh`. + pub(crate) const UPSTREAM: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/data/resigned-provider/upstream.jar" + )); + pub(crate) const SERVED: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/data/resigned-provider/served.jar" + )); + pub(crate) const CHANGED: &str = "org/example/B.class"; + const BEFORE: &[u8] = b"\xca\xfe\xba\xbe class B, vulnerable"; + const AFTER: &[u8] = b"\xca\xfe\xba\xbe class B, fixed"; + + /// The record that changes [`CHANGED`]. + pub(crate) fn record() -> HashMap { + HashMap::from([( + CHANGED.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(BEFORE), + after_hash: compute_git_sha256_from_bytes(AFTER), + }, + )]) + } + + /// `jar` rewritten: `keep` picks its entries, `manifest` rewrites the + /// manifest's text, and `extra` members are appended. + pub(crate) fn rewritten( + jar: &[u8], + keep: impl Fn(&str) -> bool, + manifest: impl Fn(String) -> String, + extra: &[(&str, &[u8])], + ) -> Vec { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(jar)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for i in 0..zip.len() { + let mut entry = zip.by_index(i).unwrap(); + let name = entry.name().to_string(); + if name.ends_with('/') || !keep(&name) { + continue; + } + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes).unwrap(); + if name == MANIFEST { + bytes = manifest(String::from_utf8(bytes).unwrap()).into_bytes(); + } + out.start_file(name, opts).unwrap(); + out.write_all(&bytes).unwrap(); + } + for (name, bytes) in extra { + out.start_file(*name, opts).unwrap(); + out.write_all(bytes).unwrap(); + } + out.finish().unwrap().into_inner() + } + + /// [`SERVED`] with its manifest's text rewritten. + pub(crate) fn edited(manifest: impl Fn(String) -> String) -> Vec { + rewritten(SERVED, |_| true, manifest, &[]) + } +} + +#[cfg(test)] +mod tests { + use super::fixture::*; + use super::*; + use crate::hash::git_sha256::compute_git_sha256_from_bytes; + use crate::patch::jar_members::difference_outside_patch; + + /// What the patch service's signer made of five upstream jars (the + /// patch changes `fixture/Plain.class` in each): `(upstream, served)`. + macro_rules! service { + ($name:literal) => { + ( + include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/data/resigned-provider/service/", + $name, + ".upstream.jar" + )) + .as_slice(), + include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/data/resigned-provider/service/", + $name, + ".jar" + )) + .as_slice(), + ) + }; + } + const PLAIN: &str = "fixture/Plain.class"; + const UNTOUCHED: &str = "fixture/Unicode.class"; + + /// The record of a pair: `changed` members by their hashes in the two + /// jars, `added` ones with no `beforeHash`. + fn record_of( + upstream: &[u8], + served: &[u8], + changed: &[&str], + added: &[&str], + ) -> HashMap { + let hash = |jar: &[u8], member: &str| { + let mut jar = Jar::of_bytes(jar).unwrap(); + jar.member_git_sha256(member).unwrap().unwrap() + }; + let changed = changed.iter().map(|member| { + let (before_hash, after_hash) = (hash(upstream, member), hash(served, member)); + ( + member.to_string(), + PatchFileInfo { + before_hash, + after_hash, + }, + ) + }); + let added = added.iter().map(|member| { + let (before_hash, after_hash) = (String::new(), hash(served, member)); + ( + member.to_string(), + PatchFileInfo { + before_hash, + after_hash, + }, + ) + }); + changed.chain(added).collect() + } + + fn manifest_of(jar: &[u8]) -> String { + let mut jar = Jar::of_bytes(jar).unwrap(); + String::from_utf8(jar.member_bytes(MANIFEST).unwrap().unwrap()).unwrap() + } + + fn refusal( + upstream: &[u8], + served: &[u8], + files: &HashMap, + ) -> Option { + let (was, is) = ( + Digests::of_bytes(upstream).unwrap(), + Digests::of_bytes(served).unwrap(), + ); + let verdict = resigned((upstream, &was), (served, &is), files).unwrap(); + // The comparison the swap and vendoring make agrees. + let difference = difference_outside_patch((upstream, &was), (served, &is), files).unwrap(); + match verdict { + Resigned::Accepted => { + assert!(difference.is_empty(), "{}", difference.describe()); + None + } + Resigned::Refused(why) => { + assert_eq!(difference.manifest.as_deref(), Some(why.as_str())); + assert!(difference.changed.contains(&MANIFEST.to_string())); + Some(why) + } + Resigned::Unsigned => { + assert_eq!(difference.manifest, None); + assert!(difference.changed.contains(&MANIFEST.to_string())); + Some("the patched jar is not signed".to_string()) + } + } + } + + /// The line `attribute: …` of `member`'s section in `manifest`. + fn line(manifest: &str, member: &str, attribute: &str) -> String { + let at = manifest.find(&format!("Name: {member}\r\n")).unwrap(); + let section = &manifest[at..at + manifest[at..].find("\r\n\r\n").unwrap()]; + let line = section.lines().find(|l| l.starts_with(attribute)); + line.unwrap().to_string() + } + + #[test] + fn the_fixture_is_a_resigned_jar() { + let names = |jar: &[u8]| -> Vec { + let zip = zip::ZipArchive::new(std::io::Cursor::new(jar)).unwrap(); + let mut names: Vec = zip.file_names().map(str::to_string).collect(); + names.retain(|n| n.starts_with("META-INF/") && !n.ends_with('/')); + names.sort(); + names + }; + assert_eq!( + names(UPSTREAM), + [ + "META-INF/MANIFEST.MF", + "META-INF/UPSTREAM.RSA", + "META-INF/UPSTREAM.SF" + ] + ); + assert_eq!( + names(SERVED), + [ + "META-INF/MANIFEST.MF", + "META-INF/SOCKET.RSA", + "META-INF/SOCKET.SF" + ] + ); + } + + /// What the service's signer produces is accepted, in each shape it + /// takes: one digest value changed; a SHA-256 line inserted in every + /// section of a SHA-1-only manifest; sections appended for entries the + /// original never listed (the changed one among them); an unterminated + /// last line dropped and a section appended for an added member. + #[test] + fn the_services_resigned_jars_are_accepted() { + assert_eq!(refusal(UPSTREAM, SERVED, &record()), None); + for ((upstream, served), added) in [ + (service!("sha256"), &[][..]), + (service!("sha1-only"), &[]), + (service!("unlisted"), &[]), + (service!("unterminated-line"), &["com/fresh/Added.class"]), + ] { + let files = record_of(upstream, served, &[PLAIN], added); + assert_eq!(refusal(upstream, served, &files), None); + } + // The shapes are the ones named above. + let (upstream, served) = service!("sha1-only"); + assert!(!manifest_of(upstream).contains("SHA-256-Digest")); + assert_eq!(manifest_of(served).matches("SHA-256-Digest").count(), 4); + let (upstream, served) = service!("unlisted"); + assert!(!manifest_of(upstream).contains(UNTOUCHED)); + assert!(manifest_of(served).ends_with(&format!( + "Name: {UNTOUCHED}\r\n{}\r\n\r\n", + line(&manifest_of(served), UNTOUCHED, "SHA-256-Digest") + ))); + let (upstream, _) = service!("unterminated-line"); + assert!(manifest_of(upstream).ends_with("X-Junk: no newline")); + // Line endings are the file's own: `\n` on both sides is accepted. + let unix = |jar: &[u8]| rewritten(jar, |_| true, |m| m.replace("\r\n", "\n"), &[]); + assert_eq!(refusal(&unix(UPSTREAM), &unix(SERVED), &record()), None); + } + + /// A record that lists the manifest itself is outside the rule: the + /// manifest is then a member the record changes, held to its + /// `afterHash`, and the served manifest (the record's blob with its + /// digests completed) is not that blob. The swap and vendoring refuse + /// such a jar at that check. + #[test] + fn a_record_that_lists_the_manifest_is_not_accepted_yet() { + let (upstream, served) = service!("manifest-in-record"); + let blob = manifest_of(upstream).replacen("\r\n", "\r\nX-Patched: yes\r\n", 1); + let mut files = record_of(upstream, served, &[PLAIN], &[]); + files.insert( + MANIFEST.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(manifest_of(upstream).as_bytes()), + after_hash: compute_git_sha256_from_bytes(blob.as_bytes()), + }, + ); + assert_ne!(manifest_of(served), blob); + assert!(!crate::vendor::common::zip_bytes_match_after_hashes( + served, &files + )); + } + + /// A member is found by the raw bytes of its name, in the manifest rule + /// as in the reader: a UTF-8 name written without the UTF-8 flag, which + /// the zip reader decodes as something else, still has its digest. + #[test] + fn a_member_with_a_non_ascii_name_and_no_utf8_flag_is_verified() { + use crate::patch::jar_members::testing::without_utf8_flag; + const NAME: &str = "fixture/\u{dc}n\u{ef}code.class"; + let (upstream, served) = service!("sha256"); + let sha1 = base64::engine::general_purpose::STANDARD + .encode(::digest(b"unicode")); + let extra: &[(&str, &[u8])] = &[(NAME, b"unicode")]; + let upstream = without_utf8_flag(rewritten(upstream, |_| true, |m| m, extra)); + let served = without_utf8_flag(rewritten( + served, + |_| true, + |m| format!("{m}Name: {NAME}\r\nSHA1-Digest: {sha1}\r\n\r\n"), + extra, + )); + let files = record_of(&upstream, &served, &[PLAIN], &[]); + assert_eq!(refusal(&upstream, &served, &files), None); + } + + /// A manifest larger than any cap of its own is read within the jar + /// limits and accepted; a jar past a limit is the caller's too-large + /// refusal, never a difference. + #[test] + fn a_large_manifest_is_read_and_a_limit_is_a_limit() { + let (upstream, served) = service!("sha256"); + let pad = format!( + "Manifest-Version: 1.0\r\nX-Pad: {}", + "a".repeat(17 * 1024 * 1024) + ); + let padded = |jar: &[u8]| { + rewritten( + jar, + |_| true, + |m| m.replacen("Manifest-Version: 1.0", &pad, 1), + &[], + ) + }; + let (big_upstream, big_served) = (padded(upstream), padded(served)); + let files = record_of(upstream, served, &[PLAIN], &[]); + assert_eq!(refusal(&big_upstream, &big_served, &files), None); + + // A signed jar whose manifest inflates past what its size allows. + use std::io::Read as _; + let mut bomb = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + bomb.start_file(MANIFEST, opts).unwrap(); + std::io::copy(&mut std::io::repeat(0).take(65 * 1024 * 1024), &mut bomb).unwrap(); + bomb.start_file("META-INF/SOCKET.SF", opts).unwrap(); + let bomb = bomb.finish().unwrap().into_inner(); + let (was, is) = ( + Digests::of_bytes(upstream).unwrap(), + Digests::of_bytes(served).unwrap(), + ); + let limit = resigned((upstream, &was), (&bomb, &is), &files).unwrap_err(); + assert!(limit.is_too_large(), "{limit:?}"); + let limit = difference_outside_patch((upstream, &was), (&bomb, &is), &files).unwrap_err(); + assert!(limit.is_too_large(), "{limit:?}"); + } + + /// A member's SHA-256 is the one the comparison already holds, so a + /// section that lists it beside another digest inflates the member once + /// more, not twice: 40 MiB under SHA-1 fits what this jar may inflate, + /// 80 MiB would not. + #[test] + fn a_sha256_digest_is_checked_without_inflating_the_member_again() { + use std::io::Write as _; + const BIG: &str = "big.bin"; + let zeros = vec![0u8; 40 * 1024 * 1024]; + let b64 = |digest: &[u8]| base64::engine::general_purpose::STANDARD.encode(digest); + let sha1 = |bytes: &[u8]| b64(&::digest(bytes)); + let sha256 = |bytes: &[u8]| b64(&::digest(bytes)); + let jar = |manifest: String, big: &[u8], signature: &str| { + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, bytes) in [ + (MANIFEST, manifest.as_bytes()), + (BIG, big), + (signature, b"signature"), + ] { + out.start_file(name, opts).unwrap(); + out.write_all(bytes).unwrap(); + } + out.finish().unwrap().into_inner() + }; + let head = format!("Manifest-Version: 1.0\r\n\r\nName: {BIG}\r\n"); + let upstream = jar( + format!("{head}SHA1-Digest: {}\r\n\r\n", sha1(b"before")), + b"before", + "META-INF/UPSTREAM.SF", + ); + let served = jar( + format!( + "{head}SHA1-Digest: {}\r\nSHA-256-Digest: {}\r\n\r\n", + sha1(&zeros), + sha256(&zeros) + ), + &zeros, + "META-INF/SOCKET.SF", + ); + let files = record_of(&upstream, &served, &[BIG], &[]); + assert_eq!(refusal(&upstream, &served, &files), None); + } + + /// Attribute names are matched as a manifest reads them, without regard + /// to case: upstream's `SHA-256-digest` is the line the service writes + /// back as `SHA-256-Digest`. + #[test] + fn a_digest_attribute_is_matched_whatever_its_case() { + let (upstream, served) = service!("sha256"); + let lower = rewritten( + upstream, + |_| true, + |m| m.replacen("SHA-256-Digest: ", "SHA-256-digest: ", 1), + &[], + ); + assert!(manifest_of(&lower).contains(&format!("Name: {PLAIN}\r\nSHA-256-digest: "))); + let files = record_of(upstream, served, &[PLAIN], &[]); + assert_eq!(refusal(&lower, served, &files), None); + } + + /// Re-signing is named only for a signed jar. An unsigned jar whose + /// manifest differs is the ordinary wrong-base case, and reads as one. + #[test] + fn signing_is_named_only_for_a_signed_jar() { + let created = |m: String| m.replace("Created-By: ", "Built-By: "); + let describe = |served: &[u8]| { + let (was, is) = ( + Digests::of_bytes(UPSTREAM).unwrap(), + Digests::of_bytes(served).unwrap(), + ); + difference_outside_patch((UPSTREAM, &was), (served, &is), &record()) + .unwrap() + .describe() + }; + let unsigned = rewritten(SERVED, |n| !n.starts_with("META-INF/SOCKET."), created, &[]); + assert_eq!(describe(&unsigned), "1 changed (`META-INF/MANIFEST.MF`)"); + assert_eq!( + describe(&edited(created)), + "1 changed (`META-INF/MANIFEST.MF`), the manifest is not the original's as signing \ + the jar again leaves it: its main attributes differ" + ); + } + + /// Everything else stays the coded refusal, with its reason. + #[test] + fn any_other_manifest_difference_is_refused() { + let (upstream, served) = service!("sha1-only"); + let files = record_of(upstream, served, &[PLAIN], &[]); + let manifest = manifest_of(served); + let inserted = line(&manifest, UNTOUCHED, "SHA-256-Digest"); + let existing = line(&manifest, UNTOUCHED, "SHA1-Digest"); + let of_plain = line(&manifest, PLAIN, "SHA-256-Digest"); + let plain_sha1 = line(&manifest, PLAIN, "SHA1-Digest"); + let edit = |change: &dyn Fn(String) -> String| rewritten(served, |_| true, change, &[]); + let evil = base64::engine::general_purpose::STANDARD + .encode(::digest(b"evil")); + let cases: Vec<(&str, Vec, HashMap, &str)> = vec![ + ( + "an inserted digest that is not the member's", + edit(&|m| m.replace(&inserted, &of_plain)), + files.clone(), + "its SHA-256 digest of `fixture/Unicode.class` does not match the member in the jar", + ), + ( + "an inserted attribute that is not a digest", + edit(&|m| m.replace(&inserted, &format!("{inserted}\r\nSealed: true"))), + files.clone(), + "its section for `fixture/Unicode.class` adds or changes `Sealed`, which is not a \ + digest, though the patch does not touch the member", + ), + ( + "an inserted digest the JDK does not read", + edit(&|m| m.replace(&inserted, &format!("{inserted}\r\nSHA-224-Digest: AAAA"))), + files.clone(), + "adds or changes `SHA-224-Digest`, which is not a digest", + ), + ( + "a section for an entry the installed jar does not hold", + rewritten( + served, + |_| true, + |m| format!("{m}Name: fixture/Evil.class\r\nSHA-256-Digest: {evil}\r\n\r\n"), + &[("fixture/Evil.class", b"evil")], + ), + files.clone(), + "it adds a section for `fixture/Evil.class`, which is neither a member the patch \ + adds or changes nor an unchanged entry of the original jar", + ), + ( + "an existing line of an untouched section changed", + edit(&|m| m.replace(&existing, &plain_sha1)), + files.clone(), + "its section for `fixture/Unicode.class` changes or drops its `SHA1-Digest` line, \ + though the patch does not touch the member", + ), + ( + "an attribute of the changed member that is not a digest", + edit(&|m| m.replace(&of_plain, &format!("{of_plain}\r\nSealed: true"))), + files.clone(), + "its section for `fixture/Plain.class` adds or changes `Sealed`, which is not a digest", + ), + ( + "a stale digest of the changed member", + edit(&|m| m.replace(&plain_sha1, &existing)), + files.clone(), + "its SHA-1 digest of `fixture/Plain.class` does not match the member in the jar", + ), + ( + "a main attribute changed", + edit(&|m| m.replace("Manifest-Version: 1.0", "Manifest-Version: 1.0\r\nSealed: true")), + files.clone(), + "its main attributes differ", + ), + ( + "a dropped section", + edit(&|m| m.replace(&format!("Name: {UNTOUCHED}\r\n{existing}\r\n{inserted}\r\n\r\n"), "")), + files.clone(), + "it drops the section for `fixture/Unicode.class`", + ), + ( + "an unsigned jar with the edited manifest", + rewritten(served, |n| !n.starts_with("META-INF/SOCKET."), |m| m, &[]), + files.clone(), + "the patched jar is not signed", + ), + ( + "a record that does not change the member", + served.to_vec(), + HashMap::new(), + "its section for `fixture/Plain.class` changes or drops its `SHA1-Digest` line, \ + though the patch does not touch the member", + ), + ]; + for (what, served, files, why) in cases { + let refusal = refusal(upstream, &served, &files); + assert!( + refusal.as_deref().is_some_and(|r| r.contains(why)), + "{what}: {refusal:?}" + ); + } + } + + /// Lines wrap at 72 bytes with a leading space on the continuation, and + /// may end in `\n` or `\r` alone: a section is its bytes, its name is + /// the joined value. + #[test] + fn a_manifest_is_read_as_the_jar_specification_lays_it_out() { + let long = format!("org/example/{}.class", "x".repeat(80)); + let (first, rest) = long.split_at(72 - "Name: ".len()); + let text = format!( + "Manifest-Version: 1.0\nCreated-By: test\n\nName: {first}\n {rest}\nSHA-256-Digest: \ + AAAA\n\n\nName: b.class\rSHA-256-Digest: BBBB\r" + ); + let parsed = sections(text.as_bytes()).unwrap(); + assert_eq!(parsed.main, b"Manifest-Version: 1.0\nCreated-By: test\n"); + assert_eq!( + parsed.entries.keys().collect::>(), + [&b"b.class".to_vec(), &long.clone().into_bytes()] + ); + let section = &parsed.entries[long.as_bytes()].attributes; + assert_eq!(section.len(), 2); + assert_eq!(section[0].value, long.as_bytes()); + assert_eq!(section[1].name, b"SHA-256-Digest"); + assert_eq!( + parsed.entries[b"b.class".as_slice()].raw, + b"Name: b.class\rSHA-256-Digest: BBBB\r" + ); + for broken in [ + "Manifest-Version: 1.0\n\nSHA-256-Digest: AAAA\n", + "Manifest-Version: 1.0\n\nName: a\n\nName: a\n", + "Manifest-Version: 1.0\n\nName: a\nno colon here\n", + ] { + assert!(sections(broken.as_bytes()).is_err(), "{broken}"); + } + } +} diff --git a/crates/socket-patch-core/src/patch/jar_members.rs b/crates/socket-patch-core/src/patch/jar_members.rs index 73993b39c..09c209037 100644 --- a/crates/socket-patch-core/src/patch/jar_members.rs +++ b/crates/socket-patch-core/src/patch/jar_members.rs @@ -125,6 +125,8 @@ pub(crate) struct Jar { archive_len: u64, budget: u64, left: u64, + /// Member indices by the raw bytes of their names; built on first use. + names: Option, usize>>, } impl<'a> Jar> { @@ -158,9 +160,32 @@ impl Jar { archive_len, budget, left: budget, + names: None, }) } + /// The index of the member `name`, matched on the raw bytes of the + /// central directory, which is what a JVM matches on and what + /// [`Self::content_digests`] keys by. The zip reader's own lookup is by + /// a name it decodes as CP437 when the entry lacks the UTF-8 flag, so a + /// UTF-8 name written without that flag would be missed. Of two entries + /// with one name the last is the member. + fn index_of(&mut self, name: &str) -> Option { + if name.ends_with('/') { + return None; + } + if self.names.is_none() { + let mut names = std::collections::HashMap::new(); + for index in 0..self.zip.len() { + if let Ok(entry) = self.zip.by_index_raw(index) { + names.insert(entry.name_raw().to_vec(), index); + } + } + self.names = Some(names); + } + self.names.as_ref()?.get(name.as_bytes()).copied() + } + fn over_budget(&self) -> JarError { JarError::TooLarge(if self.budget < MAX_INFLATED_BYTES { format!( @@ -215,13 +240,99 @@ impl Jar { Ok(Digests(out)) } + /// Whether the jar holds a signature file (`META-INF/*.SF`, `.RSA`, + /// `.DSA`, `.EC`). + pub(crate) fn has_signature_file(&self) -> bool { + self.zip.file_names().any(crate::vendor::jvm::is_signature) + } + + /// Inflate the member `name` into `sink`, within the pass's budget. + /// `false` when the jar has no such member. + fn stream(&mut self, name: &str, mut sink: impl FnMut(&[u8])) -> Result { + let Some(index) = self.index_of(name) else { + return Ok(false); + }; + let mut left = self.left; + { + let mut entry = self.zip.by_index(index).map_err(|e| { + JarError::Unreadable(format!("member `{name}` cannot be read ({e})")) + })?; + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = entry.read(&mut buf).map_err(|e| { + JarError::Unreadable(format!("member `{name}` cannot be inflated ({e})")) + })?; + if n == 0 { + break; + } + if n as u64 > left { + drop(entry); + return Err(self.over_budget()); + } + left -= n as u64; + sink(&buf[..n]); + } + } + self.left = left; + Ok(true) + } + + /// The bytes of the member `name`, read within the pass's budget (the + /// only bound: a member a jar within the limits may hold is one that + /// can be read); `None` when the jar has no such member. + pub(crate) fn member_bytes(&mut self, name: &str) -> Result>, JarError> { + let mut bytes = Vec::new(); + let found = self.stream(name, |chunk| bytes.extend_from_slice(chunk))?; + Ok(found.then_some(bytes)) + } + + /// The digest of the member `name` under `algorithm`, named as a jar + /// manifest names it (`SHA-256`, `SHA1`, `SHA-512`, …); `None` when the + /// jar has no such member. + pub(crate) fn member_digest( + &mut self, + name: &str, + algorithm: &str, + ) -> Result>, JarError> { + enum Hasher { + Sha1(sha1::Sha1), + Sha256(Sha256), + Sha384(sha2::Sha384), + Sha512(sha2::Sha512), + Md5(Md5), + } + let mut hasher = match algorithm.replace('-', "").to_ascii_uppercase().as_str() { + "SHA1" => Hasher::Sha1(Default::default()), + "SHA256" => Hasher::Sha256(Default::default()), + "SHA384" => Hasher::Sha384(Default::default()), + "SHA512" => Hasher::Sha512(Default::default()), + "MD5" => Hasher::Md5(Md5::new()), + _ => { + return Err(JarError::Unreadable(format!( + "the digest algorithm {algorithm} is not one this reads" + ))) + } + }; + let found = self.stream(name, |chunk| match &mut hasher { + Hasher::Sha1(h) => h.update(chunk), + Hasher::Sha256(h) => h.update(chunk), + Hasher::Sha384(h) => h.update(chunk), + Hasher::Sha512(h) => h.update(chunk), + Hasher::Md5(h) => h.update(chunk), + })?; + Ok(found.then(|| match hasher { + Hasher::Sha1(h) => h.finalize().to_vec(), + Hasher::Sha256(h) => h.finalize().to_vec(), + Hasher::Sha384(h) => h.finalize().to_vec(), + Hasher::Sha512(h) => h.finalize().to_vec(), + Hasher::Md5(h) => h.finalize().to_vec(), + })) + } + /// The git-blob sha256 of the member `name`, `None` when the jar has no /// such member. Counts against the pass's budget. pub(crate) fn member_git_sha256(&mut self, name: &str) -> Result, JarError> { - if name.ends_with('/') { - return Ok(None); - } - let Some(index) = self.zip.index_for_name(name) else { + let Some(index) = self.index_of(name) else { return Ok(None); }; let entry = self @@ -242,6 +353,151 @@ impl Jar { } } +/// RFC 1321 MD5, for the `MD5-Digest` attributes of old jar manifests (the +/// crate has no MD5 otherwise, and nothing else here should use one). Fed +/// block by block, so a member is never held to be hashed. +struct Md5 { + state: [u32; 4], + block: [u8; 64], + held: usize, + length: u64, +} + +impl Md5 { + /// `floor(2^32 * abs(sin(i + 1)))`, as RFC 1321 tabulates it. + const K: [u32; 64] = [ + 0xd76a_a478, + 0xe8c7_b756, + 0x2420_70db, + 0xc1bd_ceee, + 0xf57c_0faf, + 0x4787_c62a, + 0xa830_4613, + 0xfd46_9501, + 0x6980_98d8, + 0x8b44_f7af, + 0xffff_5bb1, + 0x895c_d7be, + 0x6b90_1122, + 0xfd98_7193, + 0xa679_438e, + 0x49b4_0821, + 0xf61e_2562, + 0xc040_b340, + 0x265e_5a51, + 0xe9b6_c7aa, + 0xd62f_105d, + 0x0244_1453, + 0xd8a1_e681, + 0xe7d3_fbc8, + 0x21e1_cde6, + 0xc337_07d6, + 0xf4d5_0d87, + 0x455a_14ed, + 0xa9e3_e905, + 0xfcef_a3f8, + 0x676f_02d9, + 0x8d2a_4c8a, + 0xfffa_3942, + 0x8771_f681, + 0x6d9d_6122, + 0xfde5_380c, + 0xa4be_ea44, + 0x4bde_cfa9, + 0xf6bb_4b60, + 0xbebf_bc70, + 0x289b_7ec6, + 0xeaa1_27fa, + 0xd4ef_3085, + 0x0488_1d05, + 0xd9d4_d039, + 0xe6db_99e5, + 0x1fa2_7cf8, + 0xc4ac_5665, + 0xf429_2244, + 0x432a_ff97, + 0xab94_23a7, + 0xfc93_a039, + 0x655b_59c3, + 0x8f0c_cc92, + 0xffef_f47d, + 0x8584_5dd1, + 0x6fa8_7e4f, + 0xfe2c_e6e0, + 0xa301_4314, + 0x4e08_11a1, + 0xf753_7e82, + 0xbd3a_f235, + 0x2ad7_d2bb, + 0xeb86_d391, + ]; + const SHIFTS: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, + 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, + 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + + fn new() -> Self { + Md5 { + state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476], + block: [0; 64], + held: 0, + length: 0, + } + } + + fn update(&mut self, mut input: &[u8]) { + self.length = self.length.wrapping_add(input.len() as u64); + while !input.is_empty() { + let take = (64 - self.held).min(input.len()); + self.block[self.held..self.held + take].copy_from_slice(&input[..take]); + self.held += take; + input = &input[take..]; + if self.held == 64 { + self.compress(); + self.held = 0; + } + } + } + + fn compress(&mut self) { + let block = self.block; + let word = |i: usize| u32::from_le_bytes(block[4 * i..4 * i + 4].try_into().unwrap()); + let [mut a, mut b, mut c, mut d] = self.state; + for (i, (k, shift)) in Self::K.into_iter().zip(Self::SHIFTS).enumerate() { + let (mix, at) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let rotated = a + .wrapping_add(mix) + .wrapping_add(k) + .wrapping_add(word(at)) + .rotate_left(shift); + (a, d, c, b) = (d, c, b, b.wrapping_add(rotated)); + } + for (sum, add) in self.state.iter_mut().zip([a, b, c, d]) { + *sum = sum.wrapping_add(add); + } + } + + fn finalize(mut self) -> [u8; 16] { + let bits = self.length.wrapping_mul(8); + self.update(&[0x80]); + while self.held != 56 { + self.update(&[0]); + } + self.update(&bits.to_le_bytes()); + let mut out = [0u8; 16]; + for (bytes, word) in out.chunks_mut(4).zip(self.state) { + bytes.copy_from_slice(&word.to_le_bytes()); + } + out + } +} + /// A reader that shows zeros below `floor`, for as long as `floor` is set: /// what the zip reader is given while it opens an archive, so that it /// cannot take an end record [`admit`] did not look at. @@ -486,9 +742,8 @@ impl Digests { } /// The digest of the member `name`. - #[cfg(test)] - pub(crate) fn get(&self, name: &str) -> Option<&[u8; 32]> { - self.0.get(name.as_bytes()) + pub(crate) fn get(&self, name: impl AsRef<[u8]>) -> Option<&[u8; 32]> { + self.0.get(name.as_ref()) } } @@ -502,6 +757,11 @@ pub(crate) struct Difference { pub missing: Vec, /// In both, with other content. pub changed: Vec, + /// Why the manifest of a signed jar, when it is among `changed`, is not + /// the original's as signing the jar again leaves it + /// ([`super::jar_manifest`]). `None` for a jar that is not signed: its + /// manifest is a changed member like any other. + pub manifest: Option, } impl Difference { @@ -528,11 +788,43 @@ impl Difference { } format!("{} {kind} ({})", names.len(), shown.join(", ")) }) + .chain(self.manifest.iter().map(|why| { + format!("the manifest is not the original's as signing the jar again leaves it: {why}") + })) .collect::>() .join(", ") } } +/// [`unpatched_difference`] of two jars `(bytes, members)` for the record +/// `files`, less the manifest of a signed jar that differs only as signing +/// the patched jar again leaves it ([`super::jar_manifest::resigned`]): the +/// one member outside the patch whose content may change, and only so. +/// `Err` is a jar past a limit while its manifest was read. +pub(crate) fn difference_outside_patch( + original: (&[u8], &Digests), + patched: (&[u8], &Digests), + files: &std::collections::HashMap, +) -> Result { + use super::jar_manifest::{resigned, Resigned, MANIFEST}; + let names: Vec<&str> = files + .keys() + .map(|key| crate::patch::apply::normalize_file_path(key)) + .collect(); + let mut difference = unpatched_difference(original.1, patched.1, &names); + if let Some(at) = difference.changed.iter().position(|name| name == MANIFEST) { + match resigned(original, patched, files)? { + // Not signed: a base mismatch like any other member's. + Resigned::Unsigned => {} + Resigned::Accepted => { + difference.changed.remove(at); + } + Resigned::Refused(why) => difference.manifest = Some(why), + } + } + Ok(difference) +} + /// How `candidate` differs from `original` outside the members named in /// `patched` (manifest keys, already normalized) and signature files: /// empty when everything else a JVM would load is the same in both. @@ -590,6 +882,20 @@ pub(crate) mod testing { out.finish().unwrap().into_inner() } + /// `jar` with the UTF-8 flag cleared on every entry, as an archiver + /// that writes UTF-8 names without announcing them leaves it. For jars + /// whose member bytes do not spell a zip header. + pub(crate) fn without_utf8_flag(mut jar: Vec) -> Vec { + for at in 0..jar.len().saturating_sub(10) { + match &jar[at..at + 4] { + b"PK\x03\x04" => jar[at + 7] &= !0x08, + b"PK\x01\x02" => jar[at + 9] &= !0x08, + _ => {} + } + } + jar + } + /// An archive whose end records declare `entries` 46-byte central /// records where a directory would be, and hold none: a zip64 record /// that ends where its locator begins, the locator (pointing `early` @@ -654,6 +960,33 @@ mod tests { const OLD_ENTRIES: usize = 10_000; const OLD_BYTES: u64 = 64 * 1024 * 1024; + /// A member is found by the raw bytes of its name. A UTF-8 name written + /// without the UTF-8 flag is one the zip reader decodes as CP437, so its + /// own lookup misses it; a JVM reads the bytes. + #[test] + fn a_member_is_found_by_the_raw_bytes_of_its_name() { + const NAME: &str = "org/x/\u{dc}n\u{ef}.class"; + let bytes = testing::without_utf8_flag(jar(&[(NAME, b"code"), ("a/B.class", b"b")])); + let decoded: Vec = zip::ZipArchive::new(std::io::Cursor::new(&bytes)) + .unwrap() + .file_names() + .map(str::to_string) + .collect(); + assert!(!decoded.iter().any(|name| name == NAME), "{decoded:?}"); + let mut jar = Jar::of_bytes(&bytes).unwrap(); + assert_eq!( + jar.member_git_sha256(NAME).unwrap(), + Some(compute_git_sha256_from_bytes(b"code")) + ); + assert_eq!( + jar.member_bytes(NAME).unwrap().as_deref(), + Some(&b"code"[..]) + ); + assert!(jar.member_digest(NAME, "SHA-1").unwrap().is_some()); + assert!(Digests::of_bytes(&bytes).unwrap().get(NAME).is_some()); + assert_eq!(jar.member_git_sha256("org/x/absent.class").unwrap(), None); + } + /// A member's git hash is the buffered hash of its bytes, stored, /// deflated or empty; an absent member is `None`. #[test] @@ -715,6 +1048,75 @@ mod tests { ); } + #[test] + fn member_digests_are_the_algorithms_a_manifest_names() { + // The RFC 1321 test suite, the multi-block vectors among them. + let md5 = |input: &[u8]| { + let mut whole = Md5::new(); + whole.update(input); + let mut pieces = Md5::new(); + input.chunks(7).for_each(|piece| pieces.update(piece)); + let digest = hex::encode(whole.finalize()); + assert_eq!(digest, hex::encode(pieces.finalize()), "fed in pieces"); + digest + }; + const LETTERS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let digits = b"1234567890".repeat(8); + for (input, digest) in [ + (&b""[..], "d41d8cd98f00b204e9800998ecf8427e"), + (b"a", "0cc175b9c0f1b6a831c399e269772661"), + (b"abc", "900150983cd24fb0d6963f7d28e17f72"), + (b"message digest", "f96b697d7cb7938d525a2f31aaf161d0"), + ( + b"abcdefghijklmnopqrstuvwxyz", + "c3fcd3d76192e4007dfb496cca67e13b", + ), + (LETTERS, "d174ab98d277d9f5a5611c2c9f419d9f"), + (&digits, "57edf4a22be3c955ac49da2e2107b67a"), + ] { + assert_eq!(md5(input), digest, "{:?}", String::from_utf8_lossy(input)); + } + // A member of more than one block, and of many. + let long = b"1234567890".repeat(100_000); + let big = jar(&[("a/Digits.class", &digits), ("a/Long.class", &long)]); + let mut big = Jar::of_bytes(&big).unwrap(); + assert_eq!( + big.member_digest("a/Digits.class", "MD5") + .unwrap() + .map(hex::encode) + .unwrap(), + "57edf4a22be3c955ac49da2e2107b67a" + ); + assert_eq!( + big.member_digest("a/Long.class", "MD5") + .unwrap() + .map(hex::encode) + .unwrap(), + md5(&long) + ); + let bytes = jar(&[("a/B.class", b"abc")]); + let digest = |algorithm: &str| { + let mut jar = Jar::of_bytes(&bytes).unwrap(); + jar.member_digest("a/B.class", algorithm) + .map(|d| d.map(hex::encode)) + }; + assert_eq!( + digest("MD5").unwrap().unwrap(), + "900150983cd24fb0d6963f7d28e17f72" + ); + assert_eq!( + digest("SHA-1").unwrap().unwrap(), + "a9993e364706816aba3e25717850c26c9cd0d89d" + ); + assert_eq!(digest("SHA-256").unwrap().unwrap().len(), 64); + assert!(digest("SHA-224").is_err()); + let mut jar = Jar::of_bytes(&bytes).unwrap(); + assert_eq!( + jar.member_digest("a/Absent.class", "SHA-256").unwrap(), + None + ); + } + #[test] fn the_entry_limit_names_the_count() { let members: Vec<(String, &[u8])> = (0..=MAX_ENTRIES) @@ -942,6 +1344,7 @@ mod tests { added: vec!["a/New.class".into()], missing: vec!["a/Gone.class".into()], changed: vec!["a/C.class".into()], + manifest: None, } ); assert_eq!( diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index a01dcb933..94db45cab 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -36,7 +36,7 @@ use crate::patch::apply::{ apply_file_patch_at, files_in_order, normalize_file_path, ApplyResult, VerifyResult, VerifyStatus, }; -use crate::patch::jar_members::{unpatched_difference, Digests, Jar, JarError}; +use crate::patch::jar_members::{difference_outside_patch, Difference, Digests, Jar, JarError}; use crate::patch::rollback::{RollbackResult, VerifyRollbackResult, VerifyRollbackStatus}; use crate::patch::sidecars::{self, maven as maven_sidecars}; use crate::utils::purl::{parse_maven_purl, purl_qualifier}; @@ -412,11 +412,6 @@ fn result_for(swap: &JarSwap<'_>, dir: &Path) -> ApplyResult { } } -/// The member names a record patches, as a jar spells them. -fn patched_names(files: &HashMap) -> Vec<&str> { - files.keys().map(|k| normalize_file_path(k)).collect() -} - fn sha256_hex(bytes: &[u8]) -> String { crate::utils::digest::sha256_hex_of(bytes) } @@ -607,19 +602,28 @@ async fn swap_copies( // inflates the download, then of each original. Identical originals // (one jar in several caches) are read once, keyed by their sha256. let files = swap.files.clone(); - let (jar, originals, service_members, copy_members) = blocking(move || { + let (jar, originals, service_members, differences) = blocking(move || { use sha2::Digest as _; let service = Digests::of_bytes(&jar).map(|members| { // After the bounded pass: this inflates only what that one did. crate::vendor::common::zip_bytes_match_after_hashes(&jar, &files).then_some(members) }); - let mut read: HashMap<[u8; 32], Result> = HashMap::new(); - let copies: Vec> = match &service { - Ok(Some(_)) => pending + // Per copy: everything the patch does not touch must be upstream's. + let mut read: HashMap<[u8; 32], Result> = HashMap::new(); + let copies: Vec> = match &service { + Ok(Some(service)) => pending .iter() .map(|(_, original)| { read.entry(sha2::Sha256::digest(original).into()) - .or_insert_with(|| Digests::of_bytes(original)) + .or_insert_with(|| { + Digests::of_bytes(original).and_then(|members| { + difference_outside_patch( + (original, &members), + (&jar, service), + &files, + ) + }) + }) .clone() }) .collect(), @@ -628,8 +632,8 @@ async fn swap_copies( (jar, pending, service, copies) }) .await; - let service_members = match service_members { - Ok(Some(members)) => members, + match service_members { + Ok(Some(_)) => {} Ok(None) => { return Err(SwapRefusal::new( SERVICE_JAR_MISMATCH, @@ -653,14 +657,11 @@ async fn swap_copies( )) } }; - // Per copy: everything the patch does not touch must be upstream's. - let patched = patched_names(swap.files); let mut pending = Vec::new(); - for ((i, original), members) in originals.into_iter().zip(copy_members) { + for ((i, original), difference) in originals.into_iter().zip(differences) { let path = Path::new(&results[i].package_path).join(swap.jar_leaf); - let refusal = match members { - Ok(members) => { - let difference = unpatched_difference(&members, &service_members, &patched); + let refusal = match difference { + Ok(difference) => { if difference.is_empty() { pending.push((i, original)); continue; @@ -859,7 +860,7 @@ fn m2_backup( }; let found = backups(socket_dir).into_iter().find_map(|path| { let bytes = crate::utils::fs::read_regular_to_bytes_sync(&path).ok()?; - is_original_of(&bytes, &members, files).then_some(bytes) + is_original_of(&bytes, (current, &members), files).then_some(bytes) }); match found { Some(bytes) => M2Original::Backup(bytes), @@ -884,12 +885,13 @@ fn members_at_before(candidate: &[u8], files: &HashMap) - /// other member the patched copy's. fn is_original_of( candidate: &[u8], - patched_copy: &Digests, + patched_copy: (&[u8], &Digests), files: &HashMap, ) -> bool { members_at_before(candidate, files) && Digests::of_bytes(candidate).is_ok_and(|members| { - unpatched_difference(&members, patched_copy, &patched_names(files)).is_empty() + difference_outside_patch((candidate, &members), patched_copy, files) + .is_ok_and(|difference| difference.is_empty()) }) } @@ -922,30 +924,38 @@ async fn upstream_for_gradle_copy(purl: &str, jar_leaf: &str, dir: &Path) -> Opt /// that file for the patched jar. `Err` says what was missing. async fn upstream_for_m2_copy( restore: &JarRestore<'_>, - current: Digests, -) -> Result, String> { - let (group, artifact, version) = - parse_maven_purl(restore.purl).ok_or("its purl names no Maven coordinates")?; - let bytes = crate::vendor::maven_repo::verified_registry_file( + current: Vec, + members: Digests, +) -> (Vec, Result, String>) { + let Some((group, artifact, version)) = parse_maven_purl(restore.purl) else { + let why = "its purl names no Maven coordinates".to_string(); + return (current, Err(why)); + }; + let fetched = crate::vendor::maven_repo::verified_registry_file( &group, &artifact, &version, restore.jar_leaf, ) - .await?; + .await; + let bytes = match fetched { + Ok(bytes) => bytes, + Err(why) => return (current, Err(why)), + }; let files = restore.files.clone(); - let (bytes, original) = blocking(move || { - let original = is_original_of(&bytes, ¤t, &files); - (bytes, original) + let (current, bytes, original) = blocking(move || { + let original = is_original_of(&bytes, (¤t, &members), &files); + (current, bytes, original) }) .await; if !original { - return Err(format!( + let why = format!( "the registry's {} is not the jar this copy was patched from", restore.jar_leaf - )); + ); + return (current, Err(why)); } - Ok(bytes) + (current, Ok(bytes)) } /// What to do about a copy with no original to restore: said with every @@ -1074,10 +1084,12 @@ pub async fn rollback_jar_swap( (current, found) }) .await; - let original = match found { - M2Original::Backup(bytes) => Ok(bytes), - M2Original::NoBackup(_) if restore.offline => Err(OFFLINE.to_string()), - M2Original::NoBackup(members) => upstream_for_m2_copy(restore, members).await, + let (current, original) = match found { + M2Original::Backup(bytes) => (current, Ok(bytes)), + M2Original::NoBackup(_) if restore.offline => (current, Err(OFFLINE.to_string())), + M2Original::NoBackup(members) => { + upstream_for_m2_copy(restore, current, members).await + } M2Original::Unread(e) => { let delete = format!( "It was left as it is; delete {} so the build downloads the jar again.", @@ -1911,6 +1923,51 @@ mod tests { assert!(std::fs::read(hash_dir.join("lib-1.0.jar")).unwrap() == original); } + /// A signed jar the patch service patched and re-signed differs from + /// the installed one in its signature files and in the manifest digests + /// of the member the patch changes. It is swapped in, and rolled back to + /// the original from the backup. Any other manifest change stays the + /// coded refusal, with its reason. + #[tokio::test] + async fn a_resigned_provider_jar_swaps_and_rolls_back() { + use crate::patch::jar_manifest::fixture::{edited, record as resigned, SERVED, UPSTREAM}; + let files = resigned(); + let d = tempfile::tempdir().unwrap(); + let socket = d.path().join(".socket"); + let copy = d.path().join("m2/com/example/lib/1.0"); + std::fs::create_dir_all(©).unwrap(); + std::fs::write(copy.join("lib-1.0.jar"), UPSTREAM).unwrap(); + + let tampered = + edited(|m| m.replace("Implementation-Version: 1.0", "Implementation-Version: 9")); + let (_server, cfg) = mock_service(&tampered, &tampered).await; + let out = apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], Some(&cfg)) + .await + .unwrap(); + let refusal = out[0].refusal.as_ref().expect("a coded refusal"); + assert_eq!(refusal.code, SERVICE_JAR_MISMATCH); + assert!( + refusal + .message + .contains("1 changed (`META-INF/MANIFEST.MF`)") + && refusal.message.contains("its main attributes differ"), + "{}", + refusal.message + ); + assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), UPSTREAM); + + let (_server, cfg) = mock_service(SERVED, SERVED).await; + let out = apply_jar_swap(&swap(&files, &socket, false), &[copy.clone()], Some(&cfg)) + .await + .unwrap(); + assert!(out[0].success, "{:?}", out[0].error); + assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), SERVED); + + let back = rollback_jar_swap(&restore(&files, &socket, true), &[copy.clone()]).await; + assert!(back[0].success, "{:?}", back[0].error); + assert_eq!(std::fs::read(copy.join("lib-1.0.jar")).unwrap(), UPSTREAM); + } + /// The bounded reader is the first thing that parses a copy, on apply /// and on rollback. This archive's end records declare 200,001 entries /// and it holds no central directory at all: only a reader that holds diff --git a/crates/socket-patch-core/src/patch/mod.rs b/crates/socket-patch-core/src/patch/mod.rs index 0bc36ee26..3281e259d 100644 --- a/crates/socket-patch-core/src/patch/mod.rs +++ b/crates/socket-patch-core/src/patch/mod.rs @@ -6,6 +6,7 @@ pub(crate) mod file_hash; pub mod gem_ext; pub mod gem_refresh; pub(crate) mod gem_source; +pub(crate) mod jar_manifest; pub(crate) mod jar_members; pub mod jvm_jar; pub(crate) mod npm_bin; diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index a2634ed83..004be3320 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -1074,18 +1074,14 @@ async fn vendor_maven_jvm( // nothing to say. (An offline re-run compares nothing, as before.) if !was_committed || online { if let Ok(Some(resolved)) = local.find(&gav, None, "jar", false).await { - let names: Vec = record - .files - .keys() - .map(|k| crate::patch::apply::normalize_file_path(k).to_string()) - .collect(); + let files = record.files.clone(); let leaf = layout::file_name(&artifact_id, &version, None, "jar"); // Off the async workers: a pass inflates up to the jar limits. let compared = tokio::task::spawn_blocking(move || { let verdict = verify_unpatched_jar_members( (&leaf, &resolved), &jar_bytes, - &names, + &files, was_committed, ); (jar_bytes, verdict) @@ -1500,25 +1496,29 @@ async fn acquire_classifier( /// The patched jar (the service's on a first vendoring, the committed one /// on a re-run) against `resolved`, the jar `(leaf, bytes)` the build -/// resolves from its local repository: outside the record's members -/// (`patched_members`, as a jar spells them) and signature files, every -/// member a JVM would load must be the same in both -/// ([`crate::patch::jar_members`], whose limits also bound the read). A -/// local jar that cannot be read gives nothing to compare with. `Err` is -/// the refusal's `(code, detail)`. +/// resolves from its local repository: outside the record `files` and +/// signature files, every member a JVM would load must be the same in both +/// ([`crate::patch::jar_members`], whose limits also bound the read). For a +/// jar the service signed again, the manifest may differ as that signing +/// leaves it: digest lines changed or added, and sections added for +/// entries it did not list ([`crate::patch::jar_manifest`]). A local jar +/// that cannot be read gives nothing to compare with. `Err` is the +/// refusal's `(code, detail)`. fn verify_unpatched_jar_members( resolved: (&str, &[u8]), patched: &[u8], - patched_members: &[String], + files: &std::collections::HashMap, committed: bool, ) -> Result<(), (&'static str, String)> { - use crate::patch::jar_members::{unpatched_difference, Digests, JarError}; + use crate::patch::jar_members::{difference_outside_patch, Digests, JarError}; let whose = if committed { "the committed jar" } else { "the patch service's jar" }; - let candidate = Digests::of_bytes(patched).map_err(|e| match e { + // A jar past a limit is too large, whichever read met the limit; it is + // never reported as a jar that differs. + let unread = |e: JarError| match e { JarError::TooLarge(why) => ( super::verify::ARTIFACT_TOO_LARGE, format!("{whose} cannot be checked: {why}"), @@ -1527,12 +1527,14 @@ fn verify_unpatched_jar_members( "vendor_prebuilt_integrity_mismatch", format!("{whose} cannot be read: {why}"), ), - })?; + }; + let candidate = Digests::of_bytes(patched).map_err(unread)?; let Ok(original) = Digests::of_bytes(resolved.1) else { return Ok(()); }; - let names: Vec<&str> = patched_members.iter().map(String::as_str).collect(); - let difference = unpatched_difference(&original, &candidate, &names); + let difference = + difference_outside_patch((resolved.1, &original), (patched, &candidate), files) + .map_err(unread)?; if !difference.is_empty() { return Err(( "vendor_prebuilt_integrity_mismatch", @@ -4416,6 +4418,31 @@ mod tests { } } + /// The vendored comparison accepts a jar the patch service re-signed + /// (its signature files, and the manifest digests of the member the + /// patch changes) and refuses any other manifest change. + #[test] + fn a_resigned_provider_jar_is_upstream_outside_the_patch() { + use crate::patch::jar_manifest::fixture::{edited, record as resigned, SERVED, UPSTREAM}; + let files = resigned(); + for committed in [false, true] { + assert_eq!( + verify_unpatched_jar_members(("lib-1.0.jar", UPSTREAM), SERVED, &files, committed), + Ok(()) + ); + } + let tampered = edited(|m| m.replace("Implementation-Title: ", "Implementation-Title: x")); + let (code, detail) = + verify_unpatched_jar_members(("lib-1.0.jar", UPSTREAM), &tampered, &files, false) + .unwrap_err(); + assert_eq!(code, "vendor_prebuilt_integrity_mismatch"); + assert!( + detail.contains("1 changed (`META-INF/MANIFEST.MF`)") + && detail.contains("its main attributes differ"), + "{detail}" + ); + } + /// commons-text as log4j-core is published: a sibling's version comes /// from the parent's management, written `${project.version}`. const CHILD_OF_PARENT_POM: &str = "4.0.0\ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/make.sh b/crates/socket-patch-core/tests/data/resigned-provider/make.sh new file mode 100755 index 000000000..52840f678 --- /dev/null +++ b/crates/socket-patch-core/tests/data/resigned-provider/make.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Rebuild upstream.jar and served.jar: a jar jarsigner signed, and the same +# jar with org/example/B.class changed, upstream's signature files dropped +# and jarsigner run again under the alias SOCKET (what the patch service's +# re-signing of a patched security provider produces). Needs a JDK +# (jar, keytool, jarsigner) and python3; the keys are throwaway, so the +# jars differ from the committed ones in their signature blocks only. +# +# ./make.sh +set -euo pipefail +work=$(cd "$1" && pwd) +here=$(cd "$(dirname "$0")" && pwd) +cd "$work" +mkdir -p src/org/example home +printf '\xca\xfe\xba\xbe class A' > src/org/example/A.class +printf '\xca\xfe\xba\xbe class B, vulnerable' > src/org/example/B.class +printf '\xca\xfe\xba\xbe class C' > src/org/example/C.class +printf 'provider notice\n' > src/NOTICE.txt +printf 'Implementation-Title: example-provider\nImplementation-Version: 1.0\n' > manifest.txt +home="-J-Duser.home=$work/home" +jar "$home" --create --file upstream.jar --manifest manifest.txt -C src . +for alias in upstream socket; do + keytool "$home" -genkeypair -alias "$alias" -keyalg RSA -keysize 2048 \ + -dname "CN=$alias test key" -validity 36500 \ + -keystore ks.p12 -storetype PKCS12 -storepass changeit +done +sign() { + jarsigner "$home" -keystore ks.p12 -storepass changeit -digestalg SHA-256 "$@" +} +sign -sigfile UPSTREAM upstream.jar upstream +python3 - <<'PY' +import zipfile +src = zipfile.ZipFile('upstream.jar') +out = zipfile.ZipFile('served.jar', 'w', zipfile.ZIP_DEFLATED) +for info in src.infolist(): + if info.filename.startswith('META-INF/UPSTREAM.'): + continue + data = src.read(info.filename) + if info.filename == 'org/example/B.class': + data = b'\xca\xfe\xba\xbe class B, fixed' + out.writestr(info, data) +out.close() +PY +sign -sigfile SOCKET served.jar socket +jarsigner "$home" -verify served.jar +cp upstream.jar served.jar "$here/" diff --git a/crates/socket-patch-core/tests/data/resigned-provider/served.jar b/crates/socket-patch-core/tests/data/resigned-provider/served.jar new file mode 100644 index 000000000..74acdcff5 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/served.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.jar new file mode 100644 index 000000000..308bdb727 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.upstream.jar new file mode 100644 index 000000000..033e525b2 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/manifest-in-record.upstream.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.jar new file mode 100644 index 000000000..0118e2ab7 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.upstream.jar new file mode 100644 index 000000000..8b281f23c Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/sha1-only.upstream.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.jar new file mode 100644 index 000000000..1287ede2c Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.upstream.jar new file mode 100644 index 000000000..7746ff674 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/sha256.upstream.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.jar new file mode 100644 index 000000000..34bcf7653 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.upstream.jar new file mode 100644 index 000000000..4f7ab20a1 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/unlisted.upstream.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.jar new file mode 100644 index 000000000..dc6049f76 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.upstream.jar new file mode 100644 index 000000000..b41803424 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/service/unterminated-line.upstream.jar differ diff --git a/crates/socket-patch-core/tests/data/resigned-provider/upstream.jar b/crates/socket-patch-core/tests/data/resigned-provider/upstream.jar new file mode 100644 index 000000000..8cbfb9015 Binary files /dev/null and b/crates/socket-patch-core/tests/data/resigned-provider/upstream.jar differ diff --git a/docs/ecosystems.md b/docs/ecosystems.md index f4a1b214b..88b4b8849 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1363,7 +1363,12 @@ keyed by members inside a jar swap in the patch service's build of the whole jar they need network access (`jvm_agent_service_required` offline). Before the swap the service's jar is compared with the installed one member by member: everything the JVM would load outside the patched members and signature files must be identical, or -that copy is left alone (`jvm_agent_service_jar_mismatch`, naming the members). Jars +that copy is left alone (`jvm_agent_service_jar_mismatch`, naming the members). A +signed jar the patch service signed again (a security provider such as Bouncy +Castle's) may also differ in its manifest, as that signing leaves it: digest lines +changed for the patched members and added for the others, and sections added for +entries the manifest did not list. Nothing else of the manifest may differ; the CLI +contract has the rule. Jars of up to 200,000 entries and 1 GiB inflated are handled; one past that is `jvm_jar_too_large`. The original is backed up under `.socket/jvm-originals/` and `rollback` restores from it. A `~/.m2`