ndisapi 0.6.5

Rust crate for interacting with the Windows Packet Filter driver (NDISAPI)
Documentation
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/// This example demonstrates the basic usage of the `set_packet_filter_table` API, showcasing different filter scenarios:
///
/// 1. Redirect only DNS packets for user mode processing.
/// 2. Redirect only HTTP (TCP port 80) packets for user mode processing.
/// 3. Drop all ICMP packets and redirect all other packets to user mode (default behavior).
/// 4. Block access to http://www.ntkernel.com, while allowing all other packets to pass without user mode processing.
/// 5. Redirect only ARP/RARP packets to user mode, and pass all other packets without processing.
/// 6. Redirect only outgoing ICMP ping request packets to user mode. Pass all others.
use clap::Parser;
use ndisapi::{
    ByteRange, DataLinkLayerFilter, DataLinkLayerFilterUnion, DirectionFlags, Eth8023Filter,
    Eth802_3FilterFlags, EthRequest, EthRequestMut, FilterFlags, FilterLayerFlags, IcmpFilter,
    IcmpFilterFlags, IntermediateBuffer, IpAddressV4, IpAddressV4Union, IpAddressV6, IpSubnetV4,
    IpV4Filter, IpV4FilterFlags, IpV6Filter, IpV6FilterFlags, Ndisapi, NetworkLayerFilter,
    NetworkLayerFilterUnion, PortRange, StaticFilter, StaticFilterTable, TcpUdpFilter,
    TcpUdpFilterFlags, TransportLayerFilter, TransportLayerFilterUnion, ETHER_ADDR_LENGTH,
    ETH_802_3, FILTER_PACKET_DROP, FILTER_PACKET_PASS, FILTER_PACKET_REDIRECT, ICMP, IPV4, IPV6,
    IP_SUBNET_V4_TYPE, TCPUDP,
};
use smoltcp::wire::{
    ArpPacket, EthernetFrame, EthernetProtocol, Icmpv4Packet, Icmpv6Packet, IpProtocol, Ipv4Packet,
    Ipv6Packet, TcpPacket, UdpPacket,
};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use windows::{
    core::Result,
    Win32::Foundation::{CloseHandle, HANDLE},
    Win32::Networking::WinSock::{IN_ADDR, IN_ADDR_0, IN_ADDR_0_0},
    Win32::System::Threading::{CreateEventW, ResetEvent, SetEvent, WaitForSingleObject},
};

#[derive(Parser)]
struct Cli {
    /// Network interface index (please use listadapters example to determine the right one)
    #[clap(short, long)]
    interface_index: usize,
    /// Filter set to apply the selected network interface. The following sets are supported:
    /// 1 - Redirect only IPv4 DNS packets for processing in user mode.
    /// 2 - Redirect only HTTP(TCP port 80) packets for processing in user mode. Both IPv4 and IPv6 protocols.
    /// 3 - Drop all IPv4 ICMP packets. Redirect all other packets to user mode (default behaviour).
    /// 4 - Block IPv4 access to https://www.ntkernel.com. Pass all other packets without processing in user mode.
    /// 5 - Redirect only ARP/RARP packets to user mode. Pass all others.
    /// 6 - Redirect only outgoing ICMP ping request packets to user mode. Pass all others.
    #[clap(short, long, verbatim_doc_comment)]
    filter: usize,
}

// Reverse Addr Res packet
const ETH_P_RARP: u16 = 0x8035;
// Address Resolution packet
const ETH_P_ARP: u16 = 0x0806;

const IPPROTO_ICMP: u8 = 1;
const IPPROTO_TCP: u8 = 6;
const IPPROTO_UDP: u8 = 17;

const DNS_PORT: u16 = 53;
const HTTP_PORT: u16 = 80;

