summaryrefslogtreecommitdiffhomepage
path: root/test/test-manager/src/tests/dns.rs
blob: ff99cb4260e5d721bcf9eee9b77b37a0aeead2b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use anyhow::{Context, anyhow};
use std::{
    net::{IpAddr, Ipv4Addr, SocketAddr},
    sync::atomic::{AtomicUsize, Ordering},
    time::Duration,
};

use itertools::Itertools;
use mullvad_management_interface::MullvadProxyClient;
use mullvad_types::{
    ConnectionConfig, CustomTunnelEndpoint, settings,
    wireguard::{DaitaSettings, QuantumResistantState},
};
use talpid_types::net::wireguard;
use test_macro::test_function;
use test_rpc::ServiceClient;

use super::{
    Error, TestContext,
    helpers::{self, connect_and_wait, set_custom_endpoint},
};
use crate::{
    TEST_CONFIG,
    network_monitor::{
        Direction, IpHeaderProtocols, MonitorOptions, start_packet_monitor_until,
        start_tunnel_packet_monitor_until,
    },
    vm::network::{
        CUSTOM_TUN_GATEWAY, CUSTOM_TUN_LOCAL_PRIVKEY, CUSTOM_TUN_LOCAL_TUN_ADDR,
        CUSTOM_TUN_REMOTE_PUBKEY, CUSTOM_TUN_REMOTE_REAL_PORT, CUSTOM_TUN_REMOTE_TUN_ADDR,
    },
};

/// How long to wait for expected "DNS queries" to appear
const MONITOR_TIMEOUT: Duration = Duration::from_secs(5);

/// Test whether DNS leaks can be produced when using the default resolver. It does this by
/// connecting to a custom WireGuard relay on localhost and monitoring outbound DNS traffic in (and
/// outside of) the tunnel interface.
///
/// The test succeeds if and only if expected outbound packets inside the tunnel on port 53 are
/// observed. If traffic on port 53 is observed outside the tunnel or to an unexpected destination,
/// the test fails.
///
/// # Limitations
///
/// This test only detects outbound DNS leaks in the connected state.
#[test_function]
pub async fn test_dns_leak_default(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> Result<(), Error> {
    leak_test_dns(
        &rpc,
        &mut mullvad_client,
        true,
        IpAddr::V4(CUSTOM_TUN_REMOTE_TUN_ADDR),
    )
    .await
}

/// Test whether DNS leaks can be produced when using a custom public IP. This test succeeds if and
/// only if outgoing packets are only observed on the tunnel interface to the expected IP.
///
/// See `test_dns_leak_default` for more details.
///
/// # Limitations
///
/// This test only detects outbound DNS leaks in the connected state.
#[test_function]
pub async fn test_dns_leak_custom_public_ip(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> Result<(), Error> {
    const CONFIG_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(1, 3, 3, 7));

    log::debug!("Setting custom DNS resolver to {CONFIG_IP}");

    mullvad_client
        .set_dns_options(settings::DnsOptions {
            default_options: settings::DefaultDnsOptions::default(),
            custom_options: settings::CustomDnsOptions {
                addresses: vec![CONFIG_IP],
            },
            state: settings::DnsState::Custom,
        })
        .await
        .expect("failed to configure DNS server");

    leak_test_dns(&rpc, &mut mullvad_client, true, CONFIG_IP).await
}

/// Test whether DNS leaks can be produced when using a custom private IP. This test succeeds if and
/// only if outgoing packets are only observed on the non-tunnel interface to the expected IP.
///
/// See `test_dns_leak_default` for more details.
///
/// # Limitations
///
/// This test only detects outbound DNS leaks in the connected state.
#[test_function]
pub async fn test_dns_leak_custom_private_ip(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> Result<(), Error> {
    const CONFIG_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 64, 10, 1));

    log::debug!("Setting custom DNS resolver to {CONFIG_IP}");

    mullvad_client
        .set_dns_options(settings::DnsOptions {
            default_options: settings::DefaultDnsOptions::default(),
            custom_options: settings::CustomDnsOptions {
                addresses: vec![CONFIG_IP],
            },
            state: settings::DnsState::Custom,
        })
        .await
        .expect("failed to configure DNS server");

    leak_test_dns(&rpc, &mut mullvad_client, false, CONFIG_IP).await
}

