159 行
4.8 KiB
Rust
159 行
4.8 KiB
Rust
use std::{fmt, net::SocketAddr, time::Duration};
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct NetworkTarget {
|
|
pub host: String,
|
|
pub port: u16,
|
|
pub timeout: Duration,
|
|
}
|
|
|
|
impl NetworkTarget {
|
|
pub fn validate(&self) -> Result<(), NetworkCheckError> {
|
|
let host = self.host.trim();
|
|
if host.is_empty() || host.len() > 253 {
|
|
return Err(NetworkCheckError::InvalidTarget);
|
|
}
|
|
if self.port == 0
|
|
|| host
|
|
.chars()
|
|
.any(|character| character.is_whitespace() || "/\\@,*?".contains(character))
|
|
|| host.contains("://")
|
|
{
|
|
return Err(NetworkCheckError::InvalidTarget);
|
|
}
|
|
if self.timeout.is_zero() || self.timeout > Duration::from_secs(10) {
|
|
return Err(NetworkCheckError::InvalidTimeout);
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct NetworkAttempt {
|
|
pub address: SocketAddr,
|
|
pub connected: bool,
|
|
pub error_kind: Option<String>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct NetworkCheckResult {
|
|
pub resolved_addresses: usize,
|
|
pub connected_address: Option<SocketAddr>,
|
|
pub attempts: Vec<NetworkAttempt>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum NetworkCheckError {
|
|
InvalidTarget,
|
|
InvalidTimeout,
|
|
ResolutionTimedOut,
|
|
ResolutionFailed(String),
|
|
NoAddresses,
|
|
}
|
|
|
|
impl fmt::Display for NetworkCheckError {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::InvalidTarget => formatter.write_str("the network target is invalid"),
|
|
Self::InvalidTimeout => formatter.write_str("the network timeout is invalid"),
|
|
Self::ResolutionTimedOut => formatter.write_str("network name resolution timed out"),
|
|
Self::ResolutionFailed(kind) => {
|
|
write!(formatter, "network name resolution failed: {kind}")
|
|
}
|
|
Self::NoAddresses => formatter.write_str("the network target resolved to no addresses"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for NetworkCheckError {}
|
|
|
|
pub async fn check_tcp_target(
|
|
target: &NetworkTarget,
|
|
) -> Result<NetworkCheckResult, NetworkCheckError> {
|
|
target.validate()?;
|
|
|
|
let resolution = tokio::time::timeout(
|
|
target.timeout,
|
|
tokio::net::lookup_host((target.host.as_str(), target.port)),
|
|
)
|
|
.await
|
|
.map_err(|_| NetworkCheckError::ResolutionTimedOut)?
|
|
.map_err(|error| NetworkCheckError::ResolutionFailed(error.kind().to_string()))?;
|
|
|
|
let addresses = resolution.take(3).collect::<Vec<_>>();
|
|
if addresses.is_empty() {
|
|
return Err(NetworkCheckError::NoAddresses);
|
|
}
|
|
|
|
let mut attempts = Vec::with_capacity(addresses.len());
|
|
let mut connected_address = None;
|
|
for address in addresses.iter().copied() {
|
|
match tokio::time::timeout(target.timeout, tokio::net::TcpStream::connect(address)).await {
|
|
Ok(Ok(stream)) => {
|
|
drop(stream);
|
|
connected_address = Some(address);
|
|
attempts.push(NetworkAttempt {
|
|
address,
|
|
connected: true,
|
|
error_kind: None,
|
|
});
|
|
break;
|
|
}
|
|
Ok(Err(error)) => attempts.push(NetworkAttempt {
|
|
address,
|
|
connected: false,
|
|
error_kind: Some(error.kind().to_string()),
|
|
}),
|
|
Err(_) => attempts.push(NetworkAttempt {
|
|
address,
|
|
connected: false,
|
|
error_kind: Some("timed-out".to_owned()),
|
|
}),
|
|
}
|
|
}
|
|
|
|
Ok(NetworkCheckResult {
|
|
resolved_addresses: addresses.len(),
|
|
connected_address,
|
|
attempts,
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[tokio::test]
|
|
async fn connects_only_to_the_requested_loopback_port() {
|
|
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
|
|
.await
|
|
.expect("bind loopback listener");
|
|
let port = listener.local_addr().expect("listener address").port();
|
|
let target = NetworkTarget {
|
|
host: "127.0.0.1".to_owned(),
|
|
port,
|
|
timeout: Duration::from_secs(1),
|
|
};
|
|
|
|
let result = check_tcp_target(&target).await.expect("check succeeds");
|
|
assert!(result.connected_address.is_some());
|
|
assert_eq!(result.attempts.len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_scanning_and_url_shaped_targets() {
|
|
for host in [
|
|
"https://example.test",
|
|
"10.0.0.*",
|
|
"host,other",
|
|
"user@host",
|
|
] {
|
|
let target = NetworkTarget {
|
|
host: host.to_owned(),
|
|
port: 443,
|
|
timeout: Duration::from_secs(1),
|
|
};
|
|
assert_eq!(target.validate(), Err(NetworkCheckError::InvalidTarget));
|
|
}
|
|
}
|
|
}
|