diff --git a/leaf/src/app/api/api_server.rs b/leaf/src/app/api/api_server.rs index 60f4124..48ec52a 100644 --- a/leaf/src/app/api/api_server.rs +++ b/leaf/src/app/api/api_server.rs @@ -49,6 +49,7 @@ mod models { pub send_completed: bool, pub recv_completed: bool, pub start_time: u32, + pub sniffed_domain: Option, } #[derive(Debug, Serialize, Deserialize)] @@ -166,6 +167,7 @@ mod handlers { send_completed: c.send_completed(), recv_completed: c.recv_completed(), start_time: c.start_time(), + sniffed_domain: c.sess.sniffed_domain.clone(), }); } Ok(Json(stats)) diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index 6f897d5..41ce58d 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -10,7 +10,11 @@ use tracing::{debug, info, warn, Instrument}; use crate::{ app::SyncDnsClient, - common::{self, sniff}, + common::{ + self, + dns_sniff::{DnsSniffer, SniffingDatagram}, + sniff, + }, option, proxy::*, session::*, @@ -147,6 +151,7 @@ pub struct Dispatcher { router: Arc>, dns_client: SyncDnsClient, stat_manager: SyncStatManager, + dns_sniffer: DnsSniffer, } impl Dispatcher { @@ -161,6 +166,7 @@ impl Dispatcher { router, dns_client, stat_manager, + dns_sniffer: DnsSniffer::new(), } } @@ -176,6 +182,13 @@ impl Dispatcher { where T: 'static + AsyncRead + AsyncWrite + Unpin + Send + Sync, { + if let Some(ip) = sess.destination.ip() { + if let Some(domain) = self.dns_sniffer.get(&ip).await { + debug!("found sniffed domain {} for {}", &domain, &ip); + sess.sniffed_domain = Some(domain); + } + } + debug!("dispatching {}:{}", &sess.network, &sess.destination); if let Some(domain) = sess.destination.domain() { @@ -373,6 +386,13 @@ impl Dispatcher { &self, mut sess: Session, ) -> io::Result> { + if let Some(ip) = sess.destination.ip() { + if let Some(domain) = self.dns_sniffer.get(&ip).await { + debug!("found sniffed domain {} for {}", &domain, &ip); + sess.sniffed_domain = Some(domain); + } + } + debug!("dispatching {}:{}", &sess.network, &sess.destination); if let Some(domain) = sess.destination.domain() { @@ -447,6 +467,10 @@ impl Dispatcher { .await .stat_outbound_datagram(d, sess.clone()); + if sess.destination.port() == 53 { + d = Box::new(SniffingDatagram::new(d, self.dns_sniffer.clone())); + } + Ok(d) } Err(e) => { diff --git a/leaf/src/common/dns_sniff.rs b/leaf/src/common/dns_sniff.rs new file mode 100644 index 0000000..b69a811 --- /dev/null +++ b/leaf/src/common/dns_sniff.rs @@ -0,0 +1,218 @@ +use std::io; +use std::net::IpAddr; +use std::num::NonZeroUsize; +use std::sync::Arc; + +use hickory_proto::op::{Message, MessageType}; +use hickory_proto::rr::RData; +use lru::LruCache; +use tokio::sync::RwLock; + +use crate::proxy::{OutboundDatagram, OutboundDatagramRecvHalf, OutboundDatagramSendHalf}; +use crate::session::SocksAddr; + +#[derive(Clone)] +pub struct DnsSniffer { + cache: Arc>>, +} + +impl DnsSniffer { + pub fn new() -> Self { + let cap = NonZeroUsize::new(2048).unwrap(); + DnsSniffer { + cache: Arc::new(RwLock::new(LruCache::new(cap))), + } + } + + pub async fn add(&self, ip: IpAddr, domain: String) { + self.cache.write().await.put(ip, domain); + } + + pub async fn get(&self, ip: &IpAddr) -> Option { + self.cache.read().await.peek(ip).cloned() + } +} + +pub struct SniffingDatagram { + recv: SniffingDatagramRecvHalf, + send: SniffingDatagramSendHalf, +} + +impl SniffingDatagram { + pub fn new(outbound: Box, sniffer: DnsSniffer) -> Self { + let (recv, send) = outbound.split(); + SniffingDatagram { + recv: SniffingDatagramRecvHalf { + inner: recv, + sniffer: sniffer.clone(), + }, + send: SniffingDatagramSendHalf { inner: send }, + } + } +} + +impl OutboundDatagram for SniffingDatagram { + fn split( + self: Box, + ) -> ( + Box, + Box, + ) { + (Box::new(self.recv), Box::new(self.send)) + } +} + +pub struct SniffingDatagramRecvHalf { + inner: Box, + sniffer: DnsSniffer, +} + +#[async_trait::async_trait] +impl OutboundDatagramRecvHalf for SniffingDatagramRecvHalf { + async fn recv_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, SocksAddr)> { + let (len, src_addr) = self.inner.recv_from(buf).await?; + + if let Ok(msg) = Message::from_vec(&buf[..len]) { + if msg.message_type() == MessageType::Response { + // Extract domain from the first query in the response + let domain = if let Some(query) = msg.queries().first() { + let mut name = query.name().to_string(); + if name.ends_with('.') { + name.pop(); + } + Some(name) + } else { + None + }; + + if let Some(domain) = domain { + for answer in msg.answers() { + if let Some(rdata) = answer.data() { + match rdata { + RData::A(ip) => { + self.sniffer.add(IpAddr::V4(ip.0), domain.clone()).await; + } + RData::AAAA(ip) => { + self.sniffer.add(IpAddr::V6(ip.0), domain.clone()).await; + } + _ => {} + } + } + } + } + } + } + + Ok((len, src_addr)) + } +} + +pub struct SniffingDatagramSendHalf { + inner: Box, +} + +#[async_trait::async_trait] +impl OutboundDatagramSendHalf for SniffingDatagramSendHalf { + async fn send_to(&mut self, buf: &[u8], dst_addr: &SocksAddr) -> io::Result { + self.inner.send_to(buf, dst_addr).await + } + + async fn close(&mut self) -> io::Result<()> { + self.inner.close().await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::proxy::{OutboundDatagram, OutboundDatagramRecvHalf, OutboundDatagramSendHalf}; + use crate::session::SocksAddr; + use hickory_proto::op::{Message, MessageType, Query}; + use hickory_proto::rr::{Name, RData, Record, RecordType}; + use std::io; + use std::net::{IpAddr, Ipv4Addr}; + use std::str::FromStr; + + struct MockOutboundDatagramRecvHalf { + data: Vec, + } + + #[async_trait::async_trait] + impl OutboundDatagramRecvHalf for MockOutboundDatagramRecvHalf { + async fn recv_from(&mut self, buf: &mut [u8]) -> io::Result<(usize, SocksAddr)> { + if self.data.is_empty() { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof")); + } + let len = std::cmp::min(buf.len(), self.data.len()); + buf[..len].copy_from_slice(&self.data[..len]); + self.data.clear(); // One-shot + Ok((len, SocksAddr::any_ipv4())) + } + } + + struct MockOutboundDatagramSendHalf; + + #[async_trait::async_trait] + impl OutboundDatagramSendHalf for MockOutboundDatagramSendHalf { + async fn send_to(&mut self, _buf: &[u8], _dst_addr: &SocksAddr) -> io::Result { + Ok(0) + } + async fn close(&mut self) -> io::Result<()> { + Ok(()) + } + } + + struct MockOutboundDatagram { + recv: MockOutboundDatagramRecvHalf, + send: MockOutboundDatagramSendHalf, + } + + impl OutboundDatagram for MockOutboundDatagram { + fn split( + self: Box, + ) -> ( + Box, + Box, + ) { + (Box::new(self.recv), Box::new(self.send)) + } + } + + #[tokio::test] + async fn test_dns_sniff() { + let sniffer = DnsSniffer::new(); + + // Construct a DNS response + let mut msg = Message::new(); + msg.set_message_type(MessageType::Response); + let name = Name::from_str("example.com.").unwrap(); + let query = Query::query(name.clone(), RecordType::A); + msg.add_query(query); + let ip = Ipv4Addr::new(1, 2, 3, 4); + let answer = Record::from_rdata(name, 3600, RData::A(hickory_proto::rr::rdata::A(ip))); + msg.add_answer(answer); + + let msg_bytes = msg.to_vec().unwrap(); + + // Create a mock outbound datagram + let mock_recv = MockOutboundDatagramRecvHalf { data: msg_bytes }; + let mock_send = MockOutboundDatagramSendHalf; + let mock_outbound = Box::new(MockOutboundDatagram { + recv: mock_recv, + send: mock_send, + }); + + // Create sniffing datagram + let sniffing_datagram = Box::new(SniffingDatagram::new(mock_outbound, sniffer.clone())); + let (mut recv, _send) = sniffing_datagram.split(); + + // Receive data (trigger sniffing) + let mut buf = vec![0u8; 1500]; + let (_len, _addr) = recv.recv_from(&mut buf).await.unwrap(); + + // Check if sniffed + let sniffed_ip = IpAddr::V4(ip); + let domain = sniffer.get(&sniffed_ip).await; + assert_eq!(domain, Some("example.com".to_string())); + } +} diff --git a/leaf/src/common/mod.rs b/leaf/src/common/mod.rs index 75878be..9184e63 100644 --- a/leaf/src/common/mod.rs +++ b/leaf/src/common/mod.rs @@ -1,4 +1,5 @@ pub mod crypto; +pub mod dns_sniff; pub mod io; pub mod net; pub mod resolver; diff --git a/leaf/src/session.rs b/leaf/src/session.rs index 8a9e650..471cc97 100644 --- a/leaf/src/session.rs +++ b/leaf/src/session.rs @@ -88,6 +88,8 @@ pub struct Session { /// Instructs a multiplexed transport should creates a new underlying /// connection for this session, and it will be used only once. pub new_conn_once: bool, + /// The sniffed domain name if the destination is an IP address. + pub sniffed_domain: Option, } impl Clone for Session { @@ -104,6 +106,7 @@ impl Clone for Session { forwarded_source: self.forwarded_source, process_name: self.process_name.clone(), new_conn_once: self.new_conn_once, + sniffed_domain: self.sniffed_domain.clone(), } } } @@ -131,6 +134,7 @@ impl Default for Session { forwarded_source: None, process_name: None, new_conn_once: false, + sniffed_domain: None, } } }