/// See whether it is possible to send "DNS queries" to a particular whitelisted destination on
/// either the tunnel interface or a non-tunnel interface on port 53. This test fails if:
/// * No packets to the whitelisted destination are observed, or
/// * Packets to any other destination or a non-matching interface are observed.
async fn leak_test_dns(
    rpc: &ServiceClient,
    mullvad_client: &mut MullvadProxyClient,
    use_tun: bool,
    whitelisted_dest: IpAddr,
) -> Result<(), Error> {
    // Connect to local wireguard relay
    //

    connect_local_wg_relay(mullvad_client)
        .await
        .expect("failed to connect to custom wg relay");

    let nontun_iface = rpc
        .get_default_interface()
        .await
        .expect("failed to find non-tun interface");
    let tunnel_iface = helpers::get_tunnel_interface(mullvad_client)
        .await
        .expect("failed to find tunnel interface");

    let nontun_ip = rpc
        .get_interface_ip(nontun_iface.clone())
        .await
        .expect("failed to obtain guest IP");
    let tunnel_ip = rpc
        .get_interface_ip(tunnel_iface.clone())
        .await
        .expect("failed to obtain tunnel IP");

    log::debug!("Tunnel (guest) IP: {tunnel_ip}");
    log::debug!("Non-tunnel (guest) IP: {nontun_ip}");

    // Spoof DNS packets
    //

    let tun_bind_addr = SocketAddr::new(tunnel_ip, 0);
    let nontun_bind_addr = SocketAddr::new(nontun_ip, 0);

    let whitelisted_dest = SocketAddr::new(whitelisted_dest, 53);
    let blocked_dest_local = "10.64.100.100:53".parse().unwrap();
    let blocked_dest_public = "1.1.1.1:53".parse().unwrap();

    // Capture all outgoing DNS
    let mut pkt_counter = DnsPacketsFound::new(1, 1);

    let (tunnel_monitor, non_tunnel_monitor) = if use_tun {
        let tunnel_monitor = start_tunnel_packet_monitor_until(
            move |packet| packet.destination.port() == 53,
            move |packet| pkt_counter.handle_packet(packet),
            MonitorOptions {
                direction: Some(Direction::In),
                timeout: Some(MONITOR_TIMEOUT),
                ..Default::default()
            },
        )
        .await;
        let non_tunnel_monitor = start_packet_monitor_until(
            move |packet| packet.destination.port() == 53,
            |_packet| false,
            MonitorOptions {
                direction: Some(Direction::In),
                ..Default::default()
            },
        )
        .await;
        (tunnel_monitor, non_tunnel_monitor)
    } else {
        let tunnel_monitor = start_tunnel_packet_monitor_until(
            move |packet| packet.destination.port() == 53,
            |_packet| false,
            MonitorOptions {
                direction: Some(Direction::In),
                ..Default::default()
            },
        )
        .await;
        let non_tunnel_monitor = start_packet_monitor_until(
            move |packet| packet.destination.port() == 53,
            move |packet| pkt_counter.handle_packet(packet),
            MonitorOptions {
                direction: Some(Direction::In),
                timeout: Some(MONITOR_TIMEOUT),
                ..Default::default()
            },
        )
        .await;
        (tunnel_monitor, non_tunnel_monitor)
    };

    // We should observe 2 outgoing packets to the whitelisted destination
    // on port 53, and only inside the desired interface.

    let rpc = rpc.clone();
    let probes = tokio::spawn(async move {
        tokio::join!(
            // send to allowed dest
            spoof_packets(
                &rpc,
                Some(tunnel_iface.clone()),
                tun_bind_addr,
                whitelisted_dest,
            ),
            spoof_packets(
                &rpc,
                Some(nontun_iface.clone()),
                nontun_bind_addr,
                whitelisted_dest,
            ),
            // send to blocked local dest
            spoof_packets(
                &rpc,
                Some(tunnel_iface.clone()),
                tun_bind_addr,
                blocked_dest_local,
            ),
            spoof_packets(
                &rpc,
                Some(nontun_iface.clone()),
                nontun_bind_addr,
                blocked_dest_local,
            ),
            // send to blocked public dest
            spoof_packets(&rpc, Some(tunnel_iface), tun_bind_addr, blocked_dest_public,),
            spoof_packets(
                &rpc,
                Some(nontun_iface),
                nontun_bind_addr,
                blocked_dest_public,
            ),
        )
    });

    if use_tun {
        // Examine tunnel traffic
        //

        let tunnel_result = tunnel_monitor.wait().await.unwrap();

        probes.abort();
        let _ = probes.await;

        assert!(
            tunnel_result.packets.len() >= 2,
            "expected at least 2 in-tunnel packets to allowed destination only"
        );

        for pkt in tunnel_result.packets {
            assert_eq!(
                pkt.destination, whitelisted_dest,
                "unexpected tunnel packet on port 53"
            );
        }

        // Examine non-tunnel traffic
        //

        let non_tunnel_result = non_tunnel_monitor.into_result().await.unwrap();
        assert_eq!(
            non_tunnel_result.packets.len(),
            0,
            "expected no non-tunnel packets on port 53"
        );
    } else {
        let non_tunnel_result = non_tunnel_monitor.wait().await.unwrap();

        probes.abort();
        let _ = probes.await;

        // Examine tunnel traffic
        //

        let tunnel_result = tunnel_monitor.into_result().await.unwrap();
        assert_eq!(
            tunnel_result.packets.len(),
            0,
            "expected no tunnel packets on port 53"
        );

        // Examine non-tunnel traffic
        //

        assert!(
            non_tunnel_result.packets.len() >= 2,
            "expected at least 2 non-tunnel packets to allowed destination only"
        );

        for pkt in non_tunnel_result.packets {
            assert_eq!(
                pkt.destination, whitelisted_dest,
                "unexpected non-tunnel packet on port 53"
            );
        }
    }

    Ok(())
}

