Packet filter для windows

Packet Filter (PF): установка и настройка

Pa?cket Fi?lter (PF) — Межсетевой экран, разрабатываемый в рамках проекта OpenBSD. Обладает высокой скоростью работы, удобством в конфигурировании и большими возможностями, включая поддержку IPv6. На данный момент используется, помимо OpenBSD, также в NetBSD и FreeBSD, а также основанных на этих трёх MirBSD, DesktopBSD, pfSense и других. PF был даже портирован на Microsoft Windows.

Установка

Чтобы иметь возможность работать с PF, надо пересобирать ядро, указав в нем следующие опции:

Далее, в /etc/rc.conf надо добавить следующие строчки:

На этом с установкой мы закончили, переходим к конфигурации.

Настройка

Настройка сводится к созданию файла конфигурации /etc/pf.conf и активации PF. Здесь я приведу лишь пример настройки файрвола, где компьютер выполняет роль веб-сервера. Ознакомившись с этими правилами, будет легко написать свои… или же, на крайний случай, дополнить имеющиеся. Сначала я покажу здесь свой конфиг файл, а потом расскажу что в нем за что отвечает.

Макросы — это, своего рода, переменные, к которым можно будет дальше обращаться. Они могут содержать как одно значение (например, $ext_if), так и несколько (например, $tcp_services). В них я указываю названия сетевого интерфейса, указываю какие порты открывать для админов, а какие для всех остальных, указываю внутреннюю подсеть и мои личные компы.

В опциях первые два параметра отвечают за действия по умолчанию для правил block и включение логов для нашего сетевого интерфейса. Опция set skip on lo означает, что мы отключаем фильтрацию на loopback интерфейсе. Опция scrub in отвечает за «нормализацию» пакетов, что позволяет предотвратить некоторые атаки на компьютер и защищает от «кривых» пактов.

Далее, идут сами правила. Мы все блокируем по умолчанию на входе, но пропускаем все на выход. antispoof — как видно из названия — это защита от спуфинга. И три правила:

  1. Открываем всем порт 80 (это мои сайты)
  2. Пропускаем icmp-пакеты
  3. Открываем доступ по SSH и WWW (порт 80 и 8080) для моих компьютеров

Вот и все. Остается лишь активировать PF и загрузить в него свои правила. Делается это следующими двумя командами:

Packet filter для windows

Введение.

В данной статье даются основные сведения по способам фильтрации сетевого траффика в Windows 9x/2000/Net.2003 Server, даётся описание фильтрации IP-траффика в Windows 2000 на основе Windows 2000 Filter-Hook Driver способа.Также указываются особенности реализации других методов фильтрации.

Часть первая, теоретическая.

Способы фильтрации сетевого трафика .

Существует несколько способов фильтрации сетевого траффика .Для начала кратко рассмотрим основы сетевой подсистемы Windows:

1) NDIS. В 1989 году Microsoft и 3Com совместно разработали Network Driver Interface Specification (NDIS), которая позволяет драйверам сетевых протоколов использовать сервисы сетевых интерфейсов (отправка/прием сетевых пакетов) скрывая детали их реализации. Драйвер сетевого адаптера, разработанный в соответствии с этой спецификацией, принято называть NDIS минипортом (miniport).Одно из преимуществ — то, что код свободно переносится из 9x/ME — winNT/2000 . Детальное описание предмета можно найти в документации DDK (раздел NetworkDrivers), вкратце NDIS описывает правила (интерфейсы и структуры), в соответствии, с которыми должны разрабатываться драйвера сетевых адаптеров, а так же предоставляет библиотеку функций, к которой должен обращаться разработчик вместо прямого использования сервисов ядра.

2) Драйвера сетевых протоколов. Вкратце, драйвер сетевого протокола (такого как, например TCP/IP) для работы с сетевыми интерфейсами использует функции уже упомянутой библиотеки NDIS и может предоставлять TDI (Transport Data Interface) вышележащим уровням (TDI-клиентам, одним из типичных представителей которых в ядре NT/2000/XP является afd.sys — kernel-mode часть Windows Sockets).

Читайте также:  Драйвер для видеокарты nvidia geforce gtx 650 для windows 10 64 bit

3) User-Mode DLL’s которые формируют интерфейс WindowsSockets. Это ws2_32.dll, msafd.dll, wshtcpip.dll и другие.

Тех, кто хочет более детально рассмотреть сетевую подсистему Windows , отсылаю к David Solomon, Mark Russinovich : Inside Windows 2000, часть 13.

Технологии фильтрации:

Технологии фильтрации в User-mode автор не рассматривает.

Технологии фильтрации сетевого трафика в режиме ядра:

