use alloc::{fmt, string::ToString, vec::Vec};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
dnssec::Nsec3HashAlgorithm,
error::ProtoResult,
rr::{RData, RecordData, RecordDataDecodable, RecordType, RecordTypeSet, domain::Label},
serialize::binary::*,
};
use super::DNSSECRData;
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct NSEC3 {
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
next_hashed_owner_name: Vec<u8>,
#[cfg_attr(feature = "serde", serde(skip_serializing))]
next_hashed_owner_name_base32: Option<Label>,
type_bit_maps: RecordTypeSet,
}
impl NSEC3 {
pub fn new(
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
next_hashed_owner_name: Vec<u8>,
type_bit_maps: impl IntoIterator<Item = RecordType>,
) -> Self {
Self::with_record_type_set(
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
RecordTypeSet::new(type_bit_maps),
)
}
fn with_record_type_set(
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
next_hashed_owner_name: Vec<u8>,
type_bit_maps: RecordTypeSet,
) -> Self {
let next_hashed_owner_name_base32 =
Label::from_ascii(&data_encoding::BASE32_DNSSEC.encode(&next_hashed_owner_name)).ok();
Self {
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
next_hashed_owner_name_base32,
type_bit_maps,
}
}
pub fn hash_algorithm(&self) -> Nsec3HashAlgorithm {
self.hash_algorithm
}
pub fn opt_out(&self) -> bool {
self.opt_out
}
pub fn iterations(&self) -> u16 {
self.iterations
}
pub fn salt(&self) -> &[u8] {
&self.salt
}
pub fn next_hashed_owner_name(&self) -> &[u8] {
&self.next_hashed_owner_name
}
pub fn next_hashed_owner_name_base32(&self) -> Option<&Label> {
self.next_hashed_owner_name_base32.as_ref()
}
pub fn type_bit_maps(&self) -> impl Iterator<Item = RecordType> + '_ {
self.type_bit_maps.iter()
}
pub fn type_set(&self) -> &RecordTypeSet {
&self.type_bit_maps
}
pub fn flags(&self) -> u8 {
let mut flags: u8 = 0;
if self.opt_out {
flags |= 0b0000_0001
};
flags
}
}
impl BinEncodable for NSEC3 {
fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
encoder.emit(self.hash_algorithm().into())?;
encoder.emit(self.flags())?;
encoder.emit_u16(self.iterations())?;
encoder.emit(self.salt().len() as u8)?;
encoder.emit_vec(self.salt())?;
encoder.emit(self.next_hashed_owner_name().len() as u8)?;
encoder.emit_vec(self.next_hashed_owner_name())?;
self.type_bit_maps.emit(encoder)?;
Ok(())
}
}
impl<'r> RecordDataDecodable<'r> for NSEC3 {
fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> Result<Self, DecodeError> {
let start_idx = decoder.index();
let hash_algorithm = Nsec3HashAlgorithm::try_from(
decoder.read_u8()?.unverified(),
)?;
let flags: u8 = decoder
.read_u8()?
.verify_unwrap(|flags| flags & 0b1111_1110 == 0)
.map_err(DecodeError::UnrecognizedNsec3Flags)?;
let opt_out: bool = flags & 0b0000_0001 == 0b0000_0001;
let iterations: u16 = decoder.read_u16()?.unverified();
let salt_len = decoder.read_u8()?.map(|u| u as usize);
let salt_len_max = length
.map(|u| u as usize)
.checked_sub(decoder.index() - start_idx)
.map_err(|len| DecodeError::IncorrectRDataLengthRead {
read: decoder.index() - start_idx,
len,
})?;
let salt_len = salt_len
.verify_unwrap(|salt_len| {
*salt_len <= salt_len_max.unverified()
})
.map_err(|salt_len| DecodeError::IncorrectRDataLengthRead {
read: salt_len_max.unverified(),
len: salt_len,
})?;
let salt: Vec<u8> =
decoder.read_vec(salt_len)?.unverified();
let hash_len = decoder.read_u8()?.map(|u| u as usize);
let hash_len_max = length
.map(|u| u as usize)
.checked_sub(decoder.index() - start_idx)
.map_err(|len| DecodeError::IncorrectRDataLengthRead {
read: decoder.index() - start_idx,
len,
})?;
let hash_len = hash_len
.verify_unwrap(|hash_len| {
*hash_len <= hash_len_max.unverified()
})
.map_err(|hash_len| DecodeError::IncorrectRDataLengthRead {
read: hash_len_max.unverified(),
len: hash_len,
})?;
let next_hashed_owner_name: Vec<u8> =
decoder.read_vec(hash_len)?.unverified();
let offset = u16::try_from(decoder.index() - start_idx).map_err(|_| {
DecodeError::IncorrectRDataLengthRead {
read: decoder.index() - start_idx,
len: u16::MAX as usize,
}
})?;
let bit_map_len =
length
.checked_sub(offset)
.map_err(|len| DecodeError::IncorrectRDataLengthRead {
read: offset as usize,
len: len as usize,
})?;
let record_types = RecordTypeSet::read_data(decoder, bit_map_len)?;
Ok(Self::with_record_type_set(
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
record_types,
))
}
}
impl RecordData for NSEC3 {
fn try_borrow(data: &RData) -> Option<&Self> {
match data {
RData::DNSSEC(DNSSECRData::NSEC3(csync)) => Some(csync),
_ => None,
}
}
fn record_type(&self) -> RecordType {
RecordType::NSEC3
}
fn into_rdata(self) -> RData {
RData::DNSSEC(DNSSECRData::NSEC3(self))
}
}
impl fmt::Display for NSEC3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
let salt = if self.salt.is_empty() {
"-".to_string()
} else {
data_encoding::HEXUPPER_PERMISSIVE.encode(&self.salt)
};
write!(
f,
"{alg} {flags} {iterations} {salt} {owner}",
alg = u8::from(self.hash_algorithm),
flags = self.flags(),
iterations = self.iterations,
salt = salt,
owner = data_encoding::BASE32_DNSSEC.encode(&self.next_hashed_owner_name)
)?;
for ty in self.type_bit_maps.iter() {
write!(f, " {ty}")?;
}
Ok(())
}
}
#[cfg(feature = "serde")]
#[derive(Deserialize)]
#[serde(rename = "NSEC3")]
struct NSEC3Serde {
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
next_hashed_owner_name: Vec<u8>,
type_bit_maps: RecordTypeSet,
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for NSEC3 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let NSEC3Serde {
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
type_bit_maps,
} = NSEC3Serde::deserialize(deserializer)?;
Ok(Self::with_record_type_set(
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
type_bit_maps,
))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use std::println;
use super::*;
use crate::dnssec::rdata::RecordType;
#[test]
fn test() {
let rdata = NSEC3::new(
Nsec3HashAlgorithm::SHA1,
true,
2,
vec![1, 2, 3, 4, 5],
vec![6, 7, 8, 9, 0],
[
RecordType::A,
RecordType::AAAA,
RecordType::DS,
RecordType::RRSIG,
],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(rdata.emit(&mut encoder).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {bytes:?}");
let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
let restrict = Restrict::new(bytes.len() as u16);
let read_rdata = NSEC3::read_data(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
#[test]
fn test_dups() {
let rdata_with_dups = NSEC3::new(
Nsec3HashAlgorithm::SHA1,
true,
2,
vec![1, 2, 3, 4, 5],
vec![6, 7, 8, 9, 0],
[
RecordType::A,
RecordType::AAAA,
RecordType::DS,
RecordType::AAAA,
RecordType::RRSIG,
],
);
let rdata_wo = NSEC3::new(
Nsec3HashAlgorithm::SHA1,
true,
2,
vec![1, 2, 3, 4, 5],
vec![6, 7, 8, 9, 0],
[
RecordType::A,
RecordType::AAAA,
RecordType::DS,
RecordType::RRSIG,
],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(rdata_with_dups.emit(&mut encoder).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {bytes:?}");
let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
let restrict = Restrict::new(bytes.len() as u16);
let read_rdata = NSEC3::read_data(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata_wo, read_rdata);
}
}