/// Sets up a packet filter table for IPv4 DNS packets.
///
/// This function configures a packet filter table with three filters:
///
/// 1. Outgoing DNS requests filter: This filter redirects outgoing UDP packets with destination port 53 (DNS) for processing in user mode. It applies to all network adapters.
///
/// 2. Incoming DNS responses filter: This filter redirects incoming UDP packets with source port 53 (DNS) for processing in user mode. It applies to all network adapters.
///
/// 3. Default pass filter: This filter passes all packets that are not matched by the previous filters without processing in user mode. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_ipv4_dns_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<3>::from_filters([
        // 1. Outgoing DNS requests filter: REDIRECT OUT UDP packets with destination PORT 53
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_UDP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_DEST_PORT,
                        PortRange::default(),
                        PortRange::new(DNS_PORT, DNS_PORT),
                        0u8,
                    ),
                },
            ),
        ),
        // 2. Incoming DNS responses filter: REDIRECT IN UDP packets with source PORT 53
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_UDP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_SRC_PORT,
                        PortRange::new(DNS_PORT, DNS_PORT),
                        PortRange::default(),
                        0u8,
                    ),
                },
            ),
        ),
        // 3. Pass all packets (skipped by previous filters) without processing in user mode
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE | DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_PASS,
            FilterLayerFlags::empty(),
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Sets up a packet filter table for HTTP packets over IPv4 and IPv6.
///
/// This function configures a packet filter table with five filters:
///
/// 1. Outgoing HTTP requests filter (IPv4): This filter redirects outgoing TCP packets with destination port 80 (HTTP) for processing in user mode. It applies to all network adapters.
///
/// 2. Incoming HTTP responses filter (IPv4): This filter redirects incoming TCP packets with source port 80 (HTTP) for processing in user mode. It applies to all network adapters.
///
/// 3. Outgoing HTTP requests filter (IPv6): This filter redirects outgoing TCP packets with destination port 80 (HTTP) for processing in user mode. It applies to all network adapters.
///
/// 4. Incoming HTTP responses filter (IPv6): This filter redirects incoming TCP packets with source port 80 (HTTP) for processing in user mode. It applies to all network adapters.
///
/// 5. Default pass filter: This filter passes all packets that are not matched by the previous filters without processing in user mode. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_http_ipv4v6_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<5>::from_filters([
        // 1. Outgoing HTTP requests filter: REDIRECT OUT TCP packets with destination PORT 80 IPv4
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_TCP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_DEST_PORT,
                        PortRange::default(),
                        PortRange::new(HTTP_PORT, HTTP_PORT),
                        0u8,
                    ),
                },
            ),
        ),
        // 2. Incoming HTTP responses filter: REDIRECT IN TCP packets with source PORT 80 IPv4
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_TCP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_SRC_PORT,
                        PortRange::new(HTTP_PORT, HTTP_PORT),
                        PortRange::default(),
                        0u8,
                    ),
                },
            ),
        ),
        // 3. Outgoing HTTP requests filter: REDIRECT OUT TCP packets with destination PORT 80 IPv6
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV6,
                NetworkLayerFilterUnion {
                    ipv6: IpV6Filter::new(
                        IpV6FilterFlags::IP_V6_FILTER_PROTOCOL,
                        IpAddressV6::default(),
                        IpAddressV6::default(),
                        IPPROTO_TCP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_DEST_PORT,
                        PortRange::default(),
                        PortRange::new(HTTP_PORT, HTTP_PORT),
                        0u8,
                    ),
                },
            ),
        ),
        // 4. Incoming HTTP responses filter: REDIRECT IN TCP packets with source PORT 80 IPv6
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV6,
                NetworkLayerFilterUnion {
                    ipv6: IpV6Filter::new(
                        IpV6FilterFlags::IP_V6_FILTER_PROTOCOL,
                        IpAddressV6::default(),
                        IpAddressV6::default(),
                        IPPROTO_TCP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_SRC_PORT,
                        PortRange::new(HTTP_PORT, HTTP_PORT),
                        PortRange::default(),
                        0u8,
                    ),
                },
            ),
        ),
        // 5. Pass all packets (skipped by previous filters) without processing in user mode
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE | DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_PASS,
            FilterLayerFlags::empty(),
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Sets up a packet filter table to drop all ICMP packets.
///
/// This function configures a packet filter table with a single filter:
///
/// 1. Block all ICMP packets: This filter drops all ICMP packets, both incoming and outgoing. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_icmpv4_drop_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<1>::from_filters([
        // 1. Block all ICMP packets
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND | DirectionFlags::PACKET_FLAG_ON_RECEIVE,
            FILTER_PACKET_DROP,
            FilterLayerFlags::NETWORK_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_ICMP,
                    ),
                },
            ),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Sets up a packet filter table to block access to https://www.ntkernel.com over IPv4.
