use std::fmt;
#[cfg(feature = "serde-config")]
use serde::{Deserialize, Serialize};
use crate::error::*;
use crate::rr::dnssec::Nsec3HashAlgorithm;
use crate::rr::type_bit_map::*;
use crate::rr::RecordType;
use crate::serialize::binary::*;
#[cfg_attr(feature = "serde-config", derive(Deserialize, 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>,
type_bit_maps: Vec<RecordType>,
}
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: Vec<RecordType>,
) -> Self {
Self {
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
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 type_bit_maps(&self) -> &[RecordType] {
&self.type_bit_maps
}
pub fn flags(&self) -> u8 {
let mut flags: u8 = 0;
if self.opt_out {
flags |= 0b0000_0001
};
flags
}
}
pub fn read(decoder: &mut BinDecoder<'_>, rdata_length: Restrict<u16>) -> ProtoResult<NSEC3> {
let start_idx = decoder.index();
let hash_algorithm =
Nsec3HashAlgorithm::from_u8(decoder.read_u8()?.unverified())?;
let flags: u8 = decoder
.read_u8()?
.verify_unwrap(|flags| flags & 0b1111_1110 == 0)
.map_err(|flags| ProtoError::from(ProtoErrorKind::UnrecognizedNsec3Flags(flags)))?;
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 = rdata_length
.map(|u| u as usize)
.checked_sub(decoder.index() - start_idx)
.map_err(|_| "invalid rdata for salt_len_max")?;
let salt_len = salt_len
.verify_unwrap(|salt_len| {
*salt_len <= salt_len_max.unverified()
})
.map_err(|_| ProtoError::from("salt_len exceeds buffer length"))?;
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 = rdata_length
.map(|u| u as usize)
.checked_sub(decoder.index() - start_idx)
.map_err(|_| "invalid rdata for hash_len_max")?;
let hash_len = hash_len
.verify_unwrap(|hash_len| {
*hash_len <= hash_len_max.unverified()
})
.map_err(|_| ProtoError::from("hash_len exceeds buffer length"))?;
let next_hashed_owner_name: Vec<u8> =
decoder.read_vec(hash_len)?.unverified();
let bit_map_len = rdata_length
.map(|u| u as usize)
.checked_sub(decoder.index() - start_idx)
.map_err(|_| "invalid rdata length in NSEC3")?;
let record_types = decode_type_bit_maps(decoder, bit_map_len)?;
Ok(NSEC3::new(
hash_algorithm,
opt_out,
iterations,
salt,
next_hashed_owner_name,
record_types,
))
}
pub fn emit(encoder: &mut BinEncoder<'_>, rdata: &NSEC3) -> ProtoResult<()> {
encoder.emit(rdata.hash_algorithm().into())?;
encoder.emit(rdata.flags())?;
encoder.emit_u16(rdata.iterations())?;
encoder.emit(rdata.salt().len() as u8)?;
encoder.emit_vec(rdata.salt())?;
encoder.emit(rdata.next_hashed_owner_name().len() as u8)?;
encoder.emit_vec(rdata.next_hashed_owner_name())?;
encode_type_bit_maps(encoder, rdata.type_bit_maps())?;
Ok(())
}
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_NOPAD.encode(&self.next_hashed_owner_name)
)?;
for ty in &self.type_bit_maps {
write!(f, " {}", ty)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use super::*;
#[test]
fn test() {
use crate::rr::dnssec::rdata::RecordType;
let rdata = NSEC3::new(
Nsec3HashAlgorithm::SHA1,
true,
2,
vec![1, 2, 3, 4, 5],
vec![6, 7, 8, 9, 0],
vec![
RecordType::A,
RecordType::AAAA,
RecordType::DS,
RecordType::RRSIG,
],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).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 = read(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
#[test]
fn test_dups() {
use crate::rr::dnssec::rdata::RecordType;
let rdata_with_dups = NSEC3::new(
Nsec3HashAlgorithm::SHA1,
true,
2,
vec![1, 2, 3, 4, 5],
vec![6, 7, 8, 9, 0],
vec![
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],
vec![
RecordType::A,
RecordType::AAAA,
RecordType::DS,
RecordType::RRSIG,
],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata_with_dups).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 = read(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata_wo, read_rdata);
}
}