Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce right types for spec-reserved keys #39

Merged
merged 21 commits into from
Aug 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 36 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,15 +473,7 @@ impl<K: EnrKey> Enr<K> {
value: Bytes,
enr_key: &K,
) -> Result<Option<Bytes>, EnrError> {
// currently only support "v4" identity schemes
if key.as_ref() == b"id" && &*value != b"v4" {
return Err(EnrError::UnsupportedIdentityScheme);
}

// Prevent inserting invalid RLP integers into keys with getters
if is_keyof_u16(key.as_ref()) {
rlp::decode::<u16>(&value).map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
}
check_spec_reserved_keys(key.as_ref(), &value)?;

let previous_value = self.content.insert(key.as_ref().to_vec(), value);
// add the new public key
Expand Down Expand Up @@ -1040,6 +1032,41 @@ const fn is_keyof_u16(key: &[u8]) -> bool {
matches!(key, b"tcp" | b"tcp6" | b"udp" | b"udp6")
}

fn check_spec_reserved_keys(key: &[u8], value: &[u8]) -> Result<(), EnrError> {
match key {
b"tcp" | b"tcp6" | b"udp" | b"udp6" => {
rlp::decode::<u16>(value).map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
}
b"id" => {
let id_bytes = rlp::decode::<Vec<u8>>(value)
.map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
if id_bytes != b"v4" {
return Err(EnrError::UnsupportedIdentityScheme);
}
}
b"ip" => {
let ip4_bytes = rlp::decode::<Vec<u8>>(value)
.map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
if ip4_bytes.len() != 4 {
return Err(EnrError::InvalidRlpData("Invalid Ipv4 size".to_string()));
}
}
b"ip6" => {
let ip6_bytes = rlp::decode::<Vec<u8>>(value)
.map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
if ip6_bytes.len() != 16 {
return Err(EnrError::InvalidRlpData("Invalid Ipv6 size".to_string()));
}
}
b"secp256k1" => {
rlp::decode::<Enr<k256::ecdsa::SigningKey>>(value)
.map_err(|err| EnrError::InvalidRlpData(err.to_string()))?;
}
_ => return Ok(()),
};
Ok(())
}

#[cfg(test)]
#[cfg(feature = "k256")]
mod tests {
Expand Down
Loading