1) Kernel-mode sockets filter. Эта технология применима для WindowsNT/2000. Основана на перехвате всех вызовов из msafd.dll (самая низкоуровневая user-mode DLL из состава Windows Sockets) к модулю ядра afd.sys (kernel-mode часть WindowsSockets). Данная технология требует аккуратного обращения с интерфейсами AFD , т.к. они изменяются в разных версиях NT. AFD является TDI клиентом и реализует приём/отправку данных через драйвер протокола. Msafd.dll сообщает AFD название протокола для каждого сокета.Для более подробного изучения отправляю в Inside Windows 2000, раздел 13, подраздел Networking APIs.Способ бесполезен при маршрутизации, т.к. она осуществляется внутри TCPIP.SYS(иногда и вне его — поиск по DDK: Fast Forwarding Path — происходит внутри NDIS ) и не доходит до сокетов. Хотя данный способ удобен для шифрования потоков данных и QoS — Quality of Service — предоставляется специальное API (смотреть в MSDN — поиск по QOS Reference).

2) TDI-filter driver. Технология применима как в Windows 9x/ME так и в WindowsNT/2000, хотя конкретные реализации сильно отличаются. Что касается Windows NT/2000, то в случае TCP/IP фильтрации необходимо перехватывать все вызовы, направленные устройствам (devices) созданным модулем tcpip.sys (\Device\RawIp, \Device\Udp, \Device\Tcp). Технология достаточно известная и используется в ряде коммерческих продуктов (например, OutpostFirewall).

3) NDIS Intermediate Driver Способ очень неудобен в инсталляции и программировании. Желающие могут изучить DDK. Ниже приведён пример кода, показывающего громоздкость программирования :

Windows Packet Filter

Windows Packet Filter (WinpkFilter) is a high performance packet filtering framework for Windows that allows developers to transparently filter (view and modify) raw network packets at the NDIS level of the network stack with minimal impact on network activity and without having to write any low level driver code.

Windows Packet Filter includes NDIS 3.1/4 hooking VxD driver (Windows 95/ME), NDIS 4 hooking filter driver (Windows NT/2000/XP), NDIS 5 Intermediate (Windows XP/2003) and NDIS 6 Lightweight Filter (LWF) drivers as well as companion user-mode API DLL and samples.

Key advantage of Windows Packet Filter in comparison to other packet filtering frameworks for Windows (based on Windows Filtering Platform (WFP) callout drivers, Layered Service Poviders (LSP), TDI filters and etc..) is the ability to manipulate raw Ethernet frames achieved by installing driver below all network protocol drivers and just above network interface driver. Thus WinpkFilter driver has an ultimate control over all network traffic flow destined to or originated from your system and allows you modify any packet, drop it or even forge and insert a completely new one. Using Windows Packet Filter requires no experience in kernel mode programming on your behalf since it provides you with a powerful user level API. However, if you need to implement your solution (to achieve better performance) in kernel mode, you can do that as well by adding your functional code directly to Windows Packet Filter driver’s code.

System Requirements

Windows 95/98/Millennium Windows Vista Widows Server 2012
Windows NT 4.0 Windows Server 2008 Windows 8.1
Windows 2000 Windows 7 Windows Server 2012 R2
Windows XP Windows Server 2008 R2 Windows 10
Windows Server 2003 Windows 8 Windows Server 2016/2019

The following connections types are supported for the operating systems above:

  • Wired Ethernet (802.3)
  • Wi-Fi (802.11)
  • WAN (Analog/ISDN modems, PPPoE, 3G/4G mobile modems)
  • Mobile Broadband (PPIP)
Читайте также:  Драйвер для bamboo wacom ctl 470 windows 10

Product features

  • Reliability and stability confirmed by hundreds of satisfied customers since product launch in 2002 ranged from small shareware companies to world known corporations.
  • High performance. WinpkFilter allows handling Gigabit network bandwidth in user mode application without noticeable performance degradation.
  • Complete and easy portability across all Windows desktop platforms.
  • Operates on RAS/PPP adapters and supports Windows 7 Mobile Broadband stack(PPIP)
  • Passive network listening (collecting network packets) and active filtering (with capability to edit/drop network packets) modes
  • Interface for injecting raw Ethernet frames into the network stack (either destined from the TCP/IP to the network and in reversed direction)
  • Support for MTU decrement (allows setting system-wide MTU decrement). This option is useful if you plan to add additional headers to IP packets (implement IP in IP packet tunneling, IPSEC based VPN and so on).
  • Powerful built-in network filters engine allows setting rules to pass, block or redirect network packet to Windows Packet Filter based application for further processing.

Windows Packet Filter architecture

Applicability/Usage Scope