///
/// This function configures a packet filter table with two filters:
///
/// 1. Outgoing HTTP requests filter: This filter drops outgoing TCP packets with destination IP 95.179.146.125 and destination port 443 (https://www.ntkernel.com). It applies to all network adapters.
///
/// 2. Default pass filter: This filter passes all packets that are not matched by the previous filter without processing in user mode. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_block_ntkernel_https_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<2>::from_filters([
        // 1. Outgoing HTTP requests filter: DROP OUT TCP packets with destination IP 95.179.146.125 PORT 443 (https://www.ntkernel.com)
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_DROP,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL
                            | IpV4FilterFlags::IP_V4_FILTER_DEST_ADDRESS,
                        IpAddressV4::default(),
                        IpAddressV4::new(
                            IP_SUBNET_V4_TYPE,
                            IpAddressV4Union {
                                ip_subnet: IpSubnetV4::new(
                                    IN_ADDR {
                                        S_un: IN_ADDR_0 {
                                            S_un_b: IN_ADDR_0_0 {
                                                s_b1: 95,
                                                s_b2: 179,
                                                s_b3: 146,
                                                s_b4: 125,
                                            },
                                        },
                                    },
                                    IN_ADDR {
                                        S_un: IN_ADDR_0 {
                                            S_un_b: IN_ADDR_0_0 {
                                                s_b1: 255,
                                                s_b2: 255,
                                                s_b3: 255,
                                                s_b4: 255,
                                            },
                                        },
                                    },
                                ),
                            },
                        ),
                        IPPROTO_TCP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                TCPUDP,
                TransportLayerFilterUnion {
                    tcp_udp: TcpUdpFilter::new(
                        TcpUdpFilterFlags::TCPUDP_DEST_PORT,
                        PortRange::default(),
                        PortRange::new(443, 443),
                        0u8,
                    ),
                },
            ),
        ),
        // 2. Pass all packets (skipped by previous filters) without processing in user mode
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE | DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_PASS,
            FilterLayerFlags::empty(),
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Sets up a packet filter table to redirect ARP and RARP packets for user mode processing.
///
/// This function configures a packet filter table with three filters:
///
/// 1. ARP packets filter: This filter redirects all ARP packets for processing in user mode. It applies to all network adapters.
///
/// 2. RARP packets filter: This filter redirects all RARP packets for processing in user mode. It applies to all network adapters.
///
/// 3. Default pass filter: This filter passes all packets that are not matched by the previous filters without processing in user mode. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_redirect_arp_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<3>::from_filters([
        // 1. Redirects all ARP packets to be processed by user mode application
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND_RECEIVE,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::DATA_LINK_LAYER_VALID,
            DataLinkLayerFilter::new(
                ETH_802_3,
                DataLinkLayerFilterUnion {
                    eth_8023_filter: Eth8023Filter::new(
                        Eth802_3FilterFlags::ETH_802_3_PROTOCOL,
                        [0; ETHER_ADDR_LENGTH],
                        [0; ETHER_ADDR_LENGTH],
                        ETH_P_ARP,
                    ),
                },
            ),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
        // 2. Redirects all RARP packets to be processed by user mode application
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND_RECEIVE,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::DATA_LINK_LAYER_VALID,
            DataLinkLayerFilter::new(
                ETH_802_3,
                DataLinkLayerFilterUnion {
                    eth_8023_filter: Eth8023Filter::new(
                        Eth802_3FilterFlags::ETH_802_3_PROTOCOL,
                        [0; ETHER_ADDR_LENGTH],
                        [0; ETHER_ADDR_LENGTH],
                        ETH_P_RARP,
                    ),
                },
            ),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
        // 3. Pass all packets (skipped by previous filters) without processing in user mode
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE | DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_PASS,
            FilterLayerFlags::empty(),
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Sets up a packet filter table to redirect outgoing ICMP ping request packets for user mode processing.
///
/// This function configures a packet filter table with two filters:
///
/// 1. Outgoing ICMP ping requests filter: This filter redirects outgoing ICMP ping request packets for processing in user mode. It applies to all network adapters.
///
/// 2. Default pass filter: This filter passes all packets that are not matched by the previous filter without processing in user mode. It applies to all network adapters.
///
/// After setting up the filter table, this function applies it to the network interface using the `set_packet_filter_table` method of the `Ndisapi` object.
///
/// # Arguments
///
/// * `ndisapi` - A reference to the `Ndisapi` object that represents the network interface.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn load_redirect_icmp_req_filters(ndisapi: &Ndisapi) -> Result<()> {
    let filter_table = StaticFilterTable::<2>::from_filters([
        // 1. Redirects all outgoing ICMP ping request packets to be processed by user mode application
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_REDIRECT,
            FilterLayerFlags::NETWORK_LAYER_VALID | FilterLayerFlags::TRANSPORT_LAYER_VALID,
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::new(
                IPV4,
                NetworkLayerFilterUnion {
                    ipv4: IpV4Filter::new(
                        IpV4FilterFlags::IP_V4_FILTER_PROTOCOL,
                        IpAddressV4::default(),
                        IpAddressV4::default(),
                        IPPROTO_ICMP,
                    ),
                },
            ),
            TransportLayerFilter::new(
                ICMP,
                TransportLayerFilterUnion {
                    icmp: IcmpFilter::new(
                        IcmpFilterFlags::ICMP_TYPE,
                        ByteRange::new(8, 8),
                        ByteRange::default(),
                    ),
                },
            ),
        ),
        // 2. Pass all packets (skipped by previous filters) without processing in user mode
        StaticFilter::new(
            0, // applied to all adapters
            DirectionFlags::PACKET_FLAG_ON_RECEIVE | DirectionFlags::PACKET_FLAG_ON_SEND,
            FILTER_PACKET_PASS,
            FilterLayerFlags::empty(),
            DataLinkLayerFilter::default(),
            NetworkLayerFilter::default(),
            TransportLayerFilter::default(),
        ),
    ]);

    ndisapi.set_packet_filter_table(&filter_table)
}

