From a13adaaf80ae2dd6900022f87df2b2102ac44738 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:36:32 -0600 Subject: [PATCH 1/2] spots: check spot signatures as Spotweb does A spot's From header carries RSA signatures (PKCS #1 v1.5, SHA-1): the header signed by Spotnet's keys 2-4, or a self-signed key-7 spot with a hashcash, and the message-id signed by the spotter's own key. Spots are now kept only when these hold, checked on the overview and again on the HEAD (for spots noted before), and the spotter id stored is the one the spotter's signature proves. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 1 + src/spotnet/header.rs | 34 +++++-- src/spotnet/ingest.rs | 31 ++++-- src/spotnet/mod.rs | 6 +- src/spotnet/sign.rs | 214 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 270 insertions(+), 17 deletions(-) create mode 100644 src/spotnet/sign.rs diff --git a/Cargo.lock b/Cargo.lock index 7afa2814..1c969afe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -231,6 +231,7 @@ dependencies = [ "lzma-rs", "md-5 0.10.6", "nntmux-yenc", + "num-bigint", "par-rs", "postgres", "quick-xml", diff --git a/Cargo.toml b/Cargo.toml index d9cab3b2..f220dc7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ path = "src/main.rs" anyhow = "1" base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +num-bigint = "0.4" flate2 = "1" getrandom = "0.3" indexmap = "2" diff --git a/src/spotnet/header.rs b/src/spotnet/header.rs index d915b52e..2d328aea 100644 --- a/src/spotnet/header.rs +++ b/src/spotnet/header.rs @@ -121,11 +121,26 @@ pub fn subcats(list: &str) -> Subcats { out } -/// The spotter id of the spot whose headers these are, from its `From`. -pub fn spotter_id_of_head(head: &[u8]) -> Option { +/// The value of the header `name` in an article's headers, unfolded (a line that starts with a space or tab goes on +/// the one before it). +pub fn header_value(head: &[u8], name: &str) -> Option { let text = String::from_utf8_lossy(head); - let from = text.lines().find_map(|l| l.get(..5).filter(|p| p.eq_ignore_ascii_case("from:")).map(|_| &l[5..]))?; - spotter_id_of_from(from) + let mut lines = text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)); + let mut value = loop { + let line = lines.next()?; + if line.is_empty() { + return None; + } + if let Some((n, v)) = line.split_once(':') + && n.eq_ignore_ascii_case(name) + { + break v.trim_start().to_string(); + } + }; + for line in lines.take_while(|l| l.starts_with([' ', '\t'])) { + value.push_str(line); + } + Some(value) } /// The spotter id a Spotnet `From` value carries: its address is the poster's public key, `.`, the signature. @@ -240,10 +255,13 @@ mod tests { } #[test] - fn spotter_id_from_headers() { - let head = b"Path: x\nFrom: Senua <1FNddBgs6c-pMxF9DDUjo9SQmtH-pgI5xOShhXz6EyZ7GHuXXWG-sSKP8sXt2EfOcz9.sig@17a09.1.2.3.4.5.6>\nSubject: s\n"; - assert_eq!(spotter_id_of_head(head).as_deref(), Some("baTFcw")); - assert_eq!(spotter_id_of_head(b"Subject: s\n"), None); + fn header_values() { + let head = b"Path: x\r\nFrom: Senua <1FNdd.sig@17a09.1.2.3.4.5.6>\r\nSubject: a\r\n\tb\r\nX: y\r\n"; + assert_eq!(header_value(head, "from").as_deref(), Some("Senua <1FNdd.sig@17a09.1.2.3.4.5.6>")); + assert_eq!(header_value(head, "Subject").as_deref(), Some("a\tb")); + assert_eq!(header_value(head, "Date"), None); + // the body isn't headers + assert_eq!(header_value(b"X: y\n\nDate: z\n", "Date"), None); } #[test] diff --git a/src/spotnet/ingest.rs b/src/spotnet/ingest.rs index eb61d540..2b846e87 100644 --- a/src/spotnet/ingest.rs +++ b/src/spotnet/ingest.rs @@ -1,7 +1,8 @@ -//! Reads new spots from `free.pt` every `poll_minutes`: the overview first, keeping the signed movie and TV spots, -//! then each of those whole (HEAD for its XML, BODY for its NZB in `alt.binaries.ftd`), saved as a release and -//! tagged with its spot. About 75 spots a day pass the filter. Spots are fetched `concurrency` at a time: each -//! request queues for a connection behind indexing, so one at a time was minutes a spot on a busy indexer. +//! Reads new spots from `free.pt` every `poll_minutes`: the overview first, keeping the movie and TV spots whose +//! signatures hold (`sign`), then each of those whole (HEAD for its XML, BODY for its NZB in `alt.binaries.ftd`), +//! saved as a release and tagged with its spot. About 75 spots a day pass the filter. Spots are fetched +//! `concurrency` at a time: each request queues for a connection behind indexing, so one at a time was minutes a +//! spot on a busy indexer. //! //! Comments and spam reports on the spots kept (`comments`) are read by a task of their own, `run_comments`: //! with a backlog of spots a spot pass takes an hour, and comments read after it waited that long. @@ -18,7 +19,7 @@ use crate::indexer::{Db, on_db}; use crate::nntp::{Pool, says_absent}; use super::store::{self, SAVED, SKIPPED, Settled, SpotRow}; -use super::{MAX_XML_BYTES, SPOT_GROUP, binary, comments, full, header, release}; +use super::{MAX_XML_BYTES, SPOT_GROUP, binary, comments, full, header, release, sign}; /// Overview lines asked for in one XOVER. const XOVER_STEP: u64 = 5_000; @@ -277,6 +278,17 @@ async fn fetch( Err(e) if says_absent(&e) => return Ok(Some(skipped(None))), Err(e) => return Err(e.into()), }; + // checked again here, for spots noted before the overview was checked + let (subject, from) = (header::header_value(&head, "Subject"), header::header_value(&head, "From")); + let verdict = match (subject, from) { + (Some(subject), Some(from)) => { + header::parse(&subject, &from).map(|h| sign::verify(&h.title, &from, message_id)).unwrap_or_default() + } + _ => sign::Verdict::default(), + }; + if !verdict.verified { + return Ok(Some(skipped(None))); + } let Some(xml) = full::xml_from_headers(&head) else { return Ok(Some(skipped(None))) }; let Some(spot) = full::parse(&xml) else { return Ok(Some(skipped(None))) }; let Some(kind) = spot.kind() else { return Ok(Some(skipped(None))) }; @@ -284,7 +296,7 @@ async fn fetch( if spot.nzb.is_empty() || !nzb_ids_usable(&spot.nzb) { return Ok(Some(skipped(None))); } - let spotter_id = header::spotter_id_of_head(&head); + let spotter_id = verdict.spotter_id; let row = |nzb_key: String| SpotRow { message_id: message_id.to_string(), kind, @@ -446,7 +458,12 @@ async fn read_overview( .iter() .filter_map(|r| { let h = header::parse(&r.subject, &r.from).filter(header::SpotHeader::wanted)?; - Some((r.message_id.trim_matches(['<', '>']).to_string(), r.number, h.spotter_id())) + // a spot whose signatures don't hold is one anyone could have posted: Spotweb drops it too + let verdict = sign::verify(&h.title, &r.from, &r.message_id); + if !verdict.verified { + return None; + } + Some((r.message_id.trim_matches(['<', '>']).to_string(), r.number, verdict.spotter_id)) }) .collect(); let key = host.clone(); diff --git a/src/spotnet/mod.rs b/src/spotnet/mod.rs index 1a349862..35d40cce 100644 --- a/src/spotnet/mod.rs +++ b/src/spotnet/mod.rs @@ -4,8 +4,9 @@ //! //! `header`, `full` and `binary` read the formats: the overview line, the full spot XML and the posted binaries. //! `release` turns a spot's NZB into a release, `store` keeps the bookkeeping and the tags, `ingest` is the -//! indexer's task that reads new spots, `comments` keeps what's said about them (comments, spam reports), and -//! `names` says what a spot's subcategories mean, and `ubb` renders a spot's or comment's text. +//! indexer's task that reads new spots, `comments` keeps what's said about them (comments, spam reports), +//! `names` says what a spot's subcategories mean, `ubb` renders a spot's or comment's text, and `sign` checks a +//! spot's signatures. pub mod binary; pub mod comments; @@ -14,6 +15,7 @@ pub mod header; pub mod ingest; pub mod names; pub mod release; +pub mod sign; pub mod store; pub mod ubb; diff --git a/src/spotnet/sign.rs b/src/spotnet/sign.rs new file mode 100644 index 00000000..8c76ae80 --- /dev/null +++ b/src/spotnet/sign.rs @@ -0,0 +1,214 @@ +//! Checks a spot's signatures the way Spotweb does, so a spot or a moderator's command that anyone could have +//! posted under another's name isn't taken. +//! +//! A spot's `From` is `Nickname .>`. The header signature is RSA (PKCS #1 +//! v1.5, SHA-1) over the title, the header up to its signature and the nickname. Keys 2 to 4 are Spotnet's own +//! (2 the moderators'), signed by its signing server; key 7 is a spot the spotter signed with their own key, which +//! must carry a hashcash (the SHA-1 of its message-id starts with four zero hex digits) to cost its poster some +//! work. A `From` that carries the spotter's key and signature must also have the message-id signed with that key: +//! that's what makes the spotter id theirs. + +use num_bigint::BigUint; +use sha1::{Digest, Sha1}; + +use super::header::{decode_base64, spotter_id, unprepare_base64}; + +/// Spotnet's public keys by key id (moduli, base64; the exponent is 65537): the ones Spotweb ships. +const SPOTNET_KEYS: [(i32, &str); 3] = [ + (2, "ys8WSlqonQMWT8ubG0tAA2Q07P36E+CJmb875wSR1XH7IFhEi0CCwlUzNqBFhC+P"), + (3, "uiyChPV23eguLAJNttC/o0nAsxXgdjtvUvidV2JL+hjNzc4Tc/PPo2JdYvsqUsat"), + (4, "1k6RNDVD6yBYWR6kHmwzmSud7JkNV4SMigBrs+jFgOK5Ldzwl17mKXJhl+su/GR9"), +]; + +/// The key id of a spot the spotter signed with their own key. +pub const SELF_SIGNED_KEY: i32 = 7; + +/// A user key in a key-2 `From` longer than this makes it a spotter's own `DISPOSE` of their spot, not a +/// moderator's command. +const PERSONAL_KEY_LEN: usize = 50; + +/// What the signatures of an overview line say. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Verdict { + /// the spot (or command) is genuine: Spotweb would take it + pub verified: bool, + /// the spotter whose key signed it, when one did + pub spotter_id: Option, + /// a key-2 command signed by a spotter's own key rather than Spotnet's moderator key: it may only remove a spot + /// of that same spotter + pub personal: bool, +} + +/// Checks the signatures of the spot (or moderator's command) whose overview gives `subject`, `from` and +/// `message_id` (with or without its brackets). `title` is the title `header::parse` read from `subject`. +pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { + let no = Verdict::default(); + let message_id = format!("<{}>", message_id.trim().trim_matches(['<', '>'])); + let Some(open) = from.find('<') else { return no }; + let address = from[open + 1..].strip_suffix('>').unwrap_or(&from[open + 1..]); + let Some((local, header)) = address.split_once('@') else { return no }; + let fields: Vec<&str> = header.split('.').collect(); + let head = fields[0].as_bytes(); + if fields.len() < 6 || head.len() < 2 || !head[1].is_ascii_digit() { + return no; + } + let key_id = i32::from(head[1] - b'0'); + let header_sig = fields[fields.len() - 1]; + if header_sig.is_empty() || title.is_empty() { + return no; + } + // Spotweb drops the one character before the `<` (the space) and nothing else + let poster = &from[..open.saturating_sub(1)]; + let signed = format!("{title}{}{poster}", &header[..header.len() - header_sig.len() - 1]); + let Some(header_sig) = decode_base64(&unprepare_base64(header_sig)) else { return no }; + let (user_key, user_sig) = match local.split_once('.') { + Some((k, s)) => (unprepare_base64(k), Some(unprepare_base64(s))), + None => (unprepare_base64(local), None), + }; + let user_modulus = decode_base64(&user_key).unwrap_or_default(); + let by_user = || !user_modulus.is_empty() && rsa_sha1(signed.as_bytes(), &header_sig, &user_modulus); + + let mut verdict = Verdict::default(); + if key_id == SELF_SIGNED_KEY { + // the hashcash is what Spotweb requires; the header signature, when it holds, names the spotter + verdict.verified = hashcash(&message_id); + if verdict.verified && by_user() { + verdict.spotter_id = spotter_id(&user_key); + } + } else if let Some((_, modulus)) = SPOTNET_KEYS.iter().find(|(k, _)| *k == key_id) { + if key_id == 2 && user_key.len() > PERSONAL_KEY_LEN { + verdict.personal = true; + verdict.verified = hashcash(&message_id); + if verdict.verified && by_user() { + verdict.spotter_id = spotter_id(&user_key); + } + } else { + let modulus = decode_base64(modulus).expect("Spotnet's keys are base64"); + verdict.verified = rsa_sha1(signed.as_bytes(), &header_sig, &modulus); + } + } + // a `From` with the spotter's key and signature: the message-id must be signed with that key too + if verdict.verified + && let Some(user_sig) = user_sig.filter(|s| !s.is_empty()) + && !user_modulus.is_empty() + { + let sig = decode_base64(&user_sig).unwrap_or_default(); + verdict.verified = rsa_sha1(message_id.as_bytes(), &sig, &user_modulus); + if verdict.verified { + verdict.spotter_id = spotter_id(&user_key); + } + } + if !verdict.verified { + return no; + } + verdict +} + +/// Whether the SHA-1 of `message_id` (with its brackets) starts with four zero hex digits. +fn hashcash(message_id: &str) -> bool { + let digest = Sha1::digest(message_id.as_bytes()); + digest[0] == 0 && digest[1] == 0 +} + +/// The DER prefix of a PKCS #1 v1.5 SHA-1 `DigestInfo`. +const SHA1_DIGEST_INFO: [u8; 15] = + [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]; + +/// Whether `sig` is an RSA PKCS #1 v1.5 SHA-1 signature of `message` under the key with `modulus` (big-endian) +/// and exponent 65537. Spotnet's own keys are 384 bits, below what crypto libraries take, hence this by hand. +fn rsa_sha1(message: &[u8], sig: &[u8], modulus: &[u8]) -> bool { + let n = BigUint::from_bytes_be(modulus); + let k = n.bits().div_ceil(8) as usize; + // the 0x00 0x01, at least 8 0xff, the 0x00, the DigestInfo and the hash + if k < 3 + 8 + SHA1_DIGEST_INFO.len() + 20 || sig.is_empty() || sig.len() > k { + return false; + } + let s = BigUint::from_bytes_be(sig); + if s >= n { + return false; + } + let m = s.modpow(&BigUint::from(65_537u32), &n).to_bytes_be(); + let mut expected = vec![0xff; k]; + expected[0] = 0; + expected[1] = 1; + let tail = k - SHA1_DIGEST_INFO.len() - 20; + expected[tail - 1] = 0; + expected[tail..tail + SHA1_DIGEST_INFO.len()].copy_from_slice(&SHA1_DIGEST_INFO); + expected[k - 20..].copy_from_slice(&Sha1::digest(message)); + // `to_bytes_be` drops the leading zero bytes + m.len() <= k && expected[..k - m.len()].iter().all(|b| *b == 0) && expected[k - m.len()..] == m[..] +} + +#[cfg(test)] +mod tests { + use super::*; + + // overview lines from free.pt, October 2026 + const SPOT_ID: &str = ""; + const SPOT_TITLE: &str = "Hitster.S01E01.DUTCH.1080p.WEB.h264-TRIPEL"; + const SPOT_FROM: &str = "Wasbeertje "; + const MOD_ID: &str = "iWNrGQFeatMqnrcagoOav@spot.net"; + const MOD_TITLE: &str = + "DISPOSE vhcUXQS5B5HaOrnqfQX9J1l5FoVEreXH@spot.net - DC200726TL&CM (Zie image previewlink ivm NTD)"; + const MOD_FROM: &str = + "Afzender <10@12a01.1.10.1792834218.N5I.mod.vLCJUTdtVmLJtnj7fW5fpdlHfnAUuqeCGIzJr4AAVImZ9QICSsiJnehDrC7-pogB5>"; + const OWN_ID: &str = "x9FBYiqqYRYTGHcagIqb8.0.J6j5rpg31fwhGPcag.Ln42@spot.net"; + const OWN_TITLE: &str = + "DISPOSE x9FBYiqqYRYTGHcagIqb8@spot.net - Rescued.2026.1080p.AMZN.WEB-DL.H.264-GP-M-NLsubs-Retail-Multi"; + const OWN_FROM: &str = "GPNZBPosterGroep <4CGr2alVHshWG91Ajiozvi3D5D1MPD8Iwh5veSiUvGdrhFl5LBcyN5jV6GwHXqZB.pXjyxG1fqwyJa5G-sjJlChIwBKawpo0ooSTKvOHKZuwslnqnM27W1xO9CnX2irBvb@12a01.999.10.1792828292.1.NL.izwJAvjPDylBpOFDpL9dN5cp-sxozQ73-sBW-sER-pKECT4rDFo-pNPWI2IIp2c3cOelu>"; + + #[test] + fn a_self_signed_spot() { + let v = verify(SPOT_TITLE, SPOT_FROM, SPOT_ID); + assert!(v.verified && !v.personal); + assert_eq!(v.spotter_id, spotter_id("r2ceRUXK82cxSlhCLnbGXUVIA6-srpbJJqYqtJfXLdubdAMMD6T0G-pcPdZe619uuF")); + assert!(v.spotter_id.is_some()); + // the message-id is what the hashcash and the spotter's signature hold + assert!(!verify(SPOT_TITLE, SPOT_FROM, MOD_ID).verified); + // a header signature that doesn't hold costs the spotter id, as in Spotweb, not the spot + let other = verify("Hitster.S01E02", SPOT_FROM, SPOT_ID); + assert!(other.verified); + // someone else's key with this spotter's message-id signature + let forged = SPOT_FROM.replacen("r2ceRUXK", "r2ceRUXL", 1); + assert!(!verify(SPOT_TITLE, &forged, SPOT_ID).verified); + } + + #[test] + fn a_moderators_command() { + let v = verify(MOD_TITLE, MOD_FROM, MOD_ID); + assert_eq!(v, Verdict { verified: true, spotter_id: None, personal: false }); + // the signed title names the spot: another spot's id breaks it + let other = MOD_TITLE.replace("vhcUXQS5", "vhcUXQS6"); + assert_eq!(verify(&other, MOD_FROM, MOD_ID), Verdict::default()); + // and so does another nickname + let renamed = MOD_FROM.replace("Afzender", "Afzendr"); + assert!(!verify(MOD_TITLE, &renamed, MOD_ID).verified); + // a key Spotweb doesn't know + let key5 = MOD_FROM.replace("@12a01", "@15a01"); + assert!(!verify(MOD_TITLE, &key5, MOD_ID).verified); + } + + #[test] + fn a_spotters_own_dispose() { + let v = verify(OWN_TITLE, OWN_FROM, OWN_ID); + assert!(v.verified && v.personal); + assert_eq!(v.spotter_id, spotter_id("4CGr2alVHshWG91Ajiozvi3D5D1MPD8Iwh5veSiUvGdrhFl5LBcyN5jV6GwHXqZB")); + assert!(v.spotter_id.is_some()); + } + + #[test] + fn unsigned_or_not_a_spot() { + assert_eq!(verify("t", "x ", SPOT_ID), Verdict::default()); + assert_eq!(verify("t", "someone ", SPOT_ID), Verdict::default()); + assert_eq!(verify("", SPOT_FROM, SPOT_ID), Verdict::default()); + } + + #[test] + fn rsa_rejects_garbage() { + let modulus = decode_base64(SPOTNET_KEYS[0].1).unwrap(); + assert!(!rsa_sha1(b"x", &[], &modulus)); + assert!(!rsa_sha1(b"x", &[0xff; 49], &modulus)); + assert!(!rsa_sha1(b"x", &[1; 48], &modulus)); + assert!(!rsa_sha1(b"x", &[1; 8], &[0xff; 8])); + } +} From e638a1b9263f8fedfa9b62f0a141252888385e35 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:42:29 -0600 Subject: [PATCH 2/2] spots: review fixes for signature checks Build the signed text as bytes, so a multibyte character before the '<' can't panic the spot task; reject an empty nickname and a user key that won't decode, as Spotweb does; take only signatures exactly as long as the key; note which verdicts rest on decoded text; and say whether the spotter's key signed the message-id itself. Co-Authored-By: Claude Opus 5.5 --- src/spotnet/sign.rs | 55 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/src/spotnet/sign.rs b/src/spotnet/sign.rs index 8c76ae80..1895761d 100644 --- a/src/spotnet/sign.rs +++ b/src/spotnet/sign.rs @@ -37,10 +37,18 @@ pub struct Verdict { /// a key-2 command signed by a spotter's own key rather than Spotnet's moderator key: it may only remove a spot /// of that same spotter pub personal: bool, + /// the spotter's key signed the message-id itself. A spotter id from the header signature alone can be + /// replayed: that signature covers the title, header and nickname, not the message-id + pub message_id_signed: bool, } /// Checks the signatures of the spot (or moderator's command) whose overview gives `subject`, `from` and /// `message_id` (with or without its brackets). `title` is the title `header::parse` read from `subject`. +/// +/// The header signature is over text Atlas has already decoded (`from_utf8_lossy`, and on the overview +/// `undo_mojibake`), and RFC 2047 subjects aren't decoded first as Spotweb does: a non-ASCII title or nickname may +/// not rebuild the bytes that were signed. That decides the verdict only for keys 2 to 4 (a key-7 spot needs its +/// hashcash and message-id signature), and only the spotter id for a key-7 `From` without a user signature. pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { let no = Verdict::default(); let message_id = format!("<{}>", message_id.trim().trim_matches(['<', '>'])); @@ -57,16 +65,21 @@ pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { if header_sig.is_empty() || title.is_empty() { return no; } - // Spotweb drops the one character before the `<` (the space) and nothing else - let poster = &from[..open.saturating_sub(1)]; - let signed = format!("{title}{}{poster}", &header[..header.len() - header_sig.len() - 1]); + // Spotweb drops the one byte before the `<` (the space) and nothing else, and wants a nickname left + let poster = &from.as_bytes()[..open.saturating_sub(1)]; + if poster.is_empty() { + return no; + } + let mut signed = Vec::from(title.as_bytes()); + signed.extend_from_slice(header[..header.len() - header_sig.len() - 1].as_bytes()); + signed.extend_from_slice(poster); let Some(header_sig) = decode_base64(&unprepare_base64(header_sig)) else { return no }; let (user_key, user_sig) = match local.split_once('.') { Some((k, s)) => (unprepare_base64(k), Some(unprepare_base64(s))), None => (unprepare_base64(local), None), }; let user_modulus = decode_base64(&user_key).unwrap_or_default(); - let by_user = || !user_modulus.is_empty() && rsa_sha1(signed.as_bytes(), &header_sig, &user_modulus); + let by_user = || !user_modulus.is_empty() && rsa_sha1(&signed, &header_sig, &user_modulus); let mut verdict = Verdict::default(); if key_id == SELF_SIGNED_KEY { @@ -84,18 +97,20 @@ pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { } } else { let modulus = decode_base64(modulus).expect("Spotnet's keys are base64"); - verdict.verified = rsa_sha1(signed.as_bytes(), &header_sig, &modulus); + verdict.verified = rsa_sha1(&signed, &header_sig, &modulus); } } - // a `From` with the spotter's key and signature: the message-id must be signed with that key too + // a `From` with the spotter's key and signature: the message-id must be signed with that key too (a key that + // won't decode signs nothing) if verdict.verified && let Some(user_sig) = user_sig.filter(|s| !s.is_empty()) - && !user_modulus.is_empty() + && !user_key.is_empty() { let sig = decode_base64(&user_sig).unwrap_or_default(); - verdict.verified = rsa_sha1(message_id.as_bytes(), &sig, &user_modulus); + verdict.verified = !user_modulus.is_empty() && rsa_sha1(message_id.as_bytes(), &sig, &user_modulus); if verdict.verified { verdict.spotter_id = spotter_id(&user_key); + verdict.message_id_signed = true; } } if !verdict.verified { @@ -120,7 +135,8 @@ fn rsa_sha1(message: &[u8], sig: &[u8], modulus: &[u8]) -> bool { let n = BigUint::from_bytes_be(modulus); let k = n.bits().div_ceil(8) as usize; // the 0x00 0x01, at least 8 0xff, the 0x00, the DigestInfo and the hash - if k < 3 + 8 + SHA1_DIGEST_INFO.len() + 20 || sig.is_empty() || sig.len() > k { + // and, as OpenSSL wants, a signature exactly as long as the key + if k < 3 + 8 + SHA1_DIGEST_INFO.len() + 20 || sig.len() != k { return false; } let s = BigUint::from_bytes_be(sig); @@ -160,7 +176,7 @@ mod tests { #[test] fn a_self_signed_spot() { let v = verify(SPOT_TITLE, SPOT_FROM, SPOT_ID); - assert!(v.verified && !v.personal); + assert!(v.verified && !v.personal && v.message_id_signed); assert_eq!(v.spotter_id, spotter_id("r2ceRUXK82cxSlhCLnbGXUVIA6-srpbJJqYqtJfXLdubdAMMD6T0G-pcPdZe619uuF")); assert!(v.spotter_id.is_some()); // the message-id is what the hashcash and the spotter's signature hold @@ -176,7 +192,7 @@ mod tests { #[test] fn a_moderators_command() { let v = verify(MOD_TITLE, MOD_FROM, MOD_ID); - assert_eq!(v, Verdict { verified: true, spotter_id: None, personal: false }); + assert_eq!(v, Verdict { verified: true, ..Verdict::default() }); // the signed title names the spot: another spot's id breaks it let other = MOD_TITLE.replace("vhcUXQS5", "vhcUXQS6"); assert_eq!(verify(&other, MOD_FROM, MOD_ID), Verdict::default()); @@ -191,11 +207,25 @@ mod tests { #[test] fn a_spotters_own_dispose() { let v = verify(OWN_TITLE, OWN_FROM, OWN_ID); - assert!(v.verified && v.personal); + assert!(v.verified && v.personal && v.message_id_signed); assert_eq!(v.spotter_id, spotter_id("4CGr2alVHshWG91Ajiozvi3D5D1MPD8Iwh5veSiUvGdrhFl5LBcyN5jV6GwHXqZB")); assert!(v.spotter_id.is_some()); } + #[test] + fn odd_nicknames() { + // a multibyte character right before the `<`: the byte before it goes, as in Spotweb, and nothing panics + let tight = SPOT_FROM.replacen("Wasbeertje <", "NĂ©<", 1); + assert!(verify(SPOT_TITLE, &tight, SPOT_ID).verified); + // no nickname left once the byte before the `<` goes + let bare = SPOT_FROM.replacen("Wasbeertje <", "x<", 1); + assert_eq!(verify(SPOT_TITLE, &bare, SPOT_ID), Verdict::default()); + // a user key that won't decode can't have signed the message-id + let garbage = + SPOT_FROM.replacen("r2ceRUXK82cxSlhCLnbGXUVIA6-srpbJJqYqtJfXLdubdAMMD6T0G-pcPdZe619uuF", "!!!", 1); + assert_eq!(verify(SPOT_TITLE, &garbage, SPOT_ID), Verdict::default()); + } + #[test] fn unsigned_or_not_a_spot() { assert_eq!(verify("t", "x ", SPOT_ID), Verdict::default()); @@ -209,6 +239,7 @@ mod tests { assert!(!rsa_sha1(b"x", &[], &modulus)); assert!(!rsa_sha1(b"x", &[0xff; 49], &modulus)); assert!(!rsa_sha1(b"x", &[1; 48], &modulus)); + assert!(!rsa_sha1(b"x", &[1; 47], &modulus)); assert!(!rsa_sha1(b"x", &[1; 8], &[0xff; 8])); } }