Merge PR 'Refuse to sign messages that collide with gossip serializations' (#5677)
What changed, and why it matters
This change fixes a security issue where a signed text message could be crafted so that its prefixed form looks exactly like a Lightning 'node_announcement' gossip message. Because both use the same double-SHA256 hash and the same signing key, an attacker could take a legitimate node's signed message and replay it as a forged gossip announcement, potentially impersonating or misrepresenting that node on the network. The patch makes the signing function refuse to sign any message whose prefixed bytes form a valid node_announcement serialization, and updates the API to return a Result so callers can handle the refusal.
Upgrade to a release containing this commit. Review any custom `NodeSigner::sign_message` implementations to ensure they also refuse to sign prefixed messages that serialize as `node_announcement` (or delegate to the updated `message_signing::sign`). Audit existing signed-message APIs and logs for any reliance on the previous infallible `String` return type.
Security signals we found
Signature replay / message confusion between signed messages and gossip announcements
Forged `node_announcement` signatures via chosen-prefix message construction
New validation rejects prefixed messages that deserialize as `UnsignedNodeAnnouncement`
API breaking change: `sign` now returns `Result<String, ()>` instead of `String`
Changelog explicitly describes the security-relevant behavior change
Evidence from the diff
The sign function in lightning::util::message_signing previously returned String and signed any input prefixed with Lightning Signed Message:. Lightning gossip signatures (e.g., for node_announcement) also sign a double-SHA256 digest of the serialized message, and node_announcement does not include a chain-hash field that would constrain replay to a specific chain. This allowed a chosen message to be prefixed so that the combined bytes serialize as a valid UnsignedNodeAnnouncement; the resulting ECDSA recoverable signature would then verify as a gossip signature for that announcement. The patch adds is_gossip_serialization, which round-trips the prefixed bytes through UnsignedNodeAnnouncement deserialization/serialization, and makes sign return Err(()) when the prefixed bytes are a valid node_announcement. All callers and trait implementations are updated to propagate the new Result.
Changed components
lightning::util::message_signing::signlightning::sign::NodeSigner::sign_messagelightning::sign::KeysManagertest and fuzz harness NodeSigner implementationsLightning gossip message signature verificationInspect captured patch +74 / −14
### fuzz/src/chanmon_consistency.rs
@@ -835,7 +835,7 @@ impl NodeSigner for KeyProvider {
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
- Ok(lightning::util::message_signing::sign(msg, &self.node_secret))
+ lightning::util::message_signing::sign(msg, &self.node_secret)
}
}
### fuzz/src/full_stack.rs
@@ -444,7 +444,7 @@ impl NodeSigner for KeyProvider {
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
- Ok(lightning::util::message_signing::sign(msg, &self.node_secret))
+ lightning::util::message_signing::sign(msg, &self.node_secret)
}
fn get_peer_storage_key(&self) -> PeerStorageKey {
### fuzz/src/onion_message.rs
@@ -282,7 +282,7 @@ impl NodeSigner for KeyProvider {
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
- Ok(lightning::util::message_signing::sign(msg, &self.node_secret))
+ lightning::util::message_signing::sign(msg, &self.node_secret)
}
fn get_peer_storage_key(&self) -> PeerStorageKey {
### lightning/src/ln/blinded_payment_tests.rs
@@ -2034,7 +2034,7 @@ fn route_blinding_spec_test_vector() {
) -> Result<schnorr::Signature, ()> { unreachable!() }
fn sign_gossip_message(&self, _msg: UnsignedGossipMessage) -> Result<Signature, ()> { unreachable!() }
- fn sign_message(&self, msg: &[u8]) -> Result<String, ()> { Ok(crate::util::message_signing::sign(msg, &self.node_secret)) }
+ fn sign_message(&self, msg: &[u8]) -> Result<String, ()> { crate::util::message_signing::sign(msg, &self.node_secret) }
}
let logger = test_utils::TestLogger::with_id("".to_owned());
@@ -2348,7 +2348,7 @@ fn test_trampoline_inbound_payment_decoding() {
&self, _invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()> { unreachable!() }
fn sign_gossip_message(&self, _msg: UnsignedGossipMessage) -> Result<Signature, ()> { unreachable!() }
- fn sign_message(&self, msg: &[u8]) -> Result<String, ()> { Ok(crate::util::message_signing::sign(msg, &self.node_secret)) }
+ fn sign_message(&self, msg: &[u8]) -> Result<String, ()> { crate::util::message_signing::sign(msg, &self.node_secret) }
}
let logger = test_utils::TestLogger::with_id("".to_owned());
### lightning/src/sign/mod.rs
@@ -1018,7 +1018,8 @@ pub trait NodeSigner {
///
/// A receiver knowing the node's id and the message can be sure that the signature was generated by the caller.
/// An `Err` can be returned to signal that the signer is unavailable / cannot produce a valid
- /// signature.
+ /// signature, including if the prefixed message would itself be a valid `node_announcement`
+ /// serialization, as its signature could otherwise be replayed as a gossip message signature.
fn sign_message(&self, msg: &[u8]) -> Result<String, ()>;
}
@@ -2467,7 +2468,7 @@ impl<L: Logger> NodeSigner for KeysManager<L> {
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
- Ok(crate::util::message_signing::sign(msg, &self.node_secret))
+ crate::util::message_signing::sign(msg, &self.node_secret)
}
}
### lightning/src/util/message_signing.rs
@@ -20,15 +20,36 @@
//! <https://lightning.readthedocs.io/lightning-signmessage.7.html>
//! <https://api.lightning.community/#signmessage>
+use crate::ln::msgs::UnsignedNodeAnnouncement;
#[allow(unused)]
use crate::prelude::*;
use crate::util::base32;
+use crate::util::ser::{LengthReadable, Writeable};
use bitcoin::hashes::{sha256d, Hash};
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey};
static LN_MESSAGE_PREFIX: &[u8] = b"Lightning Signed Message:";
+/// Returns whether the given bytes are exactly the serialization of a `node_announcement`, i.e.
+/// whether a signature over their sha256d hash would verify as a `node_announcement` signature.
+///
+/// Gossip message signatures cover the same sha256d hash construction used here, so refusing to
+/// sign such bytes prevents a signed message from being replayed as a (forged) `node_announcement`.
+///
+/// Other gossip message types are not checked: their `chain_hash` is validated against the genesis
+/// hash before their signature is processed, and no real chain's genesis hash starts with "Li",
+/// whereas `node_announcement` has no such validation.
+fn is_gossip_serialization(bytes: &[u8]) -> bool {
+ fn round_trips<T: LengthReadable + Writeable>(bytes: &[u8]) -> bool {
+ match T::read_from_fixed_length_buffer(&mut &bytes[..]) {
+ Ok(msg) => msg.encode() == bytes,
+ Err(_) => false,
+ }
+ }
+ round_trips::<UnsignedNodeAnnouncement>(bytes)
+}
+
fn sigrec_encode(sig_rec: RecoverableSignature) -> Vec<u8> {
let (rid, rsig) = sig_rec.serialize_compact();
let prefix = rid.to_i32() as u8 + 31;
@@ -54,12 +75,20 @@ fn sigrec_decode(sig_rec: Vec<u8>) -> Result<RecoverableSignature, Error> {
/// Creates a digital signature of a message given a SecretKey, like the node's secret.
/// A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller.
/// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted.
-pub fn sign(msg: &[u8], sk: &SecretKey) -> String {
+///
+/// Returns an `Err` if the prefixed message is a valid `node_announcement` serialization, as the
+/// signature could otherwise be replayed as a (forged) `node_announcement` signature.
+pub fn sign(msg: &[u8], sk: &SecretKey) -> Result<String, ()> {
+ let prefixed = [LN_MESSAGE_PREFIX, msg].concat();
+ if is_gossip_serialization(&prefixed) {
+ return Err(());
+ }
+
let secp_ctx = Secp256k1::signing_only();
- let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
+ let msg_hash = sha256d::Hash::hash(&prefixed);
let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_digest(msg_hash.to_byte_array()), sk);
- base32::Alphabet::ZBase32.encode(&sigrec_encode(sig))
+ Ok(base32::Alphabet::ZBase32.encode(&sigrec_encode(sig)))
}
/// Recovers the PublicKey of the signer of the message given the message and the signature.
@@ -89,7 +118,9 @@ pub fn verify(msg: &[u8], sig: &str, pk: &PublicKey) -> bool {
#[cfg(test)]
mod test {
- use crate::util::message_signing::{recover_pk, sign, verify};
+ use crate::util::message_signing::{
+ is_gossip_serialization, recover_pk, sign, verify, LN_MESSAGE_PREFIX,
+ };
use bitcoin::secp256k1::constants::ONE;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use core::str::FromStr;
@@ -98,7 +129,7 @@ mod test {
fn test_sign() {
let message = "test message";
let one_key = SecretKey::from_slice(&ONE).unwrap();
- let zbase32_sig = sign(message.as_bytes(), &one_key);
+ let zbase32_sig = sign(message.as_bytes(), &one_key).unwrap();
assert_eq!(zbase32_sig, "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
}
@@ -117,12 +148,34 @@ mod test {
fn test_verify() {
let message = "another message";
let one_key = SecretKey::from_slice(&ONE).unwrap();
- let sig = sign(message.as_bytes(), &one_key);
+ let sig = sign(message.as_bytes(), &one_key).unwrap();
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &one_key);
assert!(verify(message.as_bytes(), &sig, &pk))
}
+ #[test]
+ fn test_sign_refuses_gossip_serialization() {
+ let one_key = SecretKey::from_slice(&ONE).unwrap();
+ let node_id = PublicKey::from_secret_key(&Secp256k1::signing_only(), &one_key).serialize();
+
+ // The prefix starts with "Li", which a `node_announcement` parses as a feature vector
+ // length of 0x4c69 bytes. The remaining 23 prefix bytes are thus the start of that feature
+ // vector, so the message has to supply the remaining 19,538 feature bytes followed by a
+ // valid announcement tail for the prefixed message to be a `node_announcement`
+ // serialization. Signing it would allow the signature to be replayed as a gossip message
+ // signature.
+ let mut msg = vec![0u8; 19_538]; // rest of the 0x4c69-byte feature vector
+ msg.extend_from_slice(&0u32.to_be_bytes()); // timestamp
+ msg.extend_from_slice(&node_id);
+ msg.extend_from_slice(&[0; 3]); // rgb
+ msg.extend_from_slice(&[0; 32]); // alias
+ msg.extend_from_slice(&0u16.to_be_bytes()); // no addresses
+
+ assert!(is_gossip_serialization(&[LN_MESSAGE_PREFIX, &msg[..]].concat()));
+ assert_eq!(sign(&msg, &one_key), Err(()));
+ }
+
#[test]
fn test_verify_ground_truth_ish() {
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
### lightning/src/util/test_utils.rs
@@ -1982,7 +1982,7 @@ impl NodeSigner for TestNodeSigner {
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
- Ok(crate::util::message_signing::sign(msg, &self.node_secret))
+ crate::util::message_signing::sign(msg, &self.node_secret)
}
}
### pending_changelog/sign-message-gossip-collision.txt
@@ -0,0 +1,6 @@
+# API Updates
+
+ * `lightning::util::message_signing::sign` now returns a `Result`, and refuses to sign messages
+ which, once prefixed with "Lightning Signed Message:", serialize as a `node_announcement`. A
+ signature over such a message could otherwise be replayed as a (forged) `node_announcement`
+ signature (#386).Why this scored 74/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.