/// Entry point of the application.
///
/// This function parses the command line arguments, initializes the Ndisapi driver, sets up the packet filter table based on the selected filter set, and starts the packet processing loop.
///
/// The packet processing loop reads packets from the network interface, prints some information about each packet, and then re-injects the packets back into the network stack.
///
/// The loop continues until the user presses Ctrl-C.
///
/// # Arguments
///
/// None.
///
/// # Returns
///
/// This function returns a `Result` that indicates whether the operation succeeded or failed. If the operation succeeded, the `Result` contains `()`. If the operation failed, the `Result` contains an error.
///
/// # Examples
///
///
fn main() -> Result<()> {
    // Parse command line arguments
    let Cli {
        mut interface_index,
        filter,
    } = Cli::parse();

    // Adjust the interface index to be zero-based
    interface_index -= 1;

    // Initialize the Ndisapi driver
    let driver =
        Ndisapi::new("NDISRD").expect("WinpkFilter driver is not installed or failed to load!");

    // Print the version of the WinpkFilter driver
    println!(
        "Detected Windows Packet Filter version {}",
        driver.get_version()?
    );

    // Get the list of network interfaces that are bound to TCP/IP
    let adapters = driver.get_tcpip_bound_adapters_info()?;

    // Check if the selected interface index is valid
    if interface_index + 1 > adapters.len() {
        panic!("Interface index is beyond the number of available interfaces");
    }

    // Print the name of the selected network interface
    println!("Using interface {}s", adapters[interface_index].get_name());

    // Set up the packet filter table based on the selected filter set
    let filter_set_result = match filter {
        1 => load_ipv4_dns_filters(&driver),
        2 => load_http_ipv4v6_filters(&driver),
        3 => load_icmpv4_drop_filters(&driver),
        4 => load_block_ntkernel_https_filters(&driver),
        5 => load_redirect_arp_filters(&driver),
        6 => load_redirect_icmp_req_filters(&driver),
        _ => panic!("Filter set is not available"),
    };

    // Check if the packet filter table was set up successfully
    match filter_set_result {
        Ok(_) => println!("Successfully loaded static filters into the driver."),
        Err(err) => panic!("Failed to load static filter into the driver. Error code: {err}"),
    }

    // Create a Win32 event for packet arrival notification
    let event: HANDLE;
    unsafe {
        event = CreateEventW(None, true, false, None)?;
    }

    // Convert HANDLE to usize for Send-safe closure capture
    let event_raw = event.0 as usize;

    // Set up a Ctrl-C handler to terminate the packet processing loop
    let terminate: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
    let ctrlc_pressed = terminate.clone();
    ctrlc::set_handler(move || {
        println!("Ctrl-C was pressed. Terminating...");
        // Set the atomic flag to exit the loop
        ctrlc_pressed.store(true, Ordering::SeqCst);
        // Signal the event to release the loop if there are no packets in the queue
        // Reconstruct HANDLE from the raw value
        let handle = HANDLE(event_raw as *mut std::ffi::c_void);
        let _ = unsafe { SetEvent(handle) };
    })
    .expect("Error setting Ctrl-C handler");

    // Set the event within the driver for packet arrival notification
    driver.set_packet_event(adapters[interface_index].get_handle(), event)?;

    // Put the network interface into tunnel mode
    driver.set_adapter_mode(
        adapters[interface_index].get_handle(),
        FilterFlags::MSTCP_FLAG_SENT_RECEIVE_TUNNEL,
    )?;

    // Allocate a single IntermediateBuffer on the stack for packet reading
    let mut packet = IntermediateBuffer::default();

    // Start the packet processing loop
    while !terminate.load(Ordering::SeqCst) {
        // Wait for a packet to arrive
        unsafe {
            WaitForSingleObject(event, u32::MAX);
        }
        loop {
            // Initialize an EthRequestMut to pass to the driver API
            let mut read_request = EthRequestMut::new(adapters[interface_index].get_handle());

            // Set the packet buffer
            read_request.set_packet(&mut packet);

            // Read a packet from the network interface
            if driver.read_packet(&mut read_request).ok().is_none() {
                // No more packets in the queue, break the loop
                break;
            }

            // Get the direction of the packet
            let direction_flags = packet.get_device_flags();

            // Print packet information
            if direction_flags == DirectionFlags::PACKET_FLAG_ON_SEND {
                println!("\nMSTCP --> Interface ({} bytes)\n", packet.get_length());
            } else {
                println!("\nInterface --> MSTCP ({} bytes)\n", packet.get_length());
            }

            // Print some information about the packet
            print_packet_info(&packet);

            // Initialize an EthRequest to pass to the driver API
            let mut write_request = EthRequest::new(adapters[interface_index].get_handle());

            // Set the packet buffer
            write_request.set_packet(&packet);

            // Re-inject the packet back into the network stack
            if direction_flags == DirectionFlags::PACKET_FLAG_ON_SEND {
                // Send the packet to the network interface
                match driver.send_packet_to_adapter(&write_request) {
                    Ok(_) => {}
                    Err(err) => println!("Error sending packet to adapter. Error code = {err}"),
                };
            } else {
                // Send the packet to the TCP/IP stack
                match driver.send_packet_to_mstcp(&write_request) {
                    Ok(_) => {}
                    Err(err) => println!("Error sending packet to mstcp. Error code = {err}"),
                }
            }
        }

        // Reset the event to continue waiting for packets to arrive
        let _ = unsafe { ResetEvent(event) };
    }

    // Put the network interface back into default mode
    driver.set_adapter_mode(
        adapters[interface_index].get_handle(),
        FilterFlags::default(),
    )?;

    // Close the event handle
    let _ = unsafe { CloseHandle(event) };

    // Return success
    Ok(())
}