/// Test whether the expected default DNS resolver is used by `getaddrinfo` (via `ToSocketAddrs`).
///
/// # Limitations
///
/// This only examines outbound packets.
#[test_function]
pub async fn test_dns_config_default(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> anyhow::Result<()> {
    run_dns_config_tunnel_test(
        &rpc,
        &mut mullvad_client,
        IpAddr::V4(CUSTOM_TUN_REMOTE_TUN_ADDR),
    )
    .await
}

/// Test whether the expected custom DNS works for private IPs.
///
/// # Limitations
///
/// This only examines outbound packets.
#[test_function]
pub async fn test_dns_config_custom_private(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> anyhow::Result<()> {
    log::debug!(
        "Setting custom DNS resolver to {}",
        TEST_CONFIG.host_bridge_ip
    );

    mullvad_client
        .set_dns_options(settings::DnsOptions {
            default_options: settings::DefaultDnsOptions::default(),
            custom_options: settings::CustomDnsOptions {
                addresses: vec![IpAddr::V4(TEST_CONFIG.host_bridge_ip)],
            },
            state: settings::DnsState::Custom,
        })
        .await
        .context("failed to configure DNS server")?;

    run_dns_config_non_tunnel_test(
        &rpc,
        &mut mullvad_client,
        IpAddr::V4(TEST_CONFIG.host_bridge_ip),
    )
    .await
}

/// Test whether the expected custom DNS works for public IPs.
///
/// # Limitations
///
/// This only examines outbound packets.
#[test_function]
pub async fn test_dns_config_custom_public(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> anyhow::Result<()> {
    let custom_ip = IpAddr::V4(Ipv4Addr::new(1, 3, 3, 7));

    log::debug!("Setting custom DNS resolver to {custom_ip}");

    mullvad_client
        .set_dns_options(settings::DnsOptions {
            default_options: settings::DefaultDnsOptions::default(),
            custom_options: settings::CustomDnsOptions {
                addresses: vec![custom_ip],
            },
            state: settings::DnsState::Custom,
        })
        .await
        .context("failed to configure DNS server")?;

    run_dns_config_tunnel_test(&rpc, &mut mullvad_client, custom_ip).await
}

/// Test whether the correct IPs are configured as system resolver when
/// content blockers are enabled.
#[test_function]
pub async fn test_content_blockers(
    _: TestContext,
    rpc: ServiceClient,
    mut mullvad_client: MullvadProxyClient,
) -> anyhow::Result<()> {
    const DNS_BLOCKING_IP_BASE: Ipv4Addr = Ipv4Addr::new(100, 64, 0, 0);
    let content_blockers = [
        (
            "adblocking",
            1 << 0,
            settings::DefaultDnsOptions {
                block_ads: true,
                ..Default::default()
            },
        ),
        (
            "tracker",
            1 << 1,
            settings::DefaultDnsOptions {
                block_trackers: true,
                ..Default::default()
            },
        ),
        (
            "malware",
            1 << 2,
            settings::DefaultDnsOptions {
                block_malware: true,
                ..Default::default()
            },
        ),
        (
            "adult",
            1 << 3,
            settings::DefaultDnsOptions {
                block_adult_content: true,
                ..Default::default()
            },
        ),
        (
            "gambling",
            1 << 4,
            settings::DefaultDnsOptions {
                block_gambling: true,
                ..Default::default()
            },
        ),
    ];

    let combine_cases = |v: Vec<&(&str, u8, settings::DefaultDnsOptions)>| {
        let mut combination_name = String::new();
        let mut last_byte = 0;
        let mut options = settings::DefaultDnsOptions::default();

        for case in v {
            if !combination_name.is_empty() {
                combination_name.push_str(" + ");
            }
            combination_name.push_str(case.0);

            last_byte |= case.1;

            options.block_ads |= case.2.block_ads;
            options.block_trackers |= case.2.block_trackers;
            options.block_malware |= case.2.block_malware;
            options.block_adult_content |= case.2.block_adult_content;
            options.block_gambling |= case.2.block_gambling;
        }

        let mut dns_ip = DNS_BLOCKING_IP_BASE.octets();
        dns_ip[dns_ip.len() - 1] |= last_byte;

        (
            combination_name,
            IpAddr::V4(Ipv4Addr::from(dns_ip)),
            options,
        )
    };

    // Test all combinations

    for case in content_blockers.iter().powerset() {
        if case.is_empty() {
            continue;
        }
        let (test_name, test_ip, test_opts) = combine_cases(case);

        log::debug!("Testing content blocker: {test_name}, {test_ip}");

        mullvad_client
            .set_dns_options(settings::DnsOptions {
                default_options: test_opts,
                custom_options: settings::CustomDnsOptions::default(),
                state: settings::DnsState::Default,
            })
            .await
            .context("failed to configure DNS server")?;

        run_dns_config_tunnel_test(&rpc, &mut mullvad_client, test_ip).await?;
    }

    Ok(())
}

async fn run_dns_config_tunnel_test(
    rpc: &ServiceClient,
    mullvad_client: &mut MullvadProxyClient,
    expected_dns_resolver: IpAddr,
) -> anyhow::Result<()> {
    run_dns_config_test(
        rpc,
        || {
            start_tunnel_packet_monitor_until(
                move |packet| packet.destination.port() == 53,
                |packet| packet.destination.port() != 53,
                MonitorOptions {
                    direction: Some(Direction::In),
                    timeout: Some(MONITOR_TIMEOUT),
                    ..Default::default()
                },
            )
        },
        mullvad_client,
        expected_dns_resolver,
    )
    .await
}

async fn run_dns_config_non_tunnel_test(
    rpc: &ServiceClient,
    mullvad_client: &mut MullvadProxyClient,
    expected_dns_resolver: IpAddr,
) -> anyhow::Result<()> {
    run_dns_config_test(
        rpc,
        || {
            start_packet_monitor_until(
                move |packet| packet.destination.port() == 53,
                |packet| packet.destination.port() != 53,
                MonitorOptions {
                    direction: Some(Direction::In),
                    timeout: Some(MONITOR_TIMEOUT),
                    ..Default::default()
                },
            )
        },
        mullvad_client,
        expected_dns_resolver,
    )
    .await
}

async fn run_dns_config_test<
    F: std::future::Future<Output = crate::network_monitor::PacketMonitor>,
>(
    rpc: &ServiceClient,
    create_monitor: impl FnOnce() -> F,
    mullvad_client: &mut MullvadProxyClient,
    expected_dns_resolver: IpAddr,
) -> anyhow::Result<()> {
    match mullvad_client.get_tunnel_state().await {
        // prevent reconnect
        Ok(mullvad_types::states::TunnelState::Connected { .. }) => (),
        _ => {
            connect_local_wg_relay(mullvad_client)
                .await
                .context("failed to connect to custom wg relay")?;
        }
    }

    let nontun_iface = rpc
        .get_default_interface()
        .await
        .context("failed to find non-tun interface")?;
    let tunnel_iface = helpers::get_tunnel_interface(mullvad_client)
        .await
        .context("failed to find tunnel interface")?;

    let nontun_ip = rpc
        .get_interface_ip(nontun_iface)
        .await
        .context("failed to obtain guest IP")?;
    let tunnel_ip = rpc
        .get_interface_ip(tunnel_iface)
        .await
        .context("failed to obtain tunnel IP")?;

    log::debug!("Tunnel (guest) IP: {tunnel_ip}");
    log::debug!("Non-tunnel (guest) IP: {nontun_ip}");

    let monitor = create_monitor().await;

    let next_nonce = {
        static NONCE: AtomicUsize = AtomicUsize::new(0);
        || NONCE.fetch_add(1, Ordering::Relaxed)
    };

    let rpc_client = rpc.clone();
    let handle = tokio::spawn(async move {
        // Resolve a "random" domain name to prevent caching.
        // Try multiple times, as the DNS config change may not take effect immediately.
        for _ in 0..2 {
            let _ = rpc_client
                .resolve_hostname(format!("test{}.mullvad.net", next_nonce()))
                .await;
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    });

    assert_eq!(
        monitor
            .wait()
            .await?
            .packets
            .first()
            .ok_or(anyhow!("Expected at least one packet, saw none"))?
            .destination,
        SocketAddr::new(expected_dns_resolver, 53),
        "expected tunnel packet to expected destination {expected_dns_resolver}"
    );

    handle.abort();
    let _ = handle.await;

    Ok(())
}

/// Connect to the WireGuard relay that is set up in test-manager/src/vm/network
/// See those files for details.
async fn connect_local_wg_relay(mullvad_client: &mut MullvadProxyClient) -> Result<(), Error> {
    // the local wg relay doesn't support negotiating an ephemeral peer
    // which means we can't use PQ or daita.
    mullvad_client
        .set_quantum_resistant_tunnel(QuantumResistantState::Off)
        .await?;
    mullvad_client
        .set_daita_settings(DaitaSettings::default())
        .await?;

    let peer_addr: SocketAddr = SocketAddr::new(
        IpAddr::V4(TEST_CONFIG.host_bridge_ip),
        CUSTOM_TUN_REMOTE_REAL_PORT,
    );

    let custom_tunnel_endpoint = CustomTunnelEndpoint {
        host: peer_addr.ip().to_string(),
        config: ConnectionConfig::Wireguard(wireguard::ConnectionConfig {
            tunnel: wireguard::TunnelConfig {
                addresses: vec![IpAddr::V4(CUSTOM_TUN_LOCAL_TUN_ADDR)],
                private_key: wireguard::PrivateKey::from(CUSTOM_TUN_LOCAL_PRIVKEY),
            },
            peer: wireguard::PeerConfig {
                public_key: wireguard::PublicKey::from(CUSTOM_TUN_REMOTE_PUBKEY),
                allowed_ips: vec!["0.0.0.0/0".parse().unwrap()],
                endpoint: peer_addr,
                psk: None,
                constant_packet_size: false,
            },
            ipv4_gateway: CUSTOM_TUN_GATEWAY,
            exit_peer: None,
            #[cfg(target_os = "linux")]
            fwmark: None,
            ipv6_gateway: None,
        }),
    };
    set_custom_endpoint(mullvad_client, custom_tunnel_endpoint)
        .await
        .expect("failed to update relay settings");

    connect_and_wait(mullvad_client).await?;

    Ok(())
}

async fn spoof_packets(
    rpc: &ServiceClient,
    interface: Option<String>,
    bind_addr: SocketAddr,
    dest: SocketAddr,
) {
    let tcp_rpc = rpc.clone();
    let tcp_interface = interface.clone();
    let tcp_send = async move {
        log::debug!("sending to {}/tcp from {}", dest, bind_addr);
        let _ = tcp_rpc.send_tcp(tcp_interface, bind_addr, dest).await;
    };
    let udp_rpc = rpc.clone();
    let udp_interface = interface.clone();
    let udp_send = async move {
        log::debug!("sending to {}/udp from {}", dest, bind_addr);
        let _ = udp_rpc.send_udp(udp_interface, bind_addr, dest).await;
    };
    let _ = tokio::join!(tcp_send, udp_send);
}

type ShouldContinue = bool;

struct DnsPacketsFound {
    tcp_count: usize,
    udp_count: usize,
    min_tcp_count: usize,
    min_udp_count: usize,
}

impl DnsPacketsFound {
    fn new(min_udp_count: usize, min_tcp_count: usize) -> Self {
        Self {
            tcp_count: 0,
            udp_count: 0,
            min_tcp_count,
            min_udp_count,
        }
    }

    fn handle_packet(&mut self, pkt: &crate::network_monitor::ParsedPacket) -> ShouldContinue {
        if pkt.destination.port() != 53 && pkt.source.port() != 53 {
            return true;
        }
        match pkt.protocol {
            IpHeaderProtocols::Udp => self.udp_count += 1,
            IpHeaderProtocols::Tcp => self.tcp_count += 1,
            _ => return true,
        }
        self.udp_count < self.min_udp_count || self.tcp_count < self.min_tcp_count
    }
}