Improve network checks

This commit is contained in:
2024-01-08 21:29:31 +01:00
parent 672e866897
commit e86b29c03a
4 changed files with 96 additions and 33 deletions

View File

@ -1,5 +1,12 @@
use crate::utils::net_utils;
use std::net::{Ipv4Addr, Ipv6Addr};
#[derive(thiserror::Error, Debug)]
enum NatDefError {
#[error("Invalid nat definition: {0}")]
InvalidNatDef(&'static str),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum NatSource<IPv> {
@ -31,6 +38,36 @@ pub struct Nat<IPv> {
pub comment: Option<String>,
}
impl<IPv> Nat<IPv> {
pub fn check(&self) -> anyhow::Result<()> {
if let NatSource::Interface { name } = &self.host_addr {
if !net_utils::is_net_interface_name_valid(name) {
return Err(NatDefError::InvalidNatDef("Invalid nat interface name!").into());
}
}
if let NatHostPort::Range { start, end } = &self.host_port {
if *start == 0 {
return Err(NatDefError::InvalidNatDef("Invalid start range!").into());
}
if start > end {
return Err(NatDefError::InvalidNatDef("Invalid port range!").into());
}
if u16::MAX - (end - start) < self.guest_port {
return Err(NatDefError::InvalidNatDef("Guest port is too high!").into());
}
}
if self.guest_port == 0 {
return Err(NatDefError::InvalidNatDef("Invalid guest port!").into());
}
Ok(())
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
pub struct NetNat {
pub interface: String,