/// Print detailed information about a network packet.
///
/// This function takes an `IntermediateBuffer` containing a network packet and prints various
/// details about the packet, such as Ethernet, IPv4, IPv6, ICMPv4, ICMPv6, UDP, and TCP information.
///
/// # Arguments
///
/// * `packet` - A reference to an `IntermediateBuffer` containing the network packet.
///
/// # Examples
///
/// ```no_run
/// let packet: IntermediateBuffer = ...;
/// print_packet_info(&packet);
/// ```
fn print_packet_info(packet: &IntermediateBuffer) {
    let eth_hdr = EthernetFrame::new_unchecked(packet.get_data());
    match eth_hdr.ethertype() {
        EthernetProtocol::Ipv4 => {
            let ipv4_packet = Ipv4Packet::new_unchecked(eth_hdr.payload());
            println!(
                "  Ipv4 {:?} => {:?}",
                ipv4_packet.src_addr(),
                ipv4_packet.dst_addr()
            );
            match ipv4_packet.next_header() {
                IpProtocol::Icmp => {
                    let icmp_packet = Icmpv4Packet::new_unchecked(ipv4_packet.payload());
                    println!(
                        "ICMPv4: Type: {:?} Code: {:?}",
                        icmp_packet.msg_type(),
                        icmp_packet.msg_code()
                    );
                }
                IpProtocol::Tcp => {
                    let tcp_packet = TcpPacket::new_unchecked(ipv4_packet.payload());
                    println!(
                        "   TCP {:?} -> {:?}",
                        tcp_packet.src_port(),
                        tcp_packet.dst_port()
                    );
                }
                IpProtocol::Udp => {
                    let udp_packet = UdpPacket::new_unchecked(ipv4_packet.payload());
                    println!(
                        "   UDP {:?} -> {:?}",
                        udp_packet.src_port(),
                        udp_packet.dst_port()
                    );
                }
                _ => {
                    println!("Unknown IPv4 packet: {:?}", ipv4_packet);
                }
            }
        }
        EthernetProtocol::Ipv6 => {
            let ipv6_packet = Ipv6Packet::new_unchecked(eth_hdr.payload());
            println!(
                "  Ipv6 {:?} => {:?}",
                ipv6_packet.src_addr(),
                ipv6_packet.dst_addr()
            );
            match ipv6_packet.next_header() {
                IpProtocol::Icmpv6 => {
                    let icmpv6_packet = Icmpv6Packet::new_unchecked(ipv6_packet.payload());
                    println!(
                        "ICMPv6 packet: Type: {:?} Code: {:?}",
                        icmpv6_packet.msg_type(),
                        icmpv6_packet.msg_code()
                    );
                }
                IpProtocol::Tcp => {
                    let tcp_packet = TcpPacket::new_unchecked(ipv6_packet.payload());
                    println!(
                        "   TCP {:?} -> {:?}",
                        tcp_packet.src_port(),
                        tcp_packet.dst_port()
                    );
                }
                IpProtocol::Udp => {
                    let udp_packet = UdpPacket::new_unchecked(ipv6_packet.payload());
                    println!(
                        "   UDP {:?} -> {:?}",
                        udp_packet.src_port(),
                        udp_packet.dst_port()
                    );
                }
                _ => {
                    println!("Unknown IPv6 packet: {:?}", ipv6_packet);
                }
            }
        }
        EthernetProtocol::Arp => {
            let arp_packet = ArpPacket::new_unchecked(eth_hdr.payload());
            println!("ARP packet: {:?}", arp_packet);
        }
        EthernetProtocol::Unknown(_) => {
            println!("Unknown Ethernet packet: {:?}", eth_hdr);
        }
    }
}