Windows Packet Filter can be used as a base for the following kinds of network applications (including but not limited to):

  • User-mode firewall and content filtering solutions. No more need to write kernel mode drivers to implement the firewall!
  • Kernel-mode firewall and content filtering solutions. This requires kernel-mode programming skills and Source Code license (to integrate your network packet processing code directly into the drivers) but provides the maximum possible performance.
  • Internet Connection Sharing (Network Address Translation) that can be implemented either in user or kernel depending on performance requirements.
  • Virtual Private Network solution (IPSEC, SSL VPN, Wireguard and etc.) that can also be implemented both in user and kernel depending on performance requirements.
  • Network packets tunneling solution. An example, packets captured from the network can be tunneled from the client to the remote system inside the SSL, SSH, HTTP, ICMP and etc., extracted by the remote host and injected into the real network (after required packet headers modifications). Response packets can be returned back to the client in the same manner. This may allow to bypass certain network access limitations.
  • Packet sniffer. You can capture and inspect all packets sent to (received from) TCP/IP.
  • IP shaping solutions (when you need to limit bandwidth for Internet users).
  • Network traffic counting and bandwidth management solutions.
  • Wireless Firewall Gateways even with HTTP authorization.
  • Transparent proxy solution based on NDIS level packet redirection. This can be used, an example, to decrypt SSL(Man-In-The-Middle), parent content control, e-mail SPAM filtering and etc…
  • Transparent filtering bridge

Downloads

You can download Windows Packet Filter driver installer (free for private or educational use) and samples binaries in order to test and evaluate the reliability and performance of our software.

The source code for Windows Packet Filter samples along with the latest NDISAPI library is available on GitHub.

Although NDISAPI library includes C++/CLI class library .NET developers can use an alternative p/Invoke C# library NDISAPI.NET

Driver packages:

Windows Packet Filter 3.2.28.1 x64.msi Windows Vista and later Download
Windows Packet Filter 3.2.28.1 x86.msi Windows Vista and later Download
Windows Packet Filter 3.2.28.1.exe Windows 95/98/ME/NT/2000/XP/2003 Download

Samples:

Basic and advanced native C++ samples binaries x64 builds Download
Basic and advanced native C++ samples binaries x86 builds Download
Basic native C++ samples binaries x86 VC++ 6.0 builds Download
Читайте также:  Указать элементы рабочего стола windows

Important notes:

  • Installed third-party firewall software may limit samples functionality.
  • Standard driver builds above limit the network MTU to 1500 bytes. It may cause performance degradation of 10 Gbps networks with Jumbo frames. Builds supporting Ethernet Jumbo frames (up to 9000 bytes) are available to licensed customers.

Windows Packet Filter Advanced Samples

  • Internet Gateway (snat.exe) is a simple MFC Internet Connection sharing application based on Windows Packet Filter. It implements a simple TCP and UDP dynamic NAT and allows sharing single Internet connection over your home network providing the major Internet services (e-mail, WWW, FTP and etc…).
  • WAN Emulator (lfnemu.exe) is a simple console application for Windows based on Windows Packet Filter. It is also known as Long Fat Network (LFN) Emulator which primary task is simulating Long Fat Network behavior over normal Local Area Network by adding packets delays and drops.
  • capture – native C++ sample, intercepts packets for the specified network interface and saves those into the PCAP file which can be opened and analyzed with WireShark.
  • dns_proxy – native C++ sample, redirects DNS protocol through the transparent UDP proxy.
  • dnstrace – native C++ sample, intercepts DNS responses and decodes their content to the console. Has configurations to link NDISAPI statically and dynamically.
  • ethernet_bridge – native C++ sample, implements bridging wired and wireless networks. More information https://www.ntkernel.com/bridging-networks-with-windows-packet-filter/
  • ipv6_parser – native C++ sample, intercepts IPv6 packets, matches to originated process (using IP Helper API) parses protocol headers.
  • sni_inspector – native C++ sample, intercepts network packets and extracts SNI from HTTPS packets and Host from HTTP packets.
  • socksify – native C++ sample, redirects selected TCP connections through a SOCKS5 proxy.
  • TestDotNet – C# sample (using .NET C++/CLI NDISAPI library) demonstrates the NDISAPI usage in several filtering scenarios.

Price & licensing

We offer two types of licenses. Each license includes one year of free updates & support and custom driver’s build*.

License type Complete Source Code Price (USD) Online Order
Developer NO 1995.00 Buy Now!
Source Code YES 4995.00 Buy Now!
Developer to Source Upgrade YES 3000.00 Buy Now!

Please be very careful when choosing the license type:

  • Developer license can be used for creating royalty free Windows Packet Filter based software. NT Kernel Resources strongly recommends you to request custom software build* from us to use for production.
  • Source Code license is similar to Developer license, but it also includes complete source code of Windows Packet Filter.

Notes:
* – You may need custom build of WinpkFilter drivers if you are going to redistribute helper drivers as a part of your software. Custom builds allow avoiding any possible conflicts with other WinpkFilter based applications. If you have purchased Developer license you can request custom build by sending e-mail to support@ntkernel.com. One custom build per license is included in Developer and Source Code subscriptions. Additional custom builds are subject of extra charge 100 USD per build.

Subscription Renewal

If you are already WinpkFilter customer, but your support plan is out-of-date, then you can renew it using the links below (please note that NT Kernel Resources may request your previous order ID and date for confirmation):

License type Complete Source Code Price (USD) Online Order
Developer Subscription Renew NO 1495.00 Buy Now!
Source Code Subscription Renew YES 3995.00 Buy Now!

Disclaimer

Windows Packet Filter software is supplied AS-IS, without warranties of any kind.

